From 30e4ab98db9e428c09acfa57e1af43a69a8066a1 Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 6 Sep 2021 16:42:48 +0800 Subject: [PATCH 001/135] fix: owner team can change nickname --- app/services/organizations/teams/update_service.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/services/organizations/teams/update_service.rb b/app/services/organizations/teams/update_service.rb index 275dad88..d77bba9e 100644 --- a/app/services/organizations/teams/update_service.rb +++ b/app/services/organizations/teams/update_service.rb @@ -25,7 +25,7 @@ class Organizations::Teams::UpdateService < ApplicationService private def update_params if team.authorize == "owner" - update_params = params.slice(:description) + update_params = params.slice(:description, :nickname) else update_params = params.slice(:name, :nickname, :description, :authorize, :includes_all_project, :can_create_org_project) end From 74a9743bcc95b835bb701a4286cdeafb090784ed Mon Sep 17 00:00:00 2001 From: yystopf Date: Tue, 7 Sep 2021 15:17:52 +0800 Subject: [PATCH 002/135] fix: annoymous user visit project --- app/controllers/application_controller.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 6848fffa..11ea87dd 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -762,10 +762,10 @@ class ApplicationController < ActionController::Base if @project and current_user.can_read_project?(@project) logger.info "###########: has project and can read project" @project - elsif @project && current_user.is_a?(AnonymousUser) - logger.info "###########:This is AnonymousUser" - @project = nil if !@project.is_public? - render_forbidden and return + # elsif @project && current_user.is_a?(AnonymousUser) + # logger.info "###########:This is AnonymousUser" + # @project = nil if !@project.is_public? + # render_forbidden and return else logger.info "###########:project not found" @project = nil From 84aed0391adb913d2fa08b71a12b7fe733aaced3 Mon Sep 17 00:00:00 2001 From: yystopf Date: Tue, 7 Sep 2021 17:19:38 +0800 Subject: [PATCH 003/135] fix: project list query --- app/controllers/projects_controller.rb | 2 +- app/models/project.rb | 12 ++++++++++++ app/queries/projects/list_query.rb | 7 ++++--- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index 2936b35e..6bb4c094 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -28,7 +28,7 @@ class ProjectsController < ApplicationController end def index - scope = Projects::ListQuery.call(params) + scope = current_user.logged? ? Projects::ListQuery.call(params, current_user.id) : Projects::ListQuery.call(params) # @projects = kaminari_paginate(scope) @projects = paginate scope.includes(:project_category, :project_language, :repository, :project_educoder, :owner, :project_units) diff --git a/app/models/project.rb b/app/models/project.rb index ff285f17..93d7e647 100644 --- a/app/models/project.rb +++ b/app/models/project.rb @@ -137,6 +137,18 @@ class Project < ApplicationRecord delegate :content, to: :project_detail, allow_nil: true delegate :name, to: :license, prefix: true, allow_nil: true + def self.all_visible(user_id=nil) + user_projects_sql = Project.joins(:owner).where(users: {type: 'User'}).to_sql + org_public_projects_sql = Project.joins(:owner).merge(Organization.joins(:organization_extension).where(organization_extensions: {visibility: 'common'})).to_sql + if user_id.present? + org_limit_projects_sql = Project.joins(:owner).merge(Organization.joins(:organization_extension).where(organization_extensions: {visibility: 'limited'})).to_sql + org_privacy_projects_sql = Project.joins(:owner).merge(Organization.joins(:organization_extension, :organization_users).where(organization_extensions: {visibility: 'privacy'}, organization_users: {user_id: user_id})).to_sql + return Project.from("( #{ user_projects_sql } UNION #{ org_public_projects_sql } UNION #{ org_limit_projects_sql } UNION #{org_privacy_projects_sql} ) AS projects").visible + else + return Project.from("( #{ user_projects_sql } UNION #{ org_public_projects_sql } ) AS projects").visible + end + end + def reset_cache_data if changes[:user_id].present? first_owner = Owner.find_by_id(changes[:user_id].first) diff --git a/app/queries/projects/list_query.rb b/app/queries/projects/list_query.rb index 04f1d168..771d4c92 100644 --- a/app/queries/projects/list_query.rb +++ b/app/queries/projects/list_query.rb @@ -1,16 +1,17 @@ class Projects::ListQuery < ApplicationQuery include CustomSortable - attr_reader :params + attr_reader :params, :current_user_id sort_columns :updated_on, :created_on, :forked_count, :praises_count, default_by: :updated_on, default_direction: :desc - def initialize(params) + def initialize(params, current_user_id=nil) @params = params + @current_user_id = current_user_id end def call - q = Project.visible.by_name_or_identifier(params[:search]) + q = Project.all_visible(current_user_id).by_name_or_identifier(params[:search]) scope = q .with_project_type(params[:project_type]) From b0d22b3053b856392e6d354b8adb7fdc4648f580 Mon Sep 17 00:00:00 2001 From: jasder Date: Wed, 8 Sep 2021 15:34:53 +0800 Subject: [PATCH 004/135] =?UTF-8?q?FIX=20=E8=A7=A3=E5=86=B3=E4=B8=AA?= =?UTF-8?q?=E4=BA=BA=E4=B8=BB=E9=A1=B5=E5=9B=A0=E7=94=A8=E6=88=B7=E4=BF=A1?= =?UTF-8?q?=E6=81=AF=E7=BC=BA=E9=99=B7=E5=AF=BC=E8=87=B4=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E6=8A=A5=E9=94=99=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controllers/users/headmaps_controller.rb | 2 +- app/controllers/users/statistics_controller.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/controllers/users/headmaps_controller.rb b/app/controllers/users/headmaps_controller.rb index 81bd5771..7c88b568 100644 --- a/app/controllers/users/headmaps_controller.rb +++ b/app/controllers/users/headmaps_controller.rb @@ -1,7 +1,7 @@ class Users::HeadmapsController < Users::BaseController def index result = Gitea::User::HeadmapService.call(observed_user.login, start_stamp, end_stamp) - @headmaps = result[2] + @headmaps = result[2].blank? ? [] : result[2] rescue Exception => e uid_logger_error(e.message) tip_exception(e.message) diff --git a/app/controllers/users/statistics_controller.rb b/app/controllers/users/statistics_controller.rb index c6cc0d88..592a8be9 100644 --- a/app/controllers/users/statistics_controller.rb +++ b/app/controllers/users/statistics_controller.rb @@ -14,7 +14,7 @@ class Users::StatisticsController < Users::BaseController @date_data << date.strftime("%Y.%m.%d") @issue_data << observed_user.issues.where("DATE(created_on) = ?", date).size @pull_request_data << observed_user.pull_requests.where("DATE(created_at) = ?", date).size - date_commit_data = commit_data.select{|item| item["timestamp"] == date.to_time.to_i} + 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) end render :json => {dates: @date_data, issues_count: @issue_data, pull_requests_count: @pull_request_data, commits_count: @commit_data} From d5de6aa66b8697b56f7fd4ba00e2bc80e4af1bda Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 8 Sep 2021 18:16:02 +0800 Subject: [PATCH 005/135] fix: transfer repository owner complete not include organization --- app/services/projects/apply_transfer_service.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/services/projects/apply_transfer_service.rb b/app/services/projects/apply_transfer_service.rb index 0d9d41e7..2953cd3d 100644 --- a/app/services/projects/apply_transfer_service.rb +++ b/app/services/projects/apply_transfer_service.rb @@ -24,7 +24,7 @@ class Projects::ApplyTransferService < ApplicationService raise Error, '仓库标识不正确' if @project.identifier != params[:identifier] raise Error, '该仓库正在迁移' if @project.is_transfering raise Error, '新拥有者不存在' unless @owner.present? - raise Error, '新拥有者资料不完善' unless @owner.profile_completed + raise Error, '新拥有者资料不完善' if @owner.is_a?(User) && !@owner.profile_completed raise Error, '新拥有者已经存在同名仓库!' if Project.where(user_id: @owner.id, identifier: params[:identifier]).present? raise Error, '未拥有转移权限' unless is_permit_owner end From 67d4544d6b6f21fbf84a0c533d836556120b35ff Mon Sep 17 00:00:00 2001 From: jasder Date: Thu, 9 Sep 2021 13:50:31 +0800 Subject: [PATCH 006/135] FIX delete some mandatory field with projects list api --- api_document.md | 10 +++++----- app/controllers/projects_controller.rb | 1 - app/forms/base_form.rb | 10 ++++++++-- app/forms/projects/create_form.rb | 3 +-- app/services/gitea/repository/create_service.rb | 4 ++-- app/services/projects/create_service.rb | 2 +- 6 files changed, 17 insertions(+), 13 deletions(-) diff --git a/api_document.md b/api_document.md index 7620c42a..ddb79195 100644 --- a/api_document.md +++ b/api_document.md @@ -338,10 +338,10 @@ http://localhost:3000/api/projects/ | jq |-|-|-|-| |user_id |是|int |用户id或者组织id | |name |是|string |项目名称 | -|description |是|string |项目描述 | +|description |否|string |项目描述 | |repository_name |是|string |仓库名称, 只含有数字、字母、下划线不能以下划线开头和结尾,且唯一 | -|project_category_id|是|int |项目类别id | -|project_language_id|是|int |项目语言id | +|project_category_id|否|int |项目类别id | +|project_language_id|否|int |项目语言id | |ignore_id |否|int |gitignore相关id | |license_id |否|int |开源许可证id | |private |否|boolean|项目是否私有, true:为私有,false: 公开,默认为公开 | @@ -388,8 +388,8 @@ http://localhost:3000/api/projects/migrate.json | jq |clone_addr |是|string |镜像项目clone地址 | |description |否|string |项目描述 | |repository_name |是|string |仓库名称, 只含有数字、字母、下划线不能以下划线开头和结尾,且唯一 | -|project_category_id|是|int |项目类别id | -|project_language_id|是|int |项目语言id | +|project_category_id|否|int |项目类别id | +|project_language_id|否|int |项目语言id | |is_mirror |否|boolean|是否设置为镜像, true:是, false:否,默认为否 | |auth_username |否|string|镜像源仓库的登录用户名 | |auth_password |否|string|镜像源仓库的登录秘密 | diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index 2936b35e..bdc96e90 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -46,7 +46,6 @@ class ProjectsController < ApplicationController def create ActiveRecord::Base.transaction do - tip_exception("无法使用以下关键词:#{project_params[:repository_name]},请重新命名") if ReversedKeyword.is_reversed(project_params[:repository_name]).present? Projects::CreateForm.new(project_params).validate! @project = Projects::CreateService.new(current_user, project_params).call diff --git a/app/forms/base_form.rb b/app/forms/base_form.rb index 015332d8..1f601490 100644 --- a/app/forms/base_form.rb +++ b/app/forms/base_form.rb @@ -2,18 +2,24 @@ class BaseForm include ActiveModel::Model def check_project_category(project_category_id) - raise "project_category_id参数值无效." if (ProjectCategory.find_by_id project_category_id).blank? + raise "project_category_id参数值无效." if project_category_id && !ProjectCategory.exists?(project_category_id) end def check_project_language(project_language_id) - raise "project_language_id参数值无效." if (ProjectLanguage.find_by_id project_language_id).blank? + raise "project_language_id参数值无效." if project_language_id && !ProjectLanguage.exists?(project_language_id) end def check_repository_name(user_id, repository_name) + check_reversed_keyword(repository_name) raise "仓库名称已被使用." if Repository.where(user_id: user_id, identifier: repository_name.strip).exists? end def check_project_name(user_id, project_name) raise "项目名称已被使用." if Project.where(user_id: user_id, name: project_name.strip).exists? end + + def check_reversed_keyword(repository_name) + raise "仓库名称已被使用." if ReversedKeyword.is_reversed(repository_name).exists? + end + end diff --git a/app/forms/projects/create_form.rb b/app/forms/projects/create_form.rb index 8265f323..7014da2b 100644 --- a/app/forms/projects/create_form.rb +++ b/app/forms/projects/create_form.rb @@ -3,8 +3,7 @@ class Projects::CreateForm < BaseForm attr_accessor :user_id, :name, :description, :repository_name, :project_category_id, :project_language_id, :ignore_id, :license_id, :private, :owner - validates :user_id, :name, :description,:repository_name, - :project_category_id, :project_language_id, presence: true + validates :user_id, :name, :repository_name, presence: true validates :repository_name, format: { with: REPOSITORY_NAME_REGEX, multiline: true, message: "只能含有数字、字母、下划线且不能以下划线开头和结尾" } validates :name, length: { maximum: 50 } diff --git a/app/services/gitea/repository/create_service.rb b/app/services/gitea/repository/create_service.rb index 168aaab2..98a28303 100644 --- a/app/services/gitea/repository/create_service.rb +++ b/app/services/gitea/repository/create_service.rb @@ -25,8 +25,8 @@ class Gitea::Repository::CreateService < Gitea::ClientService private def request_params - create_params = params.merge(readme: "readme") - Hash.new.merge(token: token, data: create_params) + # create_params = params.merge(readme: "readme") + Hash.new.merge(token: token, data: params) end def url diff --git a/app/services/projects/create_service.rb b/app/services/projects/create_service.rb index e7e4924a..72ad8f16 100644 --- a/app/services/projects/create_service.rb +++ b/app/services/projects/create_service.rb @@ -43,7 +43,7 @@ class Projects::CreateService < ApplicationService ignore_id: params[:ignore_id], license_id: params[:license_id], website: params[:website], - identifier: params[:repository_name] #新增,hs + identifier: params[:repository_name] } end From e38539445d97cd2605805cd451b8268a8e97c27c Mon Sep 17 00:00:00 2001 From: jasder Date: Thu, 9 Sep 2021 14:34:29 +0800 Subject: [PATCH 007/135] FIX delete some mandatory field with migrate repo api --- api_document.md | 4 +--- app/controllers/projects_controller.rb | 1 - app/forms/base_form.rb | 2 +- app/forms/projects/create_form.rb | 3 +-- app/forms/projects/migrate_form.rb | 11 ++++------- app/libs/custom_regexp.rb | 4 ++++ app/services/repositories/migrate_service.rb | 2 +- 7 files changed, 12 insertions(+), 15 deletions(-) diff --git a/api_document.md b/api_document.md index ddb79195..8a579f8e 100644 --- a/api_document.md +++ b/api_document.md @@ -374,9 +374,7 @@ curl -X POST \ -d "user_id=36408" \ -d "clone_addr=https://gitea.com/mx8090alex/golden.git" \ -d "name=golden_mirror1" \ --d "description=golden_mirror" \ --d "project_category_id=1" \ --d "project_language_id=2" \ +-d "repository_name=golden_mirror1" \ http://localhost:3000/api/projects/migrate.json | jq ``` *请求参数说明:* diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index bdc96e90..9b390969 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -56,7 +56,6 @@ class ProjectsController < ApplicationController end def migrate - tip_exception("无法使用以下关键词:#{mirror_params[:repository_name]},请重新命名") if ReversedKeyword.is_reversed(mirror_params[:repository_name]).present? Projects::MigrateForm.new(mirror_params).validate! @project = diff --git a/app/forms/base_form.rb b/app/forms/base_form.rb index 1f601490..a939b199 100644 --- a/app/forms/base_form.rb +++ b/app/forms/base_form.rb @@ -19,7 +19,7 @@ class BaseForm end def check_reversed_keyword(repository_name) - raise "仓库名称已被使用." if ReversedKeyword.is_reversed(repository_name).exists? + raise "仓库名称已被占用." if ReversedKeyword.is_reversed(repository_name).exists? end end diff --git a/app/forms/projects/create_form.rb b/app/forms/projects/create_form.rb index 7014da2b..a45da1a8 100644 --- a/app/forms/projects/create_form.rb +++ b/app/forms/projects/create_form.rb @@ -1,10 +1,9 @@ class Projects::CreateForm < BaseForm - REPOSITORY_NAME_REGEX = /^(?!_)(?!.*?_$)[a-zA-Z0-9_-]+$/ #只含有数字、字母、下划线不能以下划线开头和结尾 attr_accessor :user_id, :name, :description, :repository_name, :project_category_id, :project_language_id, :ignore_id, :license_id, :private, :owner validates :user_id, :name, :repository_name, presence: true - validates :repository_name, format: { with: REPOSITORY_NAME_REGEX, multiline: true, message: "只能含有数字、字母、下划线且不能以下划线开头和结尾" } + validates :repository_name, format: { with: CustomRegexp::REPOSITORY_NAME_REGEX, multiline: true, message: "只能含有数字、字母、下划线且不能以下划线开头和结尾" } validates :name, length: { maximum: 50 } validates :repository_name, length: { maximum: 100 } diff --git a/app/forms/projects/migrate_form.rb b/app/forms/projects/migrate_form.rb index 51116b2b..13a3af2c 100644 --- a/app/forms/projects/migrate_form.rb +++ b/app/forms/projects/migrate_form.rb @@ -1,12 +1,9 @@ class Projects::MigrateForm < BaseForm - REPOSITORY_NAME_REGEX = /^(?!_)(?!.*?_$)[a-zA-Z0-9_-]+$/ #只含有数字、字母、下划线不能以下划线开头和结尾 - URL_REGEX = /\A(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?\z/i + attr_accessor :user_id, :name, :repository_name, :project_category_id, :project_language_id, :clone_addr, :private, :is_mirror, :auth_username, :auth_password, :owner - attr_accessor :user_id, :name, :description, :repository_name, :project_category_id, :project_language_id, :clone_addr, :private, :is_mirror, :auth_username, :auth_password, :owner - - validates :user_id, :name, :description,:repository_name, :project_category_id, :project_language_id, presence: true - validates :repository_name, format: { with: REPOSITORY_NAME_REGEX, multiline: true, message: "只能含有数字、字母、下划线且不能以下划线开头和结尾" } - validates :clone_addr, format: { with: URL_REGEX, multiline: true, message: "地址格式不正确" } + validates :user_id, :name, :repository_name, :clone_addr, presence: true + validates :repository_name, format: { with: CustomRegexp::REPOSITORY_NAME_REGEX, multiline: true, message: "只能含有数字、字母、下划线且不能以下划线开头和结尾" } + validates :clone_addr, format: { with: CustomRegexp::URL_REGEX, multiline: true, message: "地址格式不正确" } validate do check_project_name(user_id, name) unless name.blank? check_repository_name(user_id, repository_name) unless repository_name.blank? diff --git a/app/libs/custom_regexp.rb b/app/libs/custom_regexp.rb index 4aa6fac2..c7b5e7a1 100644 --- a/app/libs/custom_regexp.rb +++ b/app/libs/custom_regexp.rb @@ -6,4 +6,8 @@ module CustomRegexp PASSWORD = /\A[a-z_A-Z0-9\-\.!@#\$%\\\^&\*\)\(\+=\{\}\[\]\/",'_<>~\·`\?:;|]{8,16}\z/ URL = /\Ahttps?:\/\/[-A-Za-z0-9+&@#\/%?=~_|!:,.;]+[-A-Za-z0-9+&@#\/%=~_|]\z/ IP = /^((\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$/ + + URL_REGEX = /\A(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?\z/i + REPOSITORY_NAME_REGEX = /^(?!_)(?!.*?_$)[a-zA-Z0-9_-]+$/ #只含有数字、字母、下划线不能以下划线开头和结尾 + end diff --git a/app/services/repositories/migrate_service.rb b/app/services/repositories/migrate_service.rb index 2870faba..cccfaed0 100644 --- a/app/services/repositories/migrate_service.rb +++ b/app/services/repositories/migrate_service.rb @@ -32,7 +32,7 @@ class Repositories::MigrateService < ApplicationService private: params[:hidden], mirror: wrapper_mirror || false, auth_username: params[:login], - auth_password: Base64.decode64(params[:password]) + auth_password: Base64.decode64(params[:password] || "") } end From f5ffd978ac7ddddf5f26a976cc71ff68ec41aebe Mon Sep 17 00:00:00 2001 From: jasder Date: Thu, 9 Sep 2021 14:35:26 +0800 Subject: [PATCH 008/135] FIX delete some file --- app/controllers/concerns/laboratory_helper.rb | 2 +- lib/gitcheck/myshixun_update.txt | 0 lib/gitcheck/myshixun_update_error.txt | 0 lib/gitcheck/readme_test.txt | 51 ------------- lib/gitcheck/shixun_update_error.txt | 72 ------------------- 5 files changed, 1 insertion(+), 124 deletions(-) delete mode 100644 lib/gitcheck/myshixun_update.txt delete mode 100644 lib/gitcheck/myshixun_update_error.txt delete mode 100644 lib/gitcheck/readme_test.txt delete mode 100644 lib/gitcheck/shixun_update_error.txt diff --git a/app/controllers/concerns/laboratory_helper.rb b/app/controllers/concerns/laboratory_helper.rb index b231b848..ea6e0055 100644 --- a/app/controllers/concerns/laboratory_helper.rb +++ b/app/controllers/concerns/laboratory_helper.rb @@ -41,7 +41,7 @@ module LaboratoryHelper my_courses: "https://www.trustie.net/users/#{current_user.try(:login)}/user_courselist", my_projects: "/users/#{current_user.try(:login)}/projects", my_organ: "https://www.trustie.net/users/#{current_user.try(:login)}/user_organizations", - default_url: "https://www.trustie.net/", + default_url: Rails.application.config_for(:configuration)['platform_url'], tiding_url: "https://www.trustie.net/users/#{current_user.try(:login)}/user_messages", register_url: "https://www.trustie.net/login?login=false" } diff --git a/lib/gitcheck/myshixun_update.txt b/lib/gitcheck/myshixun_update.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/lib/gitcheck/myshixun_update_error.txt b/lib/gitcheck/myshixun_update_error.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/lib/gitcheck/readme_test.txt b/lib/gitcheck/readme_test.txt deleted file mode 100644 index 317af632..00000000 --- a/lib/gitcheck/readme_test.txt +++ /dev/null @@ -1,51 +0,0 @@ -# 新版Git测试说明 -统一: -参考实训:http://47.96.87.25:48080/shixuns/ca9fvobr/repository -请求方式:POST -参数{repo_path: "educoder/ca9fvobr.git"} -公共方法: -['add_repository', 'fork_repository', 'delete_repository', 'file_tree', 'update_file', - 'file_content', 'commits'] - -1、仓库目录接口 - 测试方法:模拟1000个用户同时去访问接口,访问方式 - http://121.199.19.206:9000/api/file_tree - 参数: - {repo_path: "educoder/ca9fvobr.git", path: ''} // 如:{path: 'step1'} - -2、创建版本库 - 访问地址:http://121.199.19.206:9000/api/add_repository - 参数: - {repo_path: 比如:"Hjqreturn/aaass1.git"} - -3、fork版本库 - http://121.199.19.206:9000/api/fork_repository - 参数: - {repo_path: 'Hjqreturn/aaass1.git', fork_repository_path: 'educoder/ca9fvobr.git'} - 说明:fork_repository_path是新项目的repo_path, repo_path是源项目的 - - -4、更新文件 - 测试方法: - 1、更新同一个文件,并发量可以不用很大,可以用同一个用户并发10-100 - 2、更新不同的文件:可以依据创建的版本库去更新 - 访问地址:http://121.199.19.206:9000/api/update_file - 参数: - {repo_path: "educoder/ca9fvobr.git", - file_path: 'step1/main.py', - message: 'commit by test', - content: 'afdjadsjfj1111', - author_name: 'guange', - author_email: '8863824@gmil.com'} - -5、获取文件内容 - 访问地址:http://121.199.19.206:9000/api/file_content - 参数: - {repo_path: "educoder/ca9fvobr.git", path: 'step1/main.py',} - -6、获取提交记录 - 访问地址:http://121.199.19.206:9000/api/commits - 参数: - {repo_path: 比如:"educoder/ca9fvobr.git"} - - diff --git a/lib/gitcheck/shixun_update_error.txt b/lib/gitcheck/shixun_update_error.txt deleted file mode 100644 index ef9663c4..00000000 --- a/lib/gitcheck/shixun_update_error.txt +++ /dev/null @@ -1,72 +0,0 @@ -mbtclufr -9op3hs4j -96ctv7yr -rtmzxfke -ofqxthrf -czu9w4gj -9fpzj6et -pwhc865b -maozpx4l -y5wh2ofx -b5rzhpf3 -bs243nrl -47fn2yfb -kwotfxey -w5468sbp -fyekprio -q6ze5fih -b5hjq9zm -ky8pbqux -53phc7nq -b9j2yuix -9t3uphwk -iokm8ah2 -qlsy6xb4 -345bqhfi -v728fqia -4euftvf2 -f23sef5m -nhqis8m9 -qp72tb5x -gt3anszw -tng6heyf -nb9keawo -elgnbkp9 -4neslomg -lh35s6ma -xmc4rpay -qrpaxi6b -9fla2zry -efuibzrm -fzp3iu4w -pligsyn8 -glbksr29 -kfm7ghyc -p6hk3svf -p539gjhm -am5o73er -4x3qwrbe -fqosyl8g -of5z3fci -tb7hw62n -ie6zxg7r -4q2bmy9h -fpm3u5yb -nikx3ojt -vt82s9bq -ma59fefo -lxa39tfq -4gnockxf -nxwg84ey -fmie8nzb -w5nsr24v -4hn3efwc -h9ljfbq7 -nuv54t8b -2te9fmfq -vihnsayz -qhlyn82s -vw74kmfr -vcta36bz -henz425l -g529v38z From 36adfcf016faf599ba50eeac7e6fc5873980b55a Mon Sep 17 00:00:00 2001 From: jasder Date: Thu, 9 Sep 2021 17:34:09 +0800 Subject: [PATCH 009/135] =?UTF-8?q?FIX=20=E6=95=B4=E7=90=86=E5=90=8E?= =?UTF-8?q?=E5=8F=B0=E7=AE=A1=E7=90=86=E7=9B=B8=E5=85=B3=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .merge_file_a17580 | 529 ------------------ app/views/admins/laboratories/index.html.erb | 2 +- .../shared/_laboratory_item.html.erb | 38 +- .../admins/laboratories/shared/_list.html.erb | 3 - .../admins/laboratory_settings/show.html.erb | 8 +- .../admins/reversed_keywords/index.html.erb | 4 + app/views/admins/shared/_sidebar.html.erb | 3 +- 7 files changed, 17 insertions(+), 570 deletions(-) delete mode 100644 .merge_file_a17580 diff --git a/.merge_file_a17580 b/.merge_file_a17580 deleted file mode 100644 index 47e47176..00000000 --- a/.merge_file_a17580 +++ /dev/null @@ -1,529 +0,0 @@ -import React, {Component} from 'react'; -import logo from './logo.svg'; -import './App.css'; -import {LocaleProvider} from 'antd' -import zhCN from 'antd/lib/locale-provider/zh_CN'; -import { - BrowserRouter as Router, - Route, - Switch -} from 'react-router-dom'; -import axios from 'axios'; -import '@icedesign/base/dist/ICEDesignBase.css'; - -import '@icedesign/base/index.scss'; - -import LoginDialog from './modules/login/LoginDialog'; -import Notcompletedysl from './modules/user/Notcompletedysl'; -import Trialapplicationysl from './modules/login/Trialapplicationysl'; -import Trialapplicationreview from './modules/user/Trialapplicationreview'; -import Addcourses from "./modules/courses/coursesPublic/Addcourses"; -import AccountProfile from"./modules/user/AccountProfile"; - - -import Trialapplication from './modules/login/Trialapplication' - -import NotFoundPage from './NotFoundPage' - -import Loading from './Loading' - -import Loadable from 'react-loadable'; - - -import moment from 'moment' - -import {MuiThemeProvider, createMuiTheme} from 'material-ui/styles'; - -// import './AppConfig' - -import history from './history'; - -import {SnackbarHOC} from 'educoder' -import {initAxiosInterceptors} from './AppConfig' - - -// !!!tpi需要这个来加载css -import {TPMIndexHOC} from './modules/tpm/TPMIndexHOC'; - - -const theme = createMuiTheme({ - palette: { - primary: { - main: '#4CACFF', - contrastText: 'rgba(255, 255, 255, 0.87)' - }, - secondary: {main: '#4CACFF'}, // #11cb5f This is just green.A700 as hex. - }, -}); -// -// const Trialapplication= Loadable({ -// loader: () =>import('./modules/login/Trialapplication'), -// loading:Loading, -// }) -//登入 -const EducoderLogin = Loadable({ - loader: () => import('./modules/login/EducoderLogin'), - loading: Loading, -}) -const TestIndex = Loadable({ - loader: () => import('./modules/test'), - loading: Loading, -}) - -const IndexWrapperComponent = Loadable({ - loader: () => import('./modules/page/IndexWrapper'), - loading: Loading, -}) - -const CommentComponent = Loadable({ - loader: () => import('./modules/comment/CommentContainer'), - loading: Loading, -}) - -const TestMaterialDesignComponent = Loadable({ - loader: () => import('./modules/test/md/TestMaterialDesign'), - loading: Loading, -}) -const TestCodeMirrorComponent = Loadable({ - loader: () => import('./modules/test/codemirror/TestCodeMirror'), - loading: Loading, -}) - -const TestComponent = Loadable({ - loader: () => import('./modules/test/TestRC'), - loading: Loading, -}) -const TestUrlQueryComponent = Loadable({ - loader: () => import('./modules/test/urlquery/TestUrlQuery'), - loading: Loading, -}) - -const TPMIndexComponent = Loadable({ - loader: () => import('./modules/tpm/TPMIndex'), - loading: Loading, -}) -const TPMShixunsIndexComponent = Loadable({ - loader: () => import('./modules/tpm/shixuns/ShixunsIndex'), - loading: Loading, -}) - -//实训课程(原实训路径) -const ShixunPaths = Loadable({ - loader: () => import('./modules/paths/Index'), - loading: Loading, -}) - -//在线课堂 -const CoursesIndex = Loadable({ - loader: () => import('./modules/courses/Index'), - loading: Loading, -}) -const SearchPage = Loadable({ - loader: () => import('./search/SearchPage'), - loading: Loading, -}) - -//教学案例 -const MoopCases = Loadable({ - loader: () => import('./modules/moop_cases/index'), - loading: Loading, -}) - -// 课堂讨论 -// const BoardIndex = Loadable({ -// loader: () => import('./modules/courses/boards/BoardIndex'), -// loading:Loading, -// }) - -// //课堂普通作业&分组作业 -// const CoursesWorkIndex = Loadable({ -// loader: () => import('./modules/courses/busyWork/Index'), -// loading:Loading, -// }) -// - -// const TPMShixunchildIndexComponent = Loadable({ -// loader: () => import('./modules/tpm/shixunchild/ShixunChildIndex'), -// loading: Loading, -// }) - - -// const TPMshixunfork_listIndexComponent = Loadable({ -// loader: () => import('./modules/tpm/shixunchild/Shixunfork_list'), -// loading: Loading, -// }) - - -const ForumsIndexComponent = Loadable({ - loader: () => import('./modules/forums/ForumsIndex'), - loading: Loading, -}) - -// trustie plus forum -// const TPForumsIndexComponent = Loadable({ -// loader: () => import('./modules/tp-forums/TPForumsIndex'), -// loading: Loading, -// }) - - -// const TestPageComponent = Loadable({ -// loader: () => import('./modules/page/Index'), -// loading: Loading, -// }) - - -//新建实训 -const Newshixuns = Loadable({ - loader: () => import('./modules/tpm/newshixuns/Newshixuns'), - loading: Loading, -}) - - -//实训首页 -const ShixunsHome = Loadable({ - loader: () => import('./modules/home/shixunsHome'), - loading: Loading, -}) - - -const CompatibilityPageLoadable = Loadable({ - loader: () => import('./modules/common/CompatibilityPage'), - loading: Loading, -}) - -//403页面 -const Shixunauthority = Loadable({ - loader: () => import('./modules/403/Shixunauthority'), - loading: Loading, -}) - - -//404页面 -const Shixunnopage = Loadable({ - loader: () => import('./modules/404/Shixunnopage'), - loading: Loading, -}) - -//500页面 -const http500 = Loadable({ - loader: () => import('./modules/500/http500'), - loading: Loading, -}) - -// 登录注册 -const LoginRegisterPage = Loadable({ - loader: () => import('./modules/user/LoginRegisterPage'), - loading: Loading, -}) -const AccountPage = Loadable({ - loader: () => import('./modules/user/AccountPage'), - loading: Loading, -}) - -// 个人主页 -const UsersInfo = Loadable({ - loader: () => import('./modules/user/usersInfo/Infos'), - loading: Loading, -}) - -// 兴趣页面 -const Interestpage = Loadable({ - loader: () => import('./modules/login/EducoderInteresse'), - loading: Loading, -}) - -//众包创新 -const ProjectPackages=Loadable({ - loader: () => import('./modules/projectPackages/ProjectPackageIndex'), - loading: Loading, -}) - -class App extends Component { - constructor(props) { - super(props) - // this.state = { - // isRenders:false, - // } - - } - - componentDidMount() { - // force an update if the URL changes - history.listen(() => { - this.forceUpdate() - const $ = window.$ - // https://www.trustie.net/issues/21919 可能会有问题 - $("html").animate({ scrollTop: $('html').scrollTop() - 0 }) - }); - - initAxiosInterceptors(this.props) - - // - // axios.interceptors.response.use((response) => { - // // console.log("response"+response); - // if(response!=undefined) - // // console.log("response"+response.data.statu); - // if (response&&response.data.status === 407) { - // this.setState({ - // isRenders: true, - // }) - // } - // return response; - // }, (error) => { - // //TODO 这里如果样式变了会出现css不加载的情况 - // }); - } - //修改登录方法 - Modifyloginvalue=()=>{ - this.setState({ - isRender:false, - }) - } - - render() { - - - return ( - - - - - this.Modifyloginvalue()}> - - - - - - {/*{*/} - {/* isRender === true?*/} - {/* : ""*/} - {/*}*/} - - {/*{*/} - {/* isRenders === true?*/} - {/**/} - {/*:""*/} - {/*}*/} - - - - {/**/} - - {/*众包创新*/} - - {/*认证*/} - - - {/*403*/} - - - - - {/*404*/} - - - - - - () - }> - {/**/} - - - - - - - - - - - - {/*列表页*/} - - - {/* - - - */} - - {/**/} - {/**/} - - - {/*实训课程(原实训路径)*/} - - - () - } - > - - {/*课堂*/} - - - {/* 课堂讨论 */} - {/* */} - - {/* - */} - - {/* */} - {/* 兴趣页面*/} - {/**/} - - - - - - - - - {/* 教学案例 */} - () - }/> - - {/* */} - {/*列表页*/} - {/**/} - {/*首页*/} - - - - {/**/} - - - - - - ); - } -} - -// moment国际化,设置为中文 -moment.defineLocale('zh-cn', { - months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), - monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), - weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), - weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'), - weekdaysMin: '日_一_二_三_四_五_六'.split('_'), - longDateFormat: { - LT: 'Ah点mm分', - LTS: 'Ah点m分s秒', - L: 'YYYY-MM-DD', - LL: 'YYYY年MMMD日', - LLL: 'YYYY年MMMD日Ah点mm分', - LLLL: 'YYYY年MMMD日ddddAh点mm分', - l: 'YYYY-MM-DD', - ll: 'YYYY年MMMD日', - lll: 'YYYY年MMMD日Ah点mm分', - llll: 'YYYY年MMMD日ddddAh点mm分' - }, - meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, - meridiemHour: function (hour, meridiem) { - if (hour === 12) { - hour = 0; - } - if (meridiem === '凌晨' || meridiem === '早上' || - meridiem === '上午') { - return hour; - } else if (meridiem === '下午' || meridiem === '晚上') { - return hour + 12; - } else { - // '中午' - return hour >= 11 ? hour : hour + 12; - } - }, - meridiem: function (hour, minute, isLower) { - var hm = hour * 100 + minute; - if (hm < 600) { - return '凌晨'; - } else if (hm < 900) { - return '早上'; - } else if (hm < 1130) { - return '上午'; - } else if (hm < 1230) { - return '中午'; - } else if (hm < 1800) { - return '下午'; - } else { - return '晚上'; - } - }, - calendar: { - sameDay: function () { - return this.minutes() === 0 ? '[今天]Ah[点整]' : '[今天]LT'; - }, - nextDay: function () { - return this.minutes() === 0 ? '[明天]Ah[点整]' : '[明天]LT'; - }, - lastDay: function () { - return this.minutes() === 0 ? '[昨天]Ah[点整]' : '[昨天]LT'; - }, - nextWeek: function () { - var startOfWeek, prefix; - startOfWeek = moment().startOf('week'); - prefix = this.unix() - startOfWeek.unix() >= 7 * 24 * 3600 ? '[下]' : '[本]'; - return this.minutes() === 0 ? prefix + 'dddAh点整' : prefix + 'dddAh点mm'; - }, - lastWeek: function () { - var startOfWeek, prefix; - startOfWeek = moment().startOf('week'); - prefix = this.unix() < startOfWeek.unix() ? '[上]' : '[本]'; - return this.minutes() === 0 ? prefix + 'dddAh点整' : prefix + 'dddAh点mm'; - }, - sameElse: 'LL' - }, - ordinalParse: /\d{1,2}(日|月|周)/, - ordinal: function (number, period) { - switch (period) { - case 'd': - case 'D': - case 'DDD': - return number + '日'; - case 'M': - return number + '月'; - case 'w': - case 'W': - return number + '周'; - default: - return number; - } - }, - relativeTime: { - future: '%s内', - past: '%s前', - s: '几秒', - m: '1分钟', - mm: '%d分钟', - h: '1小时', - hh: '%d小时', - d: '1天', - dd: '%d天', - M: '1个月', - MM: '%d个月', - y: '1年', - yy: '%d年' - }, - week: { - // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效 - dow: 1, // Monday is the first day of the week. - doy: 4 // The week that contains Jan 4th is the first week of the year. - } -}); -export default SnackbarHOC()(App); \ No newline at end of file diff --git a/app/views/admins/laboratories/index.html.erb b/app/views/admins/laboratories/index.html.erb index 397f50cb..8811f4ab 100644 --- a/app/views/admins/laboratories/index.html.erb +++ b/app/views/admins/laboratories/index.html.erb @@ -4,7 +4,7 @@
<%= form_tag(admins_laboratories_path(unsafe_params), method: :get, class: 'form-inline search-form flex-1', remote: true) do %> - <%= text_field_tag(:keyword, params[:keyword], class: 'form-control col-6 col-md-4 ml-3', placeholder: '学校名称/二级域名前缀检索') %> + <%= text_field_tag(:keyword, params[:keyword], class: 'form-control col-6 col-md-4 ml-3', placeholder: '单位名称/二级域名前缀检索') %> <%= submit_tag('搜索', class: 'btn btn-primary ml-3', 'data-disable-with': '搜索中...') %> <% end %> diff --git a/app/views/admins/laboratories/shared/_laboratory_item.html.erb b/app/views/admins/laboratories/shared/_laboratory_item.html.erb index a121528e..b4b4921e 100644 --- a/app/views/admins/laboratories/shared/_laboratory_item.html.erb +++ b/app/views/admins/laboratories/shared/_laboratory_item.html.erb @@ -1,6 +1,6 @@ <% school = laboratory&.school %> <%= list_index_no((params[:page] || 1).to_i, index) %> -<%= school&.name || 'Trustie主站' %> +<%= school&.name || '主站' %> <% if laboratory.identifier %> <%= link_to laboratory.site, "https://#{laboratory.site}", target: '_blank' %> @@ -29,40 +29,10 @@
<%= laboratory.created_at.strftime('%Y-%m-%d %H:%M') %> - - <% if school.present? && laboratory.id != 1 %> - <%= check_box_tag :sync_course,!laboratory.sync_course,laboratory.sync_course,remote:true,data:{id:laboratory.id},class:"laboratory-sync-form" %> - <% end %> - - - <% if school.present? && laboratory.id != 1 %> - <%= check_box_tag :sync_subject,!laboratory.sync_subject,laboratory.sync_subject,remote:true,data:{id:laboratory.id},class:"laboratory-sync-form" %> - <% end %> - - - <% if school.present? && laboratory.id != 1 %> - <%= check_box_tag :sync_shixun,!laboratory.sync_shixun,laboratory.sync_shixun,remote:true,data:{id:laboratory.id},class:"laboratory-sync-form" %> - <% end %> - - <%= link_to '定制', admins_laboratory_laboratory_setting_path(laboratory), class: 'action' %> + <%= link_to '设置', admins_laboratory_laboratory_setting_path(laboratory), class: 'action' %> <% if school.present? && laboratory.id != 1 %> - <%= javascript_void_link '添加管理员', class: 'action', data: { laboratory_id: laboratory.id, toggle: 'modal', target: '.admin-add-laboratory-user-modal' } %> - <%= link_to '同步用户', synchronize_user_admins_laboratory_path(laboratory), remote: true, data: { confirm: '确认同步该单位下的所有用户到云上实验室吗?' }, class: 'action' %> -<% end %> - -
- <%= javascript_void_link('更多', class: 'action dropdown-toggle', 'data-toggle': 'dropdown', 'aria-haspopup': true, 'aria-expanded': false) %> - -
+ <%= delete_link '删除', admins_laboratory_path(laboratory, element: ".laboratory-item-#{laboratory.id}"), class: 'action' %> + <% end %> diff --git a/app/views/admins/laboratories/shared/_list.html.erb b/app/views/admins/laboratories/shared/_list.html.erb index 621ad7a4..0b646603 100644 --- a/app/views/admins/laboratories/shared/_list.html.erb +++ b/app/views/admins/laboratories/shared/_list.html.erb @@ -7,9 +7,6 @@ 统计链接 管理员 <%= sort_tag('创建时间', name: 'id', path: admins_laboratories_path) %> - 同步课堂 - 同步实践课程 - 同步实训 操作 diff --git a/app/views/admins/laboratory_settings/show.html.erb b/app/views/admins/laboratory_settings/show.html.erb index 67536af2..735f19f0 100644 --- a/app/views/admins/laboratory_settings/show.html.erb +++ b/app/views/admins/laboratory_settings/show.html.erb @@ -86,7 +86,9 @@ -
+ <% +=begin%> +
Banner设置
@@ -140,7 +142,9 @@
- + +<% +=end%>
diff --git a/app/views/admins/reversed_keywords/index.html.erb b/app/views/admins/reversed_keywords/index.html.erb index 3907b32f..a5218c9c 100644 --- a/app/views/admins/reversed_keywords/index.html.erb +++ b/app/views/admins/reversed_keywords/index.html.erb @@ -11,6 +11,10 @@ <%= link_to "新增", new_admins_reversed_keyword_path, remote: true, class: "btn btn-primary pull-right", "data-disabled-with":"...新增" %>
+
+ 旨在为特殊用户群体、特殊场景、路由而保留的关键词,如:Gitlink、Trustie等;目前主要在用户注册、创建组织、创建项目等场景下做关键词的验证. +
+
<%= render partial: 'admins/reversed_keywords/list', locals: { keywords: @keywords } %>
diff --git a/app/views/admins/shared/_sidebar.html.erb b/app/views/admins/shared/_sidebar.html.erb index cffcf658..b4959c3f 100644 --- a/app/views/admins/shared/_sidebar.html.erb +++ b/app/views/admins/shared/_sidebar.html.erb @@ -26,10 +26,11 @@
  • <%= sidebar_item(admins_project_categories_path, '分类列表', icon: 'sitemap', controller: 'admins-project_categories') %>
  • <%= sidebar_item(admins_project_licenses_path, '开源许可证', icon: 'file-text-o', controller: 'admins-project_licenses') %>
  • <%= sidebar_item(admins_project_ignores_path, '忽略文件', icon: 'git', controller: 'admins-project_ignores') %>
  • -
  • <%= sidebar_item(admins_reversed_keywords_path, '系统保留关键词', icon: 'key', controller: 'admins-reversed_keywords') %>
  • <% end %> +
  • <%= sidebar_item(admins_reversed_keywords_path, '系统保留关键词', icon: 'key', controller: 'admins-reversed_keywords') %>
  • +
  • <%= sidebar_item(admins_laboratories_path, '云上实验室', icon: 'cloud', controller: 'admins-laboratories') %>
  • From 7549557a622d4e9d1f15f637e4e8ee75fa6a12e8 Mon Sep 17 00:00:00 2001 From: jasder Date: Thu, 9 Sep 2021 18:40:53 +0800 Subject: [PATCH 010/135] =?UTF-8?q?FIX=20=E6=9B=B4=E6=94=B9hovercard?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E4=B8=AD=E7=9B=B8=E5=85=B3=E8=B7=AF=E7=94=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/views/users/hovercard.json.jbuilder | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/app/views/users/hovercard.json.jbuilder b/app/views/users/hovercard.json.jbuilder index 79f1793f..3555be23 100644 --- a/app/views/users/hovercard.json.jbuilder +++ b/app/views/users/hovercard.json.jbuilder @@ -3,18 +3,18 @@ json.login @user.login json.name @user.full_name json.location @user.location json.image_url url_to_avatar(@user) -json.url "#{request.base_url }/users/#{@user.login}" +json.url "#{request.base_url }/#{@user.login}" json.followers_count @user.followers_count -json.followers_url "#{base_url}/users/#{@user.login}/fan_users" +json.followers_url "#{base_url}/#{@user.login}/fan_users" json.following_count @user.following_count -json.following_url "#{base_url}/users/#{@user.login}/watchers" +json.following_url "#{base_url}/#{@user.login}/watchers" json.projects_count @user.projects_count -json.projects_url "#{base_url}/users/#{@user.login}" +json.projects_url "#{base_url}/#{@user.login}" json.projects_count @user.projects_count json.is_watch current_user&.watched?(@user) json.organizations @user.organizations do |organization| json.login organization.login json.name organization.real_name json.image_url url_to_avatar(organization) - json.url "#{base_url}/organize/#{organization.login}" + json.url "#{base_url}/#{organization.login}" end \ No newline at end of file From 90ace8b7533882506c4128d89dbca8afa3a238f0 Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 10 Sep 2021 10:52:21 +0800 Subject: [PATCH 011/135] fix: download file need authorize --- app/controllers/repositories_controller.rb | 11 +++++++++++ app/helpers/projects_helper.rb | 4 ++++ app/views/repositories/_simple_entry.json.jbuilder | 3 ++- config/routes.rb | 1 + 4 files changed, 18 insertions(+), 1 deletion(-) diff --git a/app/controllers/repositories_controller.rb b/app/controllers/repositories_controller.rb index 8e3f496b..9ef44090 100644 --- a/app/controllers/repositories_controller.rb +++ b/app/controllers/repositories_controller.rb @@ -205,6 +205,17 @@ class RepositoriesController < ApplicationController 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/#{params[:filepath]}?ref=#{params[:ref]}" + file_path = [domain, api_url, url].join + file_path = [file_path, "access_token=#{current_user&.gitea_token}"].join("&") if @repository.hidden? + + redirect_to file_path + end private diff --git a/app/helpers/projects_helper.rb b/app/helpers/projects_helper.rb index 8af54219..cc4a3fe0 100644 --- a/app/helpers/projects_helper.rb +++ b/app/helpers/projects_helper.rb @@ -21,6 +21,10 @@ module ProjectsHelper [base_url, archive_repositories_path(owner&.login, repository, "#{archive}.tar.gz")].join end + def render_download_file_url(owner, repository, filepath, ref) + [base_url, "/api/#{owner&.login}/#{repository.identifier}/raw?filepath=#{filepath}&ref=#{ref}"].join + end + def render_http_url(project) [gitea_domain, project.owner.login, "#{project.identifier}.git"].join('/') end diff --git a/app/views/repositories/_simple_entry.json.jbuilder b/app/views/repositories/_simple_entry.json.jbuilder index 6c208875..cc9bdc3a 100644 --- a/app/views/repositories/_simple_entry.json.jbuilder +++ b/app/views/repositories/_simple_entry.json.jbuilder @@ -17,7 +17,8 @@ if @project.forge? dir_path = [@owner.login, @repository.identifier, "raw/branch", @ref].join('/') render_download_image_url(dir_path, entry['path'], decode64_content(entry, @owner, @repository, @ref)) else - entry['download_url'] + # entry['download_url'] + render_download_file_url(@owner, @repository, entry['path'].to_s, @ref) end json.download_url download_url diff --git a/config/routes.rb b/config/routes.rb index 346468fb..2b92e939 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -434,6 +434,7 @@ Rails.application.routes.draw do get 'readme' get 'languages' get 'archive/:archive', to: 'repositories#archive', as: "archive", constraints: { archive: /.+/, format: /(zip|gzip)/ } + get 'raw', to: 'repositories#raw', as: "raw" end end From 6d581de01850f913c1a80b4ac61ae1e1c9c340cb Mon Sep 17 00:00:00 2001 From: jasder Date: Fri, 10 Sep 2021 11:13:49 +0800 Subject: [PATCH 012/135] FIX migrate project api bug --- app/forms/projects/migrate_form.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/app/forms/projects/migrate_form.rb b/app/forms/projects/migrate_form.rb index 13a3af2c..ccd85447 100644 --- a/app/forms/projects/migrate_form.rb +++ b/app/forms/projects/migrate_form.rb @@ -1,9 +1,13 @@ class Projects::MigrateForm < BaseForm - attr_accessor :user_id, :name, :repository_name, :project_category_id, :project_language_id, :clone_addr, :private, :is_mirror, :auth_username, :auth_password, :owner + attr_accessor :user_id, :name, :repository_name, :project_category_id, :description, + :project_language_id, :clone_addr, :private, :is_mirror, :auth_username, :auth_password, :owner validates :user_id, :name, :repository_name, :clone_addr, presence: true validates :repository_name, format: { with: CustomRegexp::REPOSITORY_NAME_REGEX, multiline: true, message: "只能含有数字、字母、下划线且不能以下划线开头和结尾" } validates :clone_addr, format: { with: CustomRegexp::URL_REGEX, multiline: true, message: "地址格式不正确" } + validates :name, length: { maximum: 50 } + validates :repository_name, length: { maximum: 100 } + validates :description, length: { maximum: 200 } validate do check_project_name(user_id, name) unless name.blank? check_repository_name(user_id, repository_name) unless repository_name.blank? From 02f8e453f1b22cd564ea60c17fb0ddbd400c95c1 Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 10 Sep 2021 11:26:01 +0800 Subject: [PATCH 013/135] fix: remove watcher when project change is_public --- app/models/project.rb | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/app/models/project.rb b/app/models/project.rb index 93d7e647..293e6c47 100644 --- a/app/models/project.rb +++ b/app/models/project.rb @@ -127,8 +127,8 @@ class Project < ApplicationRecord has_many :has_pinned_users, through: :pinned_projects, source: :user has_many :webhooks, class_name: "Gitea::Webhook", primary_key: :gpid, foreign_key: :repo_id - after_save :check_project_members, :reset_cache_data - before_save :set_invite_code + after_save :check_project_members + before_save :set_invite_code, :reset_cache_data, :reset_unmember_followed after_destroy :reset_cache_data scope :project_statics_select, -> {select(:id,:name, :is_public, :identifier, :status, :project_type, :user_id, :forked_count, :visits, :project_category_id, :project_language_id, :license_id, :ignore_id, :watchers_count, :created_on)} scope :no_anomory_projects, -> {where("projects.user_id is not null and projects.user_id != ?", 2)} @@ -158,6 +158,12 @@ class Project < ApplicationRecord self.reset_user_cache_async_job(self.owner) end + def reset_unmember_followed + if changes[:is_public].present? && changes[:is_public] == [true, false] + self.watchers.where.not(user_id: self.all_collaborators).destroy_all + end + end + def set_invite_code if self.invite_code.nil? self.invite_code= self.generate_dcode('invite_code', 6) From 4c41d5050620f24c0ddc33a64ac69e14b06039e4 Mon Sep 17 00:00:00 2001 From: jasder Date: Fri, 10 Sep 2021 15:29:08 +0800 Subject: [PATCH 014/135] =?UTF-8?q?ADD=20=E5=90=8E=E5=8F=B0=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F=E9=85=8D=E7=BD=AE=E7=AE=A1=E7=90=86=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../admins/edu_settings_controller.rb | 55 ++++++++++++++++++ app/controllers/admins/sites_controller.rb | 56 +++++++++++++++++++ app/controllers/edu_settings_controller.rb | 5 -- app/models/application_record.rb | 8 +++ app/models/edu_setting.rb | 34 +++++------ app/models/site.rb | 7 ++- app/queries/admins/edu_setting_query.rb | 28 ++++++++++ app/queries/admins/site_query.rb | 35 ++++++++++++ app/views/admins/edu_settings/_form.html.erb | 38 +++++++++++++ app/views/admins/edu_settings/_list.html.erb | 36 ++++++++++++ app/views/admins/edu_settings/edit.js.erb | 2 + app/views/admins/edu_settings/index.html.erb | 22 ++++++++ app/views/admins/edu_settings/index.js.erb | 1 + app/views/admins/edu_settings/new.js.erb | 2 + app/views/admins/shared/_sidebar.html.erb | 6 ++ app/views/admins/sites/_form.html.erb | 42 ++++++++++++++ app/views/admins/sites/_list.html.erb | 38 +++++++++++++ app/views/admins/sites/edit.js.erb | 2 + app/views/admins/sites/index.html.erb | 24 ++++++++ app/views/admins/sites/index.js.erb | 1 + app/views/admins/sites/new.js.erb | 2 + app/views/edu_settings/_form.html.erb | 27 --------- app/views/edu_settings/edit.html.erb | 6 -- app/views/edu_settings/index.html.erb | 30 ---------- app/views/edu_settings/new.html.erb | 5 -- app/views/edu_settings/show.html.erb | 14 ----- config/routes.rb | 2 + .../admins/edu_settings_controller_spec.rb | 47 ++++++++++++++++ .../admins/sites_controller_spec.rb | 5 ++ .../edu_settings/create.html.erb_spec.rb | 5 ++ .../edu_settings/destroy.html.erb_spec.rb | 5 ++ .../admins/edu_settings/edit.html.erb_spec.rb | 5 ++ .../edu_settings/index.html.erb_spec.rb | 5 ++ .../admins/edu_settings/new.html.erb_spec.rb | 5 ++ .../edu_settings/update.html.erb_spec.rb | 5 ++ 35 files changed, 505 insertions(+), 105 deletions(-) create mode 100644 app/controllers/admins/edu_settings_controller.rb create mode 100644 app/controllers/admins/sites_controller.rb create mode 100644 app/queries/admins/edu_setting_query.rb create mode 100644 app/queries/admins/site_query.rb create mode 100644 app/views/admins/edu_settings/_form.html.erb create mode 100644 app/views/admins/edu_settings/_list.html.erb create mode 100644 app/views/admins/edu_settings/edit.js.erb create mode 100644 app/views/admins/edu_settings/index.html.erb create mode 100644 app/views/admins/edu_settings/index.js.erb create mode 100644 app/views/admins/edu_settings/new.js.erb create mode 100644 app/views/admins/sites/_form.html.erb create mode 100644 app/views/admins/sites/_list.html.erb create mode 100644 app/views/admins/sites/edit.js.erb create mode 100644 app/views/admins/sites/index.html.erb create mode 100644 app/views/admins/sites/index.js.erb create mode 100644 app/views/admins/sites/new.js.erb delete mode 100644 app/views/edu_settings/_form.html.erb delete mode 100644 app/views/edu_settings/edit.html.erb delete mode 100644 app/views/edu_settings/index.html.erb delete mode 100644 app/views/edu_settings/new.html.erb delete mode 100644 app/views/edu_settings/show.html.erb create mode 100644 spec/controllers/admins/edu_settings_controller_spec.rb create mode 100644 spec/controllers/admins/sites_controller_spec.rb create mode 100644 spec/views/admins/edu_settings/create.html.erb_spec.rb create mode 100644 spec/views/admins/edu_settings/destroy.html.erb_spec.rb create mode 100644 spec/views/admins/edu_settings/edit.html.erb_spec.rb create mode 100644 spec/views/admins/edu_settings/index.html.erb_spec.rb create mode 100644 spec/views/admins/edu_settings/new.html.erb_spec.rb create mode 100644 spec/views/admins/edu_settings/update.html.erb_spec.rb diff --git a/app/controllers/admins/edu_settings_controller.rb b/app/controllers/admins/edu_settings_controller.rb new file mode 100644 index 00000000..9d9334b2 --- /dev/null +++ b/app/controllers/admins/edu_settings_controller.rb @@ -0,0 +1,55 @@ +class Admins::EduSettingsController < Admins::BaseController + before_action :find_setting, only: [:edit,:update, :destroy] + + def index + default_sort('id', 'desc') + + edu_settings = Admins::EduSettingQuery.call(params) + @edu_settings = paginate edu_settings + end + + def new + @edu_setting = EduSetting.new + end + + def edit + end + + def create + @edu_setting = EduSetting.new(edu_setting_params) + if @edu_setting.save + redirect_to admins_edu_settings_path + flash[:success] = '创建成功' + else + redirect_to admins_edu_settings_path + flash[:danger] = @edu_setting.errors.full_messages.join(",") + end + end + + def update + if @edu_setting.update!(edu_setting_params) + flash[:success] = '更新成功' + else + flash[:danger] = @edu_setting.errors.full_messages.join(",") + end + redirect_to admins_edu_settings_path + end + + def destroy + if @edu_setting.destroy! + flash[:success] = '删除成功' + else + lash[:danger] = '删除失败' + end + redirect_to admins_edu_settings_path + end + + private + def find_setting + @edu_setting ||= EduSetting.find(params[:id]) + end + + def edu_setting_params + params.require(:edu_setting).permit(:name, :value, :description) + end +end diff --git a/app/controllers/admins/sites_controller.rb b/app/controllers/admins/sites_controller.rb new file mode 100644 index 00000000..f3da4ccf --- /dev/null +++ b/app/controllers/admins/sites_controller.rb @@ -0,0 +1,56 @@ +class Admins::SitesController < Admins::BaseController + before_action :find_site, only: [:edit,:update, :destroy] + + def index + default_sort('id', 'desc') + + sites = Admins::SiteQuery.call(params) + @sites = paginate sites + end + + def new + @site = Site.new + end + + def edit + end + + def create + @site = Site.new(site_params) + if @site.save + redirect_to admins_sites_path + flash[:success] = '创建成功' + else + redirect_to admins_sites_path + flash[:danger] = @site.errors.full_messages.join(",") + end + end + + def update + if @site.update!(site_params) + flash[:success] = '更新成功' + else + flash[:danger] = @site.errors.full_messages.join(",") + end + redirect_to admins_sites_path + end + + def destroy + if @site.destroy! + flash[:success] = '删除成功' + else + lash[:danger] = '删除失败' + end + redirect_to admins_sites_path + end + + private + def find_site + @site ||= Site.find(params[:id]) + end + + def site_params + params.require(:site).permit(:name, :url, :key, :site_type) + end + +end diff --git a/app/controllers/edu_settings_controller.rb b/app/controllers/edu_settings_controller.rb index d3b796da..340b03dd 100644 --- a/app/controllers/edu_settings_controller.rb +++ b/app/controllers/edu_settings_controller.rb @@ -29,10 +29,8 @@ class EduSettingsController < ApplicationController respond_to do |format| if @edu_setting.save - format.html { redirect_to @edu_setting, notice: 'Edu setting was successfully created.' } format.json { render :show, status: :created, location: @edu_setting } else - format.html { render :new } format.json { render json: @edu_setting.errors, status: :unprocessable_entity } end end @@ -43,10 +41,8 @@ class EduSettingsController < ApplicationController def update respond_to do |format| if @edu_setting.update(edu_setting_params) - format.html { redirect_to @edu_setting, notice: 'Edu setting was successfully updated.' } format.json { render :show, status: :ok, location: @edu_setting } else - format.html { render :edit } format.json { render json: @edu_setting.errors, status: :unprocessable_entity } end end @@ -57,7 +53,6 @@ class EduSettingsController < ApplicationController def destroy @edu_setting.destroy respond_to do |format| - format.html { redirect_to edu_settings_url, notice: 'Edu setting was successfully destroyed.' } format.json { head :no_content } end end diff --git a/app/models/application_record.rb b/app/models/application_record.rb index 3ab2b11e..0b95d7a5 100644 --- a/app/models/application_record.rb +++ b/app/models/application_record.rb @@ -24,4 +24,12 @@ class ApplicationRecord < ActiveRecord::Base def reset_platform_cache_async_job ResetPlatformCacheJob.perform_later end + + def self.strip_param(key) + key.to_s.strip.presence + end + + def strip_param(key) + key.to_s.strip.presence + end end diff --git a/app/models/edu_setting.rb b/app/models/edu_setting.rb index 6968b008..22575ff1 100644 --- a/app/models/edu_setting.rb +++ b/app/models/edu_setting.rb @@ -1,22 +1,24 @@ -# == Schema Information -# -# Table name: edu_settings -# -# id :integer not null, primary key -# name :string(255) -# value :string(255) -# created_at :datetime not null -# updated_at :datetime not null -# description :string(255) -# -# Indexes -# -# index_edu_settings_on_name (name) UNIQUE -# - +# == Schema Information +# +# Table name: edu_settings +# +# id :integer not null, primary key +# name :string(255) +# value :string(255) +# created_at :datetime not null +# updated_at :datetime not null +# description :string(255) +# +# Indexes +# +# index_edu_settings_on_name (name) UNIQUE +# + class EduSetting < ApplicationRecord after_commit :expire_value_cache + scope :by_search, -> (keyword){ where("name LIKE :keyword OR value LIKE :keyword", keyword: "%#{strip_param(keyword)}%") unless strip_param(keyword).blank? } + def value_cache_key self.class.value_cache_key(name) end diff --git a/app/models/site.rb b/app/models/site.rb index 58daddf1..de352dcc 100644 --- a/app/models/site.rb +++ b/app/models/site.rb @@ -17,6 +17,9 @@ class Site < ApplicationRecord # common: 普通链接 enum site_type: { add: 0, personal: 1, common: 2 } + 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? } + def self.set_default_menu set_add_menu! set_personal_menu! @@ -26,8 +29,8 @@ class Site < ApplicationRecord private def self.set_add_menu! adds= [ - {name: '新建镜像项目', key: 'add_mirror_project', url: '/projects/mirror/new'}, - {name: '新建托管项目', key: 'add_common', url: '/projects/deposit/new'}, + {name: '新建项目', key: 'add_mirror_project', url: '/projects/mirror/new'}, + {name: '导入项目', key: 'add_common', url: '/projects/deposit/new'}, {name: '新建组织', key: 'add_r', url: '/organize/new'}] adds.each { |ele| diff --git a/app/queries/admins/edu_setting_query.rb b/app/queries/admins/edu_setting_query.rb new file mode 100644 index 00000000..3e61ffd3 --- /dev/null +++ b/app/queries/admins/edu_setting_query.rb @@ -0,0 +1,28 @@ +class Admins::EduSettingQuery < ApplicationQuery + include CustomSortable + + attr_reader :params + + sort_columns :id, default_by: :id, default_direction: :desc + + def initialize(params) + @params = params + end + + def call + collection = EduSetting.all + collection = filter_settings(collection) + + custom_sort collection, params[:sort_by], params[:sort_direction] + end + + def filter_settings(collection) + by_search(collection) + end + + def by_search(collection) + keyword = strip_param(:search) + collection.by_search(keyword) + end + +end \ No newline at end of file diff --git a/app/queries/admins/site_query.rb b/app/queries/admins/site_query.rb new file mode 100644 index 00000000..1d15f031 --- /dev/null +++ b/app/queries/admins/site_query.rb @@ -0,0 +1,35 @@ +class Admins::SiteQuery < ApplicationQuery + include CustomSortable + + attr_reader :params + + sort_columns :id, default_by: :id, default_direction: :desc + + def initialize(params) + @params = params + end + + def call + collection = Site.all + collection = filter_sites(collection) + + custom_sort collection, params[:sort_by], params[:sort_direction] + end + + def filter_sites(collection) + collection = by_search(collection) + collection = by_stie_type(collection) + collection + end + + def by_search(collection) + keyword = strip_param(:search) + collection.by_search(keyword) + end + + def by_stie_type(collection) + site_type = strip_param(:site_type) + collection.by_site_type(site_type) + end + +end \ No newline at end of file diff --git a/app/views/admins/edu_settings/_form.html.erb b/app/views/admins/edu_settings/_form.html.erb new file mode 100644 index 00000000..cce930f2 --- /dev/null +++ b/app/views/admins/edu_settings/_form.html.erb @@ -0,0 +1,38 @@ + \ No newline at end of file diff --git a/app/views/admins/edu_settings/_list.html.erb b/app/views/admins/edu_settings/_list.html.erb new file mode 100644 index 00000000..a37cc9be --- /dev/null +++ b/app/views/admins/edu_settings/_list.html.erb @@ -0,0 +1,36 @@ + + + + + + + + + + + + + <% if edu_settings.present? %> + <% edu_settings.each_with_index do |edu_setting, index| %> + + + + + + + + + + <% end %> + <% else %> + <%= render 'admins/shared/no_data_for_table' %> + <% end %> + +
    序号变量名变量值备注说明<%= sort_tag('创建时间', name: 'created_at', path: admins_edu_settings_path) %>操作
    <%= list_index_no((params[:page] || 1).to_i, index) %> + <%= edu_setting.name %> + <%= edu_setting.value %><%= overflow_hidden_span display_text(edu_setting.description), width: 200 %><%= edu_setting.created_at&.strftime('%Y-%m-%d %H:%M') %> + <%= link_to "编辑", edit_admins_edu_setting_path(edu_setting), remote: true, class: "action" %> + <%= link_to "删除", admins_edu_setting_path(edu_setting), method: :delete, data:{confirm: "确认删除的吗?"}, class: "action" %> +
    + +<%= render partial: 'admins/shared/paginate', locals: { objects: edu_settings } %> \ No newline at end of file diff --git a/app/views/admins/edu_settings/edit.js.erb b/app/views/admins/edu_settings/edit.js.erb new file mode 100644 index 00000000..c2e0405f --- /dev/null +++ b/app/views/admins/edu_settings/edit.js.erb @@ -0,0 +1,2 @@ +$("#edu_setting-modals").html("<%= j render(partial: 'admins/edu_settings/form', locals: {type: 'update'}) %>") +$(".edu_setting-change-modal").modal('show'); \ No newline at end of file diff --git a/app/views/admins/edu_settings/index.html.erb b/app/views/admins/edu_settings/index.html.erb new file mode 100644 index 00000000..d52480ba --- /dev/null +++ b/app/views/admins/edu_settings/index.html.erb @@ -0,0 +1,22 @@ +<% define_admin_breadcrumbs do %> + <% add_admin_breadcrumb('全局变量配置') %> +<% end %> + +
    + <%= form_tag(admins_edu_settings_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_edu_setting_path, remote: true, class: "btn btn-primary pull-right", "data-disabled-with":"...新增" %> +
    + +
    + 说明:该界面适用于存储全局变量. +
    + +
    + <%= render partial: 'admins/edu_settings/list', locals: { edu_settings: @edu_settings } %> +
    +
    +
    diff --git a/app/views/admins/edu_settings/index.js.erb b/app/views/admins/edu_settings/index.js.erb new file mode 100644 index 00000000..92a4bfef --- /dev/null +++ b/app/views/admins/edu_settings/index.js.erb @@ -0,0 +1 @@ +$('.edu_settings-list-container').html("<%= j( render partial: 'admins/edu_settings/list', locals: { edu_settings: @edu_settings } ) %>"); \ No newline at end of file diff --git a/app/views/admins/edu_settings/new.js.erb b/app/views/admins/edu_settings/new.js.erb new file mode 100644 index 00000000..21abf389 --- /dev/null +++ b/app/views/admins/edu_settings/new.js.erb @@ -0,0 +1,2 @@ +$("#edu_setting-modals").html("<%= j render(partial: 'admins/edu_settings/form', locals: {type: 'create'}) %>") +$(".edu_setting-change-modal").modal('show'); \ 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 b4959c3f..e58337c1 100644 --- a/app/views/admins/shared/_sidebar.html.erb +++ b/app/views/admins/shared/_sidebar.html.erb @@ -43,6 +43,12 @@
  • <%= sidebar_item(admins_faqs_path, 'FAQ', icon: 'question-circle', controller: 'admins-faqs') %>
  • <% end %> +
  • + <%= sidebar_item_group('#setting-system', '系统配置', icon: 'wrench') do %> +
  • <%= sidebar_item(admins_sites_path, 'setting接口配置', icon: 'deaf', controller: 'admins-sites') %>
  • +
  • <%= sidebar_item(admins_edu_settings_path, '全局变量配置', icon: 'pencil-square', controller: 'admins-edu_settings') %>
  • + <% end %> +
  • <%= sidebar_item('/admins/sidekiq', '定时任务', icon: 'bell', controller: 'root') %>
  • diff --git a/app/views/admins/sites/_form.html.erb b/app/views/admins/sites/_form.html.erb new file mode 100644 index 00000000..1776bcd0 --- /dev/null +++ b/app/views/admins/sites/_form.html.erb @@ -0,0 +1,42 @@ + \ No newline at end of file diff --git a/app/views/admins/sites/_list.html.erb b/app/views/admins/sites/_list.html.erb new file mode 100644 index 00000000..bef39cf1 --- /dev/null +++ b/app/views/admins/sites/_list.html.erb @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + <% if sites.present? %> + <% sites.each_with_index do |site, index| %> + + + + + + + + + + + <% end %> + <% else %> + <%= render 'admins/shared/no_data_for_table' %> + <% end %> + +
    序号名称路由标识类型<%= sort_tag('创建时间', name: 'created_at', path: admins_sites_path) %>操作
    <%= list_index_no((params[:page] || 1).to_i, index) %> + <%= overflow_hidden_span display_text(site.name), width: 150 %> + <%= site.url %><%= overflow_hidden_span display_text(site.key), width: 150 %><%= site.site_type.humanize %><%= site.created_at&.strftime('%Y-%m-%d %H:%M') %> + <%= link_to "编辑", edit_admins_site_path(site), remote: true, class: "action" %> + <%= link_to "删除", admins_site_path(site), method: :delete, data:{confirm: "确认删除的吗?"}, class: "action" %> +
    + +<%= render partial: 'admins/shared/paginate', locals: { objects: sites } %> \ No newline at end of file diff --git a/app/views/admins/sites/edit.js.erb b/app/views/admins/sites/edit.js.erb new file mode 100644 index 00000000..6711ffc1 --- /dev/null +++ b/app/views/admins/sites/edit.js.erb @@ -0,0 +1,2 @@ +$("#site-modals").html("<%= j render(partial: 'admins/sites/form', locals: {type: 'update'}) %>") +$(".site-change-modal").modal('show'); \ No newline at end of file diff --git a/app/views/admins/sites/index.html.erb b/app/views/admins/sites/index.html.erb new file mode 100644 index 00000000..8a5fa1bf --- /dev/null +++ b/app/views/admins/sites/index.html.erb @@ -0,0 +1,24 @@ +<% define_admin_breadcrumbs do %> + <% add_admin_breadcrumb('Setting接口配置') %> +<% end %> + +
    + <%= form_tag(admins_sites_path, method: :get, class: 'form-inline search-form flex-1', remote: true) do %> +
    + + <% type_options = [['全部', ''], ['Add', Site.site_types[:add]], ['Personal', Site.site_types[:personal]], ['Common', Site.site_types[:common]]] %> + <%= select_tag(:site_type, options_for_select(type_options), class: 'form-control') %> +
    + + <%= 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_site_path, remote: true, class: "btn btn-primary pull-right", "data-disabled-with":"...新增" %> +
    + +
    + <%= render partial: 'admins/sites/list', locals: { sites: @sites } %> +
    +
    +
    diff --git a/app/views/admins/sites/index.js.erb b/app/views/admins/sites/index.js.erb new file mode 100644 index 00000000..797d5829 --- /dev/null +++ b/app/views/admins/sites/index.js.erb @@ -0,0 +1 @@ +$('.sites-list-container').html("<%= j( render partial: 'admins/sites/list', locals: { sites: @sites } ) %>"); \ No newline at end of file diff --git a/app/views/admins/sites/new.js.erb b/app/views/admins/sites/new.js.erb new file mode 100644 index 00000000..6978fed3 --- /dev/null +++ b/app/views/admins/sites/new.js.erb @@ -0,0 +1,2 @@ +$("#site-modals").html("<%= j render(partial: 'admins/sites/form', locals: {type: 'create'}) %>") +$(".site-change-modal").modal('show'); \ No newline at end of file diff --git a/app/views/edu_settings/_form.html.erb b/app/views/edu_settings/_form.html.erb deleted file mode 100644 index 3b7f09f1..00000000 --- a/app/views/edu_settings/_form.html.erb +++ /dev/null @@ -1,27 +0,0 @@ -<%= form_with(model: edu_setting, local: true) do |form| %> - <% if edu_setting.errors.any? %> -
    -

    <%= pluralize(edu_setting.errors.count, "error") %> prohibited this edu_setting from being saved:

    - -
      - <% edu_setting.errors.full_messages.each do |message| %> -
    • <%= message %>
    • - <% end %> -
    -
    - <% end %> - -
    - <%= form.label :name %> - <%= form.text_field :name %> -
    - -
    - <%= form.label :value %> - <%= form.text_field :value %> -
    - -
    - <%= form.submit %> -
    -<% end %> diff --git a/app/views/edu_settings/edit.html.erb b/app/views/edu_settings/edit.html.erb deleted file mode 100644 index 2a079684..00000000 --- a/app/views/edu_settings/edit.html.erb +++ /dev/null @@ -1,6 +0,0 @@ -

    Editing Edu Setting

    - -<%= render 'form', edu_setting: @edu_setting %> - -<%= link_to 'Show', @edu_setting %> | -<%= link_to 'Back', edu_settings_path %> diff --git a/app/views/edu_settings/index.html.erb b/app/views/edu_settings/index.html.erb deleted file mode 100644 index d4997725..00000000 --- a/app/views/edu_settings/index.html.erb +++ /dev/null @@ -1,30 +0,0 @@ -

    <%= notice %>

    - -

    EduCoder公共配置

    -

    说明:该界面适用于存储全局变量

    - - - - - - - - - - - - <% @edu_settings.each do |edu_setting| %> - - - - - - - - <% end %> - -
    变量名变量值
    <%= edu_setting.name %><%= edu_setting.value %><%= link_to 'Show', edu_setting %><%= link_to 'Edit', edit_edu_setting_path(edu_setting) %><%= link_to 'Destroy', edu_setting, method: :delete, data: { confirm: 'Are you sure?' } %>
    - -
    - -<%= link_to 'New Edu Setting', new_edu_setting_path %> diff --git a/app/views/edu_settings/new.html.erb b/app/views/edu_settings/new.html.erb deleted file mode 100644 index 8a70e3a6..00000000 --- a/app/views/edu_settings/new.html.erb +++ /dev/null @@ -1,5 +0,0 @@ -

    New Edu Setting

    - -<%= render 'form', edu_setting: @edu_setting %> - -<%= link_to 'Back', edu_settings_path %> diff --git a/app/views/edu_settings/show.html.erb b/app/views/edu_settings/show.html.erb deleted file mode 100644 index 9d027373..00000000 --- a/app/views/edu_settings/show.html.erb +++ /dev/null @@ -1,14 +0,0 @@ -

    <%= notice %>

    - -

    - Name: - <%= @edu_setting.name %> -

    - -

    - Value: - <%= @edu_setting.value %> -

    - -<%= link_to 'Edit', edit_edu_setting_path(@edu_setting) %> | -<%= link_to 'Back', edu_settings_path %> diff --git a/config/routes.rb b/config/routes.rb index 346468fb..37b98b22 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -651,6 +651,8 @@ Rails.application.routes.draw do get :visits_static end end + resources :sites + resources :edu_settings resources :project_languages resources :project_categories resources :project_licenses diff --git a/spec/controllers/admins/edu_settings_controller_spec.rb b/spec/controllers/admins/edu_settings_controller_spec.rb new file mode 100644 index 00000000..ae516487 --- /dev/null +++ b/spec/controllers/admins/edu_settings_controller_spec.rb @@ -0,0 +1,47 @@ +require 'rails_helper' + +RSpec.describe Admins::EduSettingsController, type: :controller do + + describe "GET #index" do + it "returns http success" do + get :index + expect(response).to have_http_status(:success) + end + end + + describe "GET #new" do + it "returns http success" do + get :new + expect(response).to have_http_status(:success) + end + end + + describe "GET #update" do + it "returns http success" do + get :update + expect(response).to have_http_status(:success) + end + end + + describe "GET #edit" do + it "returns http success" do + get :edit + expect(response).to have_http_status(:success) + end + end + + describe "GET #create" do + it "returns http success" do + get :create + expect(response).to have_http_status(:success) + end + end + + describe "GET #destroy" do + it "returns http success" do + get :destroy + expect(response).to have_http_status(:success) + end + end + +end diff --git a/spec/controllers/admins/sites_controller_spec.rb b/spec/controllers/admins/sites_controller_spec.rb new file mode 100644 index 00000000..0c5f79b3 --- /dev/null +++ b/spec/controllers/admins/sites_controller_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe Admins::SitesController, type: :controller do + +end diff --git a/spec/views/admins/edu_settings/create.html.erb_spec.rb b/spec/views/admins/edu_settings/create.html.erb_spec.rb new file mode 100644 index 00000000..bc53b9f1 --- /dev/null +++ b/spec/views/admins/edu_settings/create.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "edu_settings/create.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/views/admins/edu_settings/destroy.html.erb_spec.rb b/spec/views/admins/edu_settings/destroy.html.erb_spec.rb new file mode 100644 index 00000000..51acd490 --- /dev/null +++ b/spec/views/admins/edu_settings/destroy.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "edu_settings/destroy.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/views/admins/edu_settings/edit.html.erb_spec.rb b/spec/views/admins/edu_settings/edit.html.erb_spec.rb new file mode 100644 index 00000000..e381cbb0 --- /dev/null +++ b/spec/views/admins/edu_settings/edit.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "edu_settings/edit.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/views/admins/edu_settings/index.html.erb_spec.rb b/spec/views/admins/edu_settings/index.html.erb_spec.rb new file mode 100644 index 00000000..ba6e16eb --- /dev/null +++ b/spec/views/admins/edu_settings/index.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "edu_settings/index.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/views/admins/edu_settings/new.html.erb_spec.rb b/spec/views/admins/edu_settings/new.html.erb_spec.rb new file mode 100644 index 00000000..00bc830c --- /dev/null +++ b/spec/views/admins/edu_settings/new.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "edu_settings/new.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/views/admins/edu_settings/update.html.erb_spec.rb b/spec/views/admins/edu_settings/update.html.erb_spec.rb new file mode 100644 index 00000000..89ae0feb --- /dev/null +++ b/spec/views/admins/edu_settings/update.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "edu_settings/update.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end From 96c79ffade03a1dae19d0d26a8e3938d8442e386 Mon Sep 17 00:00:00 2001 From: jasder Date: Fri, 10 Sep 2021 15:35:57 +0800 Subject: [PATCH 015/135] =?UTF-8?q?FIX=20=E8=80=BF=E7=9B=B4=E5=88=9B?= =?UTF-8?q?=E5=BB=BA=E9=A1=B9=E7=9B=AE=E6=8F=90=E7=A4=BA=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/forms/base_form.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/forms/base_form.rb b/app/forms/base_form.rb index a939b199..c41a1299 100644 --- a/app/forms/base_form.rb +++ b/app/forms/base_form.rb @@ -11,7 +11,7 @@ class BaseForm def check_repository_name(user_id, repository_name) check_reversed_keyword(repository_name) - raise "仓库名称已被使用." if Repository.where(user_id: user_id, identifier: repository_name.strip).exists? + raise "项目标识已被使用." if Repository.where(user_id: user_id, identifier: repository_name.strip).exists? end def check_project_name(user_id, project_name) @@ -19,7 +19,7 @@ class BaseForm end def check_reversed_keyword(repository_name) - raise "仓库名称已被占用." if ReversedKeyword.is_reversed(repository_name).exists? + raise "项目标识已被占用." if ReversedKeyword.is_reversed(repository_name).exists? end end From cd569f4b8a93e8fb9c0e33e7c61691a78a610a1a Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 10 Sep 2021 15:53:38 +0800 Subject: [PATCH 016/135] fix: download url redirect delay --- app/controllers/attachments_controller.rb | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/app/controllers/attachments_controller.rb b/app/controllers/attachments_controller.rb index 14e53b3e..1f3bd97f 100644 --- a/app/controllers/attachments_controller.rb +++ b/app/controllers/attachments_controller.rb @@ -32,8 +32,17 @@ class AttachmentsController < ApplicationController def get_file normal_status(-1, "参数缺失") if params[:download_url].blank? url = URI.encode(params[:download_url].to_s.gsub("http:", "https:")) - response = Faraday.get(url) - filename = params[:download_url].to_s.split("/").pop() + if url.starts_with?(base_url) + domain = Gitea.gitea_config[:domain] + api_url = Gitea.gitea_config[:base_url] + url = url.split(base_url)[1].gsub("api", "repos").gsub('?filepath=', '/').gsub('&', '?') + request_url = [domain, api_url, url, "?ref=#{params[:ref]}&access_token=#{current_user&.gitea_token}"].join + response = Faraday.get(request_url) + filename = url.to_s.split("/").pop() + else + response = Faraday.get(url) + filename = params[:download_url].to_s.split("/").pop() + end send_data(response.body.force_encoding("UTF-8"), filename: filename, type: "application/octet-stream", disposition: 'attachment') end From c82635f6c382fbbf14dd2e3da11acacce459165f Mon Sep 17 00:00:00 2001 From: jasder Date: Fri, 10 Sep 2021 17:57:49 +0800 Subject: [PATCH 017/135] =?UTF-8?q?FIX=20=E7=BB=84=E7=BB=87=E5=90=8D?= =?UTF-8?q?=E7=A7=B0=E5=88=9B=E5=BB=BA=E9=A1=B9=E7=9B=AE=E6=97=B6=EF=BC=8C?= =?UTF-8?q?=E5=8E=BB=E6=8E=89readme=E7=9A=84=E5=88=9D=E5=A7=8B=E5=8C=96?= =?UTF-8?q?=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/services/gitea/organization/repository/create_service.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/services/gitea/organization/repository/create_service.rb b/app/services/gitea/organization/repository/create_service.rb index 060a8ab0..2990f711 100644 --- a/app/services/gitea/organization/repository/create_service.rb +++ b/app/services/gitea/organization/repository/create_service.rb @@ -15,8 +15,8 @@ class Gitea::Organization::Repository::CreateService < Gitea::ClientService private def request_params - create_params = params.merge(readme: "readme") - Hash.new.merge(token: token, data: create_params) + # create_params = params.merge(readme: "readme") + Hash.new.merge(token: token, data: params) end def url From 8c60ce1d76158fd511d79b746dfd0afd75b8180b Mon Sep 17 00:00:00 2001 From: jasder Date: Fri, 10 Sep 2021 22:46:48 +0800 Subject: [PATCH 018/135] =?UTF-8?q?FIX=20=E5=A4=84=E7=90=86=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E7=BB=84=E7=BB=87=E5=90=8E=E5=AF=BC=E8=87=B4=E4=B8=8D?= =?UTF-8?q?=E8=83=BD=E5=88=9B=E5=BB=BA=E9=A1=B9=E7=9B=AE=E7=9A=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../organizations/organizations_controller.rb | 17 ++++++++++++++++- app/forms/projects/create_form.rb | 11 ++++++----- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/app/controllers/organizations/organizations_controller.rb b/app/controllers/organizations/organizations_controller.rb index 23ef6a0d..218bc872 100644 --- a/app/controllers/organizations/organizations_controller.rb +++ b/app/controllers/organizations/organizations_controller.rb @@ -43,7 +43,8 @@ class Organizations::OrganizationsController < Organizations::BaseController @organization.login = organization_params[:name] if organization_params[:name].present? @organization.nickname = organization_params[:nickname] if organization_params[:nickname].present? @organization.save! - @organization.organization_extension.update_attributes!(organization_params.except(:name, :nickname)) + sync_organization_extension! + Gitea::Organization::UpdateService.call(@organization.gitea_token, login, @organization.reload) Util.write_file(@image, avatar_path(@organization)) if params[:image].present? end @@ -97,4 +98,18 @@ class Organizations::OrganizationsController < Organizations::BaseController %w(desc asc).include?(params[:sort_direction]) ? params[:sort_direction] : 'desc' end + def set_max_repo_creation + organization_params[:max_repo_creation].blank? ? -1 : organization_params[:max_repo_creation] + end + + def organization_extension_params + organization_params + .except(:name, :nickname) + .merge(max_repo_creation: set_max_repo_creation) + end + + def sync_organization_extension! + @organization.organization_extension.update_attributes!(organization_extension_params) + end + end \ No newline at end of file diff --git a/app/forms/projects/create_form.rb b/app/forms/projects/create_form.rb index a45da1a8..c51c2c60 100644 --- a/app/forms/projects/create_form.rb +++ b/app/forms/projects/create_form.rb @@ -26,13 +26,14 @@ class Projects::CreateForm < BaseForm end def check_owner - @owner = Owner.find_by(id: user_id) - raise "user_id值无效." if user_id && owner.blank? + @project_owner = Owner.find_by(id: user_id) + raise "user_id值无效." if user_id && @project_owner.blank? end def check_max_repo_creation - return unless owner.is_a?(Organization) - return if owner.max_repo_creation <= -1 - raise "已超过组织设置最大仓库数" if owner.max_repo_creation == owner.num_projects + return unless @project_owner.is_a?(Organization) + return if @project_owner.max_repo_creation <= -1 + + raise "已超过组织设置最大仓库数" if @project_owner.max_repo_creation == @project_owner.num_projects end end From 86d634d94fc14ab6ab510205857dd71feb011fc6 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 9 Sep 2021 16:32:13 +0800 Subject: [PATCH 019/135] add: notice message skeletal code --- app/controllers/users/messages_controller.rb | 121 +++ app/docs/slate/source/includes/_users.md | 250 ++++- app/libs/notice.rb | 21 + app/models/message_template.rb | 14 + app/models/message_template/issue_assigned.rb | 15 + .../message_template/issue_assigner_expire.rb | 15 + app/models/message_template/issue_atme.rb | 15 + app/models/message_template/issue_changed.rb | 15 + .../message_template/issue_creator_expire.rb | 15 + app/models/message_template/issue_deleted.rb | 15 + app/models/message_template/issue_journal.rb | 15 + app/models/message_template/login_ip_tip.rb | 15 + .../message_template/organization_joined.rb | 15 + .../message_template/organization_left.rb | 15 + .../message_template/organization_role.rb | 15 + app/models/message_template/project_delete.rb | 15 + .../message_template/project_followed.rb | 15 + app/models/message_template/project_forked.rb | 15 + app/models/message_template/project_issue.rb | 15 + app/models/message_template/project_joined.rb | 15 + app/models/message_template/project_left.rb | 16 + .../message_template/project_member_joined.rb | 15 + .../message_template/project_member_left.rb | 15 + .../message_template/project_milestone.rb | 15 + .../message_template/project_praised.rb | 15 + .../message_template/project_pull_request.rb | 15 + app/models/message_template/project_role.rb | 15 + .../project_setting_changed.rb | 15 + .../message_template/project_transfer.rb | 15 + .../message_template/project_version.rb | 15 + .../message_template/pull_request_assigned.rb | 15 + .../message_template/pull_request_atme.rb | 15 + .../message_template/pull_request_changed.rb | 15 + .../message_template/pull_request_journal.rb | 15 + app/services/notice/client_service.rb | 108 +++ app/views/users/get_user_info.json.jbuilder | 3 +- .../users/messages/_message.json.jbuilder | 22 + app/views/users/messages/index.json.jbuilder | 7 + config/configuration.yml.example | 3 + config/routes.rb | 7 + ...20210909030759_create_message_templates.rb | 11 + public/docs/api.html | 909 +++++++++++++----- spec/models/message_template_spec.rb | 5 + 43 files changed, 1696 insertions(+), 236 deletions(-) create mode 100644 app/controllers/users/messages_controller.rb create mode 100644 app/libs/notice.rb create mode 100644 app/models/message_template.rb create mode 100644 app/models/message_template/issue_assigned.rb create mode 100644 app/models/message_template/issue_assigner_expire.rb create mode 100644 app/models/message_template/issue_atme.rb create mode 100644 app/models/message_template/issue_changed.rb create mode 100644 app/models/message_template/issue_creator_expire.rb create mode 100644 app/models/message_template/issue_deleted.rb create mode 100644 app/models/message_template/issue_journal.rb create mode 100644 app/models/message_template/login_ip_tip.rb create mode 100644 app/models/message_template/organization_joined.rb create mode 100644 app/models/message_template/organization_left.rb create mode 100644 app/models/message_template/organization_role.rb create mode 100644 app/models/message_template/project_delete.rb create mode 100644 app/models/message_template/project_followed.rb create mode 100644 app/models/message_template/project_forked.rb create mode 100644 app/models/message_template/project_issue.rb create mode 100644 app/models/message_template/project_joined.rb create mode 100644 app/models/message_template/project_left.rb create mode 100644 app/models/message_template/project_member_joined.rb create mode 100644 app/models/message_template/project_member_left.rb create mode 100644 app/models/message_template/project_milestone.rb create mode 100644 app/models/message_template/project_praised.rb create mode 100644 app/models/message_template/project_pull_request.rb create mode 100644 app/models/message_template/project_role.rb create mode 100644 app/models/message_template/project_setting_changed.rb create mode 100644 app/models/message_template/project_transfer.rb create mode 100644 app/models/message_template/project_version.rb create mode 100644 app/models/message_template/pull_request_assigned.rb create mode 100644 app/models/message_template/pull_request_atme.rb create mode 100644 app/models/message_template/pull_request_changed.rb create mode 100644 app/models/message_template/pull_request_journal.rb create mode 100644 app/services/notice/client_service.rb create mode 100644 app/views/users/messages/_message.json.jbuilder create mode 100644 app/views/users/messages/index.json.jbuilder create mode 100644 db/migrate/20210909030759_create_message_templates.rb create mode 100644 spec/models/message_template_spec.rb diff --git a/app/controllers/users/messages_controller.rb b/app/controllers/users/messages_controller.rb new file mode 100644 index 00000000..0433d41a --- /dev/null +++ b/app/controllers/users/messages_controller.rb @@ -0,0 +1,121 @@ +class Users::MessagesController < Users::BaseController + before_action :private_user_resources! + + def index + data = { + "receiver": 2, + "type": @message_type, + "unread_total": 5, + "unread_notification": 3, + "unread_atme": 2, + "records": [ + { + "id": 1, + "sender": 5, + "receiver": 2, + "content": "Atme Message Content 1", + "status": 1, + "type": 2, + "source": "PullRequestAtme", + "notification_url": "http://www.baidu.com", + "created_at": "2021-09-09 14:34:40" + }, + { + "id": 2, + "sender": 4, + "receiver": 2, + "content": "Atme Message Content 2", + "status": 0, + "type": 2, + "source": "IssueAtme", + "notification_url": "http://www.baidu.com", + "created_at": "2021-09-09 14:34:40" + }, + { + "id": 3, + "sender": -1, + "receiver": 2, + "content": "Notification Message Content 1", + "status": 1, + "type": 1, + "source": "IssueDelete", + "notification_url": "http://www.baidu.com", + "created_at": "2021-09-09 14:34:40" + }, + { + "id": 4, + "sender": -1, + "receiver": 2, + "content": "Notification Message Content 2", + "status": 0, + "type": 1, + "source": "IssueChanged", + "notification_url": "http://www.baidu.com", + "created_at": "2021-09-09 14:34:40" + }, + { + "id": 5, + "sender": -1, + "receiver": 2, + "content": "Notification Message Content 3", + "status": 0, + "type": 1, + "source": "ProjectJoined", + "notification_url": "http://www.baidu.com", + "created_at": "2021-09-09 14:34:40" + } + ], + "records_count": 5, + "page_num": 1, + "total_page_size": 1, + "page_size": 10 + } + result = [1, "请求成功", data] + return render_error if result.nil? + puts result + @data = result[2].stringify_keys + + end + + def create + return render_forbidden unless %w(3).include(@message_type) + render_ok + end + + def delete + return render_forbidden unless %w(2).include(@message_type) + render_ok + end + + def read + render_ok + end + + private + def message_type + @message_type = begin + case params[:type] + when "notification" + 1 + when "atme" + 2 + else + -1 + end + end + end + + def message_params + { + sender: current_user.id, + reservers: @receiver.id, + type: @message_type, + content: params[:content] + } + end + + + def find_receiver + @receiver = User.find_by(login: params[:receiver_login]) + end +end \ No newline at end of file diff --git a/app/docs/slate/source/includes/_users.md b/app/docs/slate/source/includes/_users.md index bb4fd2b6..f49fdcf6 100644 --- a/app/docs/slate/source/includes/_users.md +++ b/app/docs/slate/source/includes/_users.md @@ -1,7 +1,7 @@ # Users @@ -47,6 +47,254 @@ await octokit.request('GET /api/users/me.json') Success Data. +## 用户消息列表 +获取用户消息列表 + +> 示例: + +```shell +curl -X GET http://localhost:3000/api/users/:login/messages.json +``` + +```javascript +await octokit.request('GET /api/users/:login/messages.json') +``` + +### HTTP 请求 +`GET api/users/yystopf/messages.json` + +### 请求字段说明: +参数 | 类型 | 字段说明 +--------- | ----------- | ----------- +|type | string | 消息类型,不传为所有消息,notification为系统消息,atme为@我消息| +|status | integer | 是否已读,不传为所有消息,0为未读,1为已读 | +|limit | integer | 每页个数 | +|page | integer | 页码 | + +### 返回字段说明: +参数 | 类型 | 字段说明 +--------- | ----------- | ----------- +|total_count | integer | 消息总数 | +|type | string | 消息类型 | +|unread_notification | integer | 未读系统通知数量 | +|unread_atme | integer | 未读@我数量 | +|messages.id | integer | 消息id | +|messages.status | integer | 消息是否已读,0为未读,1为已读 | +|messages.content | string | 消息内容 | +|messages.notification_url | string | 消息跳转地址 | +|messages.source | string | 消息来源 | +|messages.type | string | 消息类型,notification为系统消息,atme为@我消息| +|sender | object | 消息发送者 | + +#### 消息来源source字段说明 +类型|说明 +--------- | ----------- +|IssueAssigned | 有新指派给我的易修 | +|IssueAssignerExpire | 我负责的易修截止日期到达最后一天 | +|IssueAtme | 在易修中@我 | +|IssueChanged | 我创建或负责的易修状态变更 | +|IssueCreatorExpire | 我创建的易修截止日期到达最后一天 | +|IssueDeleted | 我创建或负责的易修删除 | +|IssueJournal | 我创建或负责的易修有新的评论 | +|LoginIpTip | 登录异常提示 | +|OrganizationJoined | 账号被拉入组织 | +|OrganizationLeft | 账号被移出组织 | +|OrganizationRole | 账号组织权限变更 | +|ProjectDelete | 我关注的仓库被删除 | +|ProjectFollowed | 我管理的仓库被关注 | +|ProjectForked | 我管理的仓库被复刻 | +|ProjectIssue | 我管理/关注的仓库有新的易修 | +|ProjectJoined | 账号被拉入项目 | +|ProjectLeft | 账号被移出项目 | +|ProjectMemberJoined | 我管理的仓库有成员加入 | +|ProjectMemberLeft | 我管理的仓库有成员移出 | +|ProjectMilestone | 我管理的仓库有新的里程碑 | +|ProjectPraised | 我管理的仓库被点赞 | +|ProjectPullRequest | 我管理/关注的仓库有新的合并请求 | +|ProjectRole | 账号仓库权限变更 | +|ProjectSettingChanged | 我管理的仓库项目设置被更改 | +|ProjectTransfer | 我关注的仓库被转移 | +|ProjectVersion | 我关注的仓库有新的发行版 | +|PullRequestAssigned | 有新指派给我的合并请求 | +|PullReuqestAtme | 在合并请求中@我 | +|PullRequestChanged | 我创建或负责的合并请求状态变更 | +|PullRequestJournal | 我创建或负责的合并请求有新的评论 | + + +> 返回的JSON示例: + +```json +{ + "total_count": 5, + "type": "", + "unread_notification": 3, + "unread_atme": 2, + "messages": [ + { + "id": 1, + "status": 1, + "content": "Atme Message Content 1", + "notification_url": "http://www.baidu.com", + "source": "PullRequestAtme", + "type": "atme", + "sender": { + "id": 5, + "type": "User", + "name": "testforge2", + "login": "testforge2", + "image_url": "system/lets/letter_avatars/2/T/236_177_85/120.png" + } + }, + { + "id": 2, + "status": 0, + "content": "Atme Message Content 2", + "notification_url": "http://www.baidu.com", + "source": "IssueAtme", + "type": "atme", + "sender": { + "id": 4, + "type": "User", + "name": "testforge1", + "login": "testforge1", + "image_url": "system/lets/letter_avatars/2/T/19_237_174/120.png" + } + }, + { + "id": 3, + "status": 1, + "content": "Notification Message Content 1", + "notification_url": "http://www.baidu.com", + "source": "IssueDelete", + "type": "notification" + }, + { + "id": 4, + "status": 0, + "content": "Notification Message Content 2", + "notification_url": "http://www.baidu.com", + "source": "IssueChanged", + "type": "notification" + }, + { + "id": 5, + "status": 0, + "content": "Notification Message Content 3", + "notification_url": "http://www.baidu.com", + "source": "ProjectJoined", + "type": "notification" + } + ] +} +``` + + +## 发送消息 +发送消息 + +> 示例: + +```shell +curl -X POST http://localhost:3000/api/users/:login/messages.json +``` + +```javascript +await octokit.request('POST /api/users/:login/messages.json') +``` + +### HTTP 请求 +`POST api/users/yystopf/messages.json` + +### 请求字段说明: +参数 | 类型 | 字段说明 +--------- | ----------- | ----------- +|type | string | 消息类型 | +|recervers_login | array | 需要发送消息的用户名数组| +|content | string | 消息内容 | + +> 返回的JSON示例: + +```json +{ + "status": 0, + "message": "success" +} +``` + + +## 阅读消息 +阅读消息 + +> 示例: + +```shell +curl -X POST http://localhost:3000/api/users/:login/messages/read.json +``` + +```javascript +await octokit.request('POST /api/users/:login/messages/read.json') +``` + +### HTTP 请求 +`POST api/users/yystopf/messages/read.json` + +### 请求字段说明: +参数 | 类型 | 字段说明 +--------- | ----------- | ----------- +|type | string | 消息类型,不传为所有消息,notification为系统消息,atme为@我消息| +|ids | array | 消息id数组,包含-1则把所有未读消息标记为已读| + +> 返回的JSON示例: + +```json +{ + "status": 0, + "message": "success" +} +``` + + +## 删除消息 +删除消息 + +> 示例: + +```shell +curl -X DELETE http://localhost:3000/api/users/:login/messages.json +``` + +```javascript +await octokit.request('DELETE /api/users/:login/messages.json') +``` + +### HTTP 请求 +`DELETE api/users/yystopf/messages.json` + +### 请求字段说明: +参数 | 类型 | 字段说明 +--------- | ----------- | ----------- +|type | string | 消息类型,atme为@我消息| +|ids | array | 消息id数组,包含-1则把所有消息删除| + +> 返回的JSON示例: + +```json +{ + "status": 0, + "message": "success" +} +``` + + + ## 更改用户信息 更改用户信息 diff --git a/app/libs/notice.rb b/app/libs/notice.rb new file mode 100644 index 00000000..93d5cb42 --- /dev/null +++ b/app/libs/notice.rb @@ -0,0 +1,21 @@ +module Notice + class << self + def notice_config + notice_config = {} + + begin + config = Rails.application.config_for(:configuration).symbolize_keys! + notice_config = config[:notice].symbolize_keys! + raise 'notice config missing' if notice_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} + notice_config = {} + end + + notice_config + end + end +end \ No newline at end of file diff --git a/app/models/message_template.rb b/app/models/message_template.rb new file mode 100644 index 00000000..f19b77fb --- /dev/null +++ b/app/models/message_template.rb @@ -0,0 +1,14 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +class MessageTemplate < ApplicationRecord +end diff --git a/app/models/message_template/issue_assigned.rb b/app/models/message_template/issue_assigned.rb new file mode 100644 index 00000000..51e3e617 --- /dev/null +++ b/app/models/message_template/issue_assigned.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 有新指派给我的易修 +class MessageTemplate::IssueAssigned < MessageTemplate +end diff --git a/app/models/message_template/issue_assigner_expire.rb b/app/models/message_template/issue_assigner_expire.rb new file mode 100644 index 00000000..03af6163 --- /dev/null +++ b/app/models/message_template/issue_assigner_expire.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 我负责的易修截止日期到达最后一天 +class MessageTemplate::IssueAssignerExpire < MessageTemplate +end diff --git a/app/models/message_template/issue_atme.rb b/app/models/message_template/issue_atme.rb new file mode 100644 index 00000000..d0915582 --- /dev/null +++ b/app/models/message_template/issue_atme.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 在易修中@我 +class MessageTemplate::IssueAtme < MessageTemplate +end \ No newline at end of file diff --git a/app/models/message_template/issue_changed.rb b/app/models/message_template/issue_changed.rb new file mode 100644 index 00000000..98772ab0 --- /dev/null +++ b/app/models/message_template/issue_changed.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 我创建或负责的易修状态变更 +class MessageTemplate::IssueChanged < MessageTemplate +end diff --git a/app/models/message_template/issue_creator_expire.rb b/app/models/message_template/issue_creator_expire.rb new file mode 100644 index 00000000..ee194071 --- /dev/null +++ b/app/models/message_template/issue_creator_expire.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 我创建的易修截止日期到达最后一天 +class MessageTemplate::IssueCreatorExpire < MessageTemplate +end diff --git a/app/models/message_template/issue_deleted.rb b/app/models/message_template/issue_deleted.rb new file mode 100644 index 00000000..d25fbffd --- /dev/null +++ b/app/models/message_template/issue_deleted.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 我创建或负责的易修删除 +class MessageTemplate::IssueDeleted < MessageTemplate +end diff --git a/app/models/message_template/issue_journal.rb b/app/models/message_template/issue_journal.rb new file mode 100644 index 00000000..4252704c --- /dev/null +++ b/app/models/message_template/issue_journal.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 我创建或负责的易修有新的评论 +class MessageTemplate::IssueJournal < MessageTemplate +end diff --git a/app/models/message_template/login_ip_tip.rb b/app/models/message_template/login_ip_tip.rb new file mode 100644 index 00000000..a86e03a5 --- /dev/null +++ b/app/models/message_template/login_ip_tip.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 登录异常提示 +class MessageTemplate::LoginIpTip < MessageTemplate +end diff --git a/app/models/message_template/organization_joined.rb b/app/models/message_template/organization_joined.rb new file mode 100644 index 00000000..4440bb74 --- /dev/null +++ b/app/models/message_template/organization_joined.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 账号被拉入组织 +class MessageTemplate::OrganizationJoined < MessageTemplate +end diff --git a/app/models/message_template/organization_left.rb b/app/models/message_template/organization_left.rb new file mode 100644 index 00000000..9d346b7b --- /dev/null +++ b/app/models/message_template/organization_left.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 账号被移出组织 +class MessageTemplate::OrganizationLeft < MessageTemplate +end diff --git a/app/models/message_template/organization_role.rb b/app/models/message_template/organization_role.rb new file mode 100644 index 00000000..1222a624 --- /dev/null +++ b/app/models/message_template/organization_role.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 账号组织权限变更 +class MessageTemplate::OrganizationRole < MessageTemplate +end diff --git a/app/models/message_template/project_delete.rb b/app/models/message_template/project_delete.rb new file mode 100644 index 00000000..b03813f3 --- /dev/null +++ b/app/models/message_template/project_delete.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 我关注的仓库被删除 +class MessageTemplate::ProjectDelete < MessageTemplate +end diff --git a/app/models/message_template/project_followed.rb b/app/models/message_template/project_followed.rb new file mode 100644 index 00000000..654e19c7 --- /dev/null +++ b/app/models/message_template/project_followed.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 我管理的仓库被关注 +class MessageTemplate::ProjectFollowed < MessageTemplate +end diff --git a/app/models/message_template/project_forked.rb b/app/models/message_template/project_forked.rb new file mode 100644 index 00000000..711460c0 --- /dev/null +++ b/app/models/message_template/project_forked.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 我管理的仓库被复刻 +class MessageTemplate::ProjectForked < MessageTemplate +end diff --git a/app/models/message_template/project_issue.rb b/app/models/message_template/project_issue.rb new file mode 100644 index 00000000..fc34d9a5 --- /dev/null +++ b/app/models/message_template/project_issue.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 我管理/关注的仓库有新的易修 +class MessageTemplate::ProjectIssue < MessageTemplate +end diff --git a/app/models/message_template/project_joined.rb b/app/models/message_template/project_joined.rb new file mode 100644 index 00000000..6d21a39e --- /dev/null +++ b/app/models/message_template/project_joined.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 账号被拉入项目 +class MessageTemplate::ProjectJoined < MessageTemplate +end diff --git a/app/models/message_template/project_left.rb b/app/models/message_template/project_left.rb new file mode 100644 index 00000000..f95467f0 --- /dev/null +++ b/app/models/message_template/project_left.rb @@ -0,0 +1,16 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 账号被移出项目 +class MessageTemplate::ProjectLeft < MessageTemplate + +end diff --git a/app/models/message_template/project_member_joined.rb b/app/models/message_template/project_member_joined.rb new file mode 100644 index 00000000..6e4e1acc --- /dev/null +++ b/app/models/message_template/project_member_joined.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 我管理的仓库有成员加入 +class MessageTemplate::ProjectMemberJoined < MessageTemplate +end diff --git a/app/models/message_template/project_member_left.rb b/app/models/message_template/project_member_left.rb new file mode 100644 index 00000000..3259034d --- /dev/null +++ b/app/models/message_template/project_member_left.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 我管理的仓库有成员移出 +class MessageTemplate::ProjectMemberLeft < MessageTemplate +end diff --git a/app/models/message_template/project_milestone.rb b/app/models/message_template/project_milestone.rb new file mode 100644 index 00000000..b1ff0b9e --- /dev/null +++ b/app/models/message_template/project_milestone.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 我管理的仓库有新的里程碑 +class MessageTemplate::ProjectMilestone < MessageTemplate +end diff --git a/app/models/message_template/project_praised.rb b/app/models/message_template/project_praised.rb new file mode 100644 index 00000000..ebbdfd93 --- /dev/null +++ b/app/models/message_template/project_praised.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 我管理的仓库被点赞 +class MessageTemplate::ProjectPraised < MessageTemplate +end diff --git a/app/models/message_template/project_pull_request.rb b/app/models/message_template/project_pull_request.rb new file mode 100644 index 00000000..b1706eb9 --- /dev/null +++ b/app/models/message_template/project_pull_request.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 我管理/关注的仓库有新的合并请求 +class MessageTemplate::ProjectPullRequest < MessageTemplate +end diff --git a/app/models/message_template/project_role.rb b/app/models/message_template/project_role.rb new file mode 100644 index 00000000..a59df536 --- /dev/null +++ b/app/models/message_template/project_role.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 账号仓库权限变更 +class MessageTemplate::ProjectRole < MessageTemplate +end diff --git a/app/models/message_template/project_setting_changed.rb b/app/models/message_template/project_setting_changed.rb new file mode 100644 index 00000000..1c4040f5 --- /dev/null +++ b/app/models/message_template/project_setting_changed.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 我管理的仓库项目设置被更改 +class MessageTemplate::ProjectSettingChanged < MessageTemplate +end diff --git a/app/models/message_template/project_transfer.rb b/app/models/message_template/project_transfer.rb new file mode 100644 index 00000000..38998d03 --- /dev/null +++ b/app/models/message_template/project_transfer.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 我关注的仓库被转移 +class MessageTemplate::ProjectTransfer < MessageTemplate +end \ No newline at end of file diff --git a/app/models/message_template/project_version.rb b/app/models/message_template/project_version.rb new file mode 100644 index 00000000..330dfe95 --- /dev/null +++ b/app/models/message_template/project_version.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 我关注的仓库有新的发行版 +class MessageTemplate::ProjectVersion < MessageTemplate +end diff --git a/app/models/message_template/pull_request_assigned.rb b/app/models/message_template/pull_request_assigned.rb new file mode 100644 index 00000000..1be86530 --- /dev/null +++ b/app/models/message_template/pull_request_assigned.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 有新指派给我的合并请求 +class MessageTemplate::PullRequestAssigned < MessageTemplate +end diff --git a/app/models/message_template/pull_request_atme.rb b/app/models/message_template/pull_request_atme.rb new file mode 100644 index 00000000..afa7a400 --- /dev/null +++ b/app/models/message_template/pull_request_atme.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 在合并请求中@我 +class MessageTemplate::PullReuqestAtme < MessageTemplate +end \ No newline at end of file diff --git a/app/models/message_template/pull_request_changed.rb b/app/models/message_template/pull_request_changed.rb new file mode 100644 index 00000000..002de3a2 --- /dev/null +++ b/app/models/message_template/pull_request_changed.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 我创建或负责的合并请求状态变更 +class MessageTemplate::PullRequestChanged < MessageTemplate +end diff --git a/app/models/message_template/pull_request_journal.rb b/app/models/message_template/pull_request_journal.rb new file mode 100644 index 00000000..0f79d166 --- /dev/null +++ b/app/models/message_template/pull_request_journal.rb @@ -0,0 +1,15 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# + +# 我创建或负责的合并请求有新的评论 +class MessageTemplate::PullRequestJournal < MessageTemplate +end diff --git a/app/services/notice/client_service.rb b/app/services/notice/client_service.rb new file mode 100644 index 00000000..a2ada88c --- /dev/null +++ b/app/services/notice/client_service.rb @@ -0,0 +1,108 @@ +class Notice::ClientService < ApplicationService + attr_reader :url, :params + + def initialize(options={}) + @url = options[:url] + @params = options[:params] + end + + def post(url, params={}) + puts "[notice][POST] request params: #{params}" + conn.post do |req| + req.url = full_url(url) + req.body = params[:data].to_json + end + end + + def get(url, params={}) + puts "[notice][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 delete(url, params={}) + puts "[notice][DELETE] request params: #{params}" + conn.delete do |req| + req.url full_url(url) + reb.body = params[:data].to_json + end + end + + def patch(url, params={}) + puts "[notice][PATCH] request params: #{params}" + conn.patch do |req| + req.url full_url(url) + reb.body = params[:data].to_json + end + end + + def put(url, params={}) + puts "[notice][PUT] request params: #{params}" + conn.put do |req| + req.url full_url(url) + reb.body = params[:data].to_json + 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 + Notice.notice_config[:base_url] + end + + def domain + Notice.notice_config[:domain] + end + + def platform + Notice.notice_config[:platform] + 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 "[notice] request url: #{url}" + return url + end + + def log_error(status, body) + puts "[notice] status: #{status}" + puts "[notice] body: #{body&.force_encoding('UTF-8')}" + end + + def render_response(response) + status = response.status + body = response&.body + + log_error(status, body) + + if status == 200 + if body["code"] == 1 + return [body["code"], body["message"], body["data"]] + else + puts "[notice][ERROR] code: #{body["code"]}" + puts "[notice][ERROR] message: #{body["message"]}" + end + end + end +end \ No newline at end of file diff --git a/app/views/users/get_user_info.json.jbuilder b/app/views/users/get_user_info.json.jbuilder index 067019ef..bf5ab882 100644 --- a/app/views/users/get_user_info.json.jbuilder +++ b/app/views/users/get_user_info.json.jbuilder @@ -21,4 +21,5 @@ 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) \ No newline at end of file +json.(@user, :show_email, :show_department, :show_location) +json.message_unread_total 5 \ No newline at end of file diff --git a/app/views/users/messages/_message.json.jbuilder b/app/views/users/messages/_message.json.jbuilder new file mode 100644 index 00000000..1d8a9b26 --- /dev/null +++ b/app/views/users/messages/_message.json.jbuilder @@ -0,0 +1,22 @@ +json.id message["id"] +# json.receiver do +# json.partial! '/users/user_simple', locals: {user: current_user} +# end +json.status message["status"] +json.content message["content"] +json.notification_url message["notification_url"] +json.source message["source"] +case message["type"] +when 1 + json.type "notification" +when 2 + json.type "atme" + json.sender do + sender = User.find_by_id(message["sender"]) + if sender.present? + json.partial! '/users/user_simple', locals: {user: sender} + else + json.nil + end + end +end diff --git a/app/views/users/messages/index.json.jbuilder b/app/views/users/messages/index.json.jbuilder new file mode 100644 index 00000000..b16d806b --- /dev/null +++ b/app/views/users/messages/index.json.jbuilder @@ -0,0 +1,7 @@ +json.total_count @data["records_count"] +json.type %w(notification atme).include?(params[:type]) ? params[:type] : "" +json.unread_notification @data["unread_notification"] +json.unread_atme @data["unread_atme"] +json.messages @data["records"].each do |message| + json.partial! "message", message: message.stringify_keys +end \ No newline at end of file diff --git a/config/configuration.yml.example b/config/configuration.yml.example index c8fe96ca..61217d4e 100644 --- a/config/configuration.yml.example +++ b/config/configuration.yml.example @@ -57,6 +57,9 @@ default: &default domain: 'https://testgit.trustie.net' base_url: '/api/v1' + notice: + domain: '' + base_url: '' production: <<: *default diff --git a/config/routes.rb b/config/routes.rb index dc889208..2d5bb9ed 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -300,6 +300,13 @@ Rails.application.routes.draw do # resources :recent_contacts, only: [:index] # resource :private_message_details, only: [:show] # resource :unread_message_info, only: [:show] + + # 通知中心 + resources :messages, only: [:index, :create, :delete] do + collection do + post :read + end + end end resources :tidings, only: [:index] diff --git a/db/migrate/20210909030759_create_message_templates.rb b/db/migrate/20210909030759_create_message_templates.rb new file mode 100644 index 00000000..dbae7f55 --- /dev/null +++ b/db/migrate/20210909030759_create_message_templates.rb @@ -0,0 +1,11 @@ +class CreateMessageTemplates < ActiveRecord::Migration[5.2] + def change + create_table :message_templates do |t| + t.string :type + t.text :sys_notice + t.text :email + + t.timestamps + end + end +end diff --git a/public/docs/api.html b/public/docs/api.html index 35099a4e..b6083dcd 100644 --- a/public/docs/api.html +++ b/public/docs/api.html @@ -345,6 +345,18 @@
  • 获取当前登陆用户信息
  • +
  • + 用户消息列表 +
  • +
  • + 发送消息 +
  • +
  • + 阅读消息 +
  • +
  • + 删除消息 +
  • 更改用户信息
  • @@ -909,7 +921,7 @@ Success — a happy kitten is an authenticated kitten!

    Users

    获取当前登陆用户信息

    @@ -971,6 +983,435 @@ Success — a happy kitten is an authenticated kitten! +

    用户消息列表

    +

    获取用户消息列表

    + +
    +

    示例:

    +
    +
    curl -X GET http://localhost:3000/api/users/:login/messages.json
    +
    await octokit.request('GET /api/users/:login/messages.json')
    +

    HTTP 请求

    +

    GET api/users/yystopf/messages.json

    +

    请求字段说明:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数类型字段说明
    typestring消息类型,不传为所有消息,notification为系统消息,atme为@我消息
    statusinteger是否已读,不传为所有消息,0为未读,1为已读
    limitinteger每页个数
    pageinteger页码
    +

    返回字段说明:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数类型字段说明
    total_countinteger消息总数
    typestring消息类型
    unread_notificationinteger未读系统通知数量
    unread_atmeinteger未读@我数量
    messages.idinteger消息id
    messages.statusinteger消息是否已读,0为未读,1为已读
    messages.contentstring消息内容
    messages.notification_urlstring消息跳转地址
    messages.sourcestring消息来源
    messages.typestring消息类型,notification为系统消息,atme为@我消息
    senderobject消息发送者
    +

    消息来源source字段说明

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    类型说明
    IssueAssigned有新指派给我的易修
    IssueAssignerExpire我负责的易修截止日期到达最后一天
    IssueAtme在易修中@我
    IssueChanged我创建或负责的易修状态变更
    IssueCreatorExpire我创建的易修截止日期到达最后一天
    IssueDeleted我创建或负责的易修删除
    IssueJournal我创建或负责的易修有新的评论
    LoginIpTip登录异常提示
    OrganizationJoined账号被拉入组织
    OrganizationLeft账号被移出组织
    OrganizationRole账号组织权限变更
    ProjectDelete我关注的仓库被删除
    ProjectFollowed我管理的仓库被关注
    ProjectForked我管理的仓库被复刻
    ProjectIssue我管理/关注的仓库有新的易修
    ProjectJoined账号被拉入项目
    ProjectLeft账号被移出项目
    ProjectMemberJoined我管理的仓库有成员加入
    ProjectMemberLeft我管理的仓库有成员移出
    ProjectMilestone我管理的仓库有新的里程碑
    ProjectPraised我管理的仓库被点赞
    ProjectPullRequest我管理/关注的仓库有新的合并请求
    ProjectRole账号仓库权限变更
    ProjectSettingChanged我管理的仓库项目设置被更改
    ProjectTransfer我关注的仓库被转移
    ProjectVersion我关注的仓库有新的发行版
    PullRequestAssigned有新指派给我的合并请求
    PullReuqestAtme在合并请求中@我
    PullRequestChanged我创建或负责的合并请求状态变更
    PullRequestJournal我创建或负责的合并请求有新的评论
    + +
    +

    返回的JSON示例:

    +
    +
    {
    +    "total_count": 5,
    +    "type": "",
    +    "unread_notification": 3,
    +    "unread_atme": 2,
    +    "messages": [
    +        {
    +            "id": 1,
    +            "status": 1,
    +            "content": "Atme Message Content 1",
    +            "notification_url": "http://www.baidu.com",
    +            "source": "PullRequestAtme",
    +            "type": "atme",
    +            "sender": {
    +                "id": 5,
    +                "type": "User",
    +                "name": "testforge2",
    +                "login": "testforge2",
    +                "image_url": "system/lets/letter_avatars/2/T/236_177_85/120.png"
    +            }
    +        },
    +        {
    +            "id": 2,
    +            "status": 0,
    +            "content": "Atme Message Content 2",
    +            "notification_url": "http://www.baidu.com",
    +            "source": "IssueAtme",
    +            "type": "atme",
    +            "sender": {
    +                "id": 4,
    +                "type": "User",
    +                "name": "testforge1",
    +                "login": "testforge1",
    +                "image_url": "system/lets/letter_avatars/2/T/19_237_174/120.png"
    +            }
    +        },
    +        {
    +            "id": 3,
    +            "status": 1,
    +            "content": "Notification Message Content 1",
    +            "notification_url": "http://www.baidu.com",
    +            "source": "IssueDelete",
    +            "type": "notification"
    +        },
    +        {
    +            "id": 4,
    +            "status": 0,
    +            "content": "Notification Message Content 2",
    +            "notification_url": "http://www.baidu.com",
    +            "source": "IssueChanged",
    +            "type": "notification"
    +        },
    +        {
    +            "id": 5,
    +            "status": 0,
    +            "content": "Notification Message Content 3",
    +            "notification_url": "http://www.baidu.com",
    +            "source": "ProjectJoined",
    +            "type": "notification"
    +        }
    +    ]
    +}
    +
    + +

    发送消息

    +

    发送消息

    + +
    +

    示例:

    +
    +
    curl -X POST http://localhost:3000/api/users/:login/messages.json
    +
    await octokit.request('POST /api/users/:login/messages.json')
    +

    HTTP 请求

    +

    POST api/users/yystopf/messages.json

    +

    请求字段说明:

    + + + + + + + + + + + + + + + + + + + + + + +
    参数类型字段说明
    typestring消息类型
    recervers_loginarray需要发送消息的用户名数组
    contentstring消息内容
    + +
    +

    返回的JSON示例:

    +
    +
    {
    +    "status": 0,
    +    "message": "success"
    +}
    +
    + +

    阅读消息

    +

    阅读消息

    + +
    +

    示例:

    +
    +
    curl -X POST http://localhost:3000/api/users/:login/messages/read.json
    +
    await octokit.request('POST /api/users/:login/messages/read.json')
    +

    HTTP 请求

    +

    POST api/users/yystopf/messages/read.json

    +

    请求字段说明:

    + + + + + + + + + + + + + + + + + +
    参数类型字段说明
    typestring消息类型,不传为所有消息,notification为系统消息,atme为@我消息
    idsarray消息id数组,包含-1则把所有未读消息标记为已读
    + +
    +

    返回的JSON示例:

    +
    +
    {
    +    "status": 0,
    +    "message": "success"
    +}
    +
    + +

    删除消息

    +

    删除消息

    + +
    +

    示例:

    +
    +
    curl -X DELETE http://localhost:3000/api/users/:login/messages.json
    +
    await octokit.request('DELETE /api/users/:login/messages.json')
    +

    HTTP 请求

    +

    DELETE api/users/yystopf/messages.json

    +

    请求字段说明:

    + + + + + + + + + + + + + + + + + +
    参数类型字段说明
    typestring消息类型,atme为@我消息
    idsarray消息id数组,包含-1则把所有消息删除
    + +
    +

    返回的JSON示例:

    +
    +
    {
    +    "status": 0,
    +    "message": "success"
    +}
    +
    +

    更改用户信息

    更改用户信息

    @@ -979,9 +1420,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X PATCH/PUT http://localhost:3000/api/users/yystopf.json
     
    await octokit.request('PATCH/PUT /api/users/:login.json')
    -

    HTTP 请求

    +

    HTTP 请求

    PATCH/PUT /api/users/:login.json

    -

    请求字段说明:

    +

    请求字段说明:

    @@ -1077,9 +1518,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/is_pinned_projects.json
     
    await octokit.request('GET /api/users/:login/is_pinned_projects.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET api/users/:login/is_pinned_projects.json

    -

    返回字段说明:

    +

    返回字段说明:

    参数
    @@ -1264,9 +1705,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/is_pinned_projects/pin.json
     
    await octokit.request('GET /api/users/:login/is_pinned_projects/pin.json')
    -

    HTTP 请求

    +

    HTTP 请求

    POST /api/users/:login/is_pinned_projects/pin.json

    -

    请求字段说明:

    同时设定多个星标项目

    +

    请求字段说明:

    同时设定多个星标项目

    参数
    @@ -1310,9 +1751,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X PATCH http://localhost:3000/api/users/yystopf/is_pinned_projects/11.json
     
    await octokit.request('PATCH/PUT /api/users/:login/is_pinned_projects/:id.json')
    -

    HTTP 请求

    +

    HTTP 请求

    PATCH/PUT /api/users/:login/is_pinned_projects/:id.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -1351,9 +1792,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/activity.json
     
    await octokit.request('GET /api/users/:login/statistics/activity.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/activity.json

    -

    返回字段说明:

    +

    返回字段说明:

    参数
    @@ -1440,9 +1881,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/headmaps.json
     
    await octokit.request('GET /api/users/:login/headmaps.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET api/users/:login/headmaps.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -1456,7 +1897,7 @@ Success — a happy kitten is an authenticated kitten!
    参数年份
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -1585,9 +2026,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/project_trends.json
     
    await octokit.request('GET /api/users/:login/project_trends.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET api/users/:login/project_trends.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -1601,7 +2042,7 @@ Success — a happy kitten is an authenticated kitten!
    参数日期,格式: 2021-05-28
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -1902,9 +2343,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/develop.json
     
    await octokit.request('GET /api/users/:login/statistics/develop.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/develop.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -1923,7 +2364,7 @@ Success — a happy kitten is an authenticated kitten!
    参数时间戳,结束时间,格式:1622131200
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -2045,9 +2486,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/role.json
     
    await octokit.request('GET /api/users/:login/statistics/role.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/role.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2066,7 +2507,7 @@ Success — a happy kitten is an authenticated kitten!
    参数时间戳,结束时间,格式:1622131200
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -2127,9 +2568,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/major.json
     
    await octokit.request('GET /api/users/:login/statistics/major.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/major.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2148,7 +2589,7 @@ Success — a happy kitten is an authenticated kitten!
    参数时间戳,结束时间,格式:1622131200
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -2188,9 +2629,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/applied_messages.json
     
    await octokit.request('GET /api/users/:login/applied_messages.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_messages.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2204,7 +2645,7 @@ Success — a happy kitten is an authenticated kitten!
    参数用户标识
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -2467,9 +2908,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/applied_transfer_projects.json
     
    await octokit.request('GET /api/users/:login/applied_transfer_projects.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_transfer_projects.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2483,7 +2924,7 @@ Success — a happy kitten is an authenticated kitten!
    参数用户标识
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -2659,200 +3100,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/applied_transfer_projects/2/accept.json
     
    await octokit.request('GET /api/users/:login/applied_transfer_projects/:id/accept.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_transfer_projects/:id/accept.json

    -

    请求字段说明:

    -
    参数
    - - - - - - - - - - - - - - - - -
    参数类型字段说明
    loginstring用户标识
    idint迁移id
    -

    返回字段说明:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    参数类型字段说明
    idint迁移id
    statusstring迁移状态,canceled:取消,common:正在迁移, accept:已接受,refuse:已拒绝
    time_agostring迁移创建的时间
    project.idint迁移项目的id
    project.identifierstring迁移项目的标识
    project.namestring迁移项目的名称
    project.descriptionstring迁移项目的描述
    project.is_publicbool迁移项目是否公开
    project.owner.idbool迁移项目拥有者id
    project.owner.typestring迁移项目拥有者类型
    project.owner.namestring迁移项目拥有者昵称
    project.owner.loginstring迁移项目拥有者标识
    project.owner.image_urlstring迁移项目拥有者头像
    user.idint迁移创建者的id
    user.typestring迁移创建者的类型
    user.namestring迁移创建者的名称
    user.loginstring迁移创建者的标识
    user.image_urlstring迁移创建者头像
    owner.idint迁移接受者的id
    owner.typestring迁移接受者的类型
    owner.namestring迁移接受者的名称
    owner.loginstring迁移接受者的标识
    owner.image_urlstring迁移接受者头像
    - -
    -

    返回的JSON示例:

    -
    -
    {
    -    "project": {
    -        "id": 86,
    -        "identifier": "ceshi_repo1",
    -        "name": "测试项目啊1",
    -        "description": "二十多",
    -        "is_public": true,
    -        "owner": {
    -            "id": 52,
    -            "type": "Organization",
    -            "name": "身份卡手动阀",
    -            "login": "ceshi1",
    -            "image_url": "images/avatars/Organization/52?t=1618805056"
    -        }
    -    },
    -    "user": {
    -        "id": 6,
    -        "type": "User",
    -        "name": "yystopf",
    -        "login": "yystopf",
    -        "image_url": "system/lets/letter_avatars/2/Y/241_125_89/120.png"
    -    },
    -    "owner": {
    -        "id": 52,
    -        "type": "Organization",
    -        "name": "身份卡手动阀",
    -        "login": "ceshi1",
    -        "image_url": "images/avatars/Organization/52?t=1618805056"
    -    },
    -    "id": 1,
    -    "status": "canceled",
    -    "created_at": "2021-04-25 18:06",
    -    "time_ago": "16小时前"
    -}
    -

    用户拒绝迁移

    -

    用户拒绝迁移

    - -
    -

    示例:

    -
    -
    curl -X POST http://localhost:3000/api/users/yystopf/applied_transfer_projects/2/refuse.json
    -
    await octokit.request('GET /api/users/:login/applied_transfer_projects/:id/refuse.json')
    -

    HTTP 请求

    -

    GET /api/users/:login/applied_transfer_projects/:id/refuse.json

    -

    请求字段说明:

    +

    请求字段说明:

    @@ -2996,6 +3246,197 @@ Success — a happy kitten is an authenticated kitten!
    参数
    +
    +

    返回的JSON示例:

    +
    +
    {
    +    "project": {
    +        "id": 86,
    +        "identifier": "ceshi_repo1",
    +        "name": "测试项目啊1",
    +        "description": "二十多",
    +        "is_public": true,
    +        "owner": {
    +            "id": 52,
    +            "type": "Organization",
    +            "name": "身份卡手动阀",
    +            "login": "ceshi1",
    +            "image_url": "images/avatars/Organization/52?t=1618805056"
    +        }
    +    },
    +    "user": {
    +        "id": 6,
    +        "type": "User",
    +        "name": "yystopf",
    +        "login": "yystopf",
    +        "image_url": "system/lets/letter_avatars/2/Y/241_125_89/120.png"
    +    },
    +    "owner": {
    +        "id": 52,
    +        "type": "Organization",
    +        "name": "身份卡手动阀",
    +        "login": "ceshi1",
    +        "image_url": "images/avatars/Organization/52?t=1618805056"
    +    },
    +    "id": 1,
    +    "status": "canceled",
    +    "created_at": "2021-04-25 18:06",
    +    "time_ago": "16小时前"
    +}
    +

    用户拒绝迁移

    +

    用户拒绝迁移

    + +
    +

    示例:

    +
    +
    curl -X POST http://localhost:3000/api/users/yystopf/applied_transfer_projects/2/refuse.json
    +
    await octokit.request('GET /api/users/:login/applied_transfer_projects/:id/refuse.json')
    +

    HTTP 请求

    +

    GET /api/users/:login/applied_transfer_projects/:id/refuse.json

    +

    请求字段说明:

    + + + + + + + + + + + + + + + + + +
    参数类型字段说明
    loginstring用户标识
    idint迁移id
    +

    返回字段说明:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数类型字段说明
    idint迁移id
    statusstring迁移状态,canceled:取消,common:正在迁移, accept:已接受,refuse:已拒绝
    time_agostring迁移创建的时间
    project.idint迁移项目的id
    project.identifierstring迁移项目的标识
    project.namestring迁移项目的名称
    project.descriptionstring迁移项目的描述
    project.is_publicbool迁移项目是否公开
    project.owner.idbool迁移项目拥有者id
    project.owner.typestring迁移项目拥有者类型
    project.owner.namestring迁移项目拥有者昵称
    project.owner.loginstring迁移项目拥有者标识
    project.owner.image_urlstring迁移项目拥有者头像
    user.idint迁移创建者的id
    user.typestring迁移创建者的类型
    user.namestring迁移创建者的名称
    user.loginstring迁移创建者的标识
    user.image_urlstring迁移创建者头像
    owner.idint迁移接受者的id
    owner.typestring迁移接受者的类型
    owner.namestring迁移接受者的名称
    owner.loginstring迁移接受者的标识
    owner.image_urlstring迁移接受者头像
    +

    返回的JSON示例:

    @@ -3041,9 +3482,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/applied_projects.json
     
    await octokit.request('GET /api/users/:login/applied_projects.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_projects.json

    -

    请求字段说明:

    +

    请求字段说明:

    @@ -3057,7 +3498,7 @@ Success — a happy kitten is an authenticated kitten!
    参数用户标识
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -3201,9 +3642,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/applied_projects/2/accept.json
     
    await octokit.request('GET /api/users/:login/applied_projects/:id/accept.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_projects/:id/accept.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -3222,7 +3663,7 @@ Success — a happy kitten is an authenticated kitten!
    参数申请id
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -3360,9 +3801,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/applied_projects/2/refuse.json
     
    await octokit.request('GET /api/users/:login/applied_projects/:id/refuse.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_projects/:id/refuse.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -3381,7 +3822,7 @@ Success — a happy kitten is an authenticated kitten!
    参数申请id
    -

    返回字段说明:

    +

    返回字段说明:

    diff --git a/spec/models/message_template_spec.rb b/spec/models/message_template_spec.rb new file mode 100644 index 00000000..8f1d26fc --- /dev/null +++ b/spec/models/message_template_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe MessageTemplate, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end From 877a20350d080226e818165f981432ab34e5c662 Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 10 Sep 2021 16:05:08 +0800 Subject: [PATCH 020/135] fix: notice messages status value --- app/controllers/users/messages_controller.rb | 6 +++--- app/docs/slate/source/includes/_users.md | 11 ++++++++--- app/views/users/messages/_message.json.jbuilder | 2 ++ public/docs/api.html | 11 ++++++++--- 4 files changed, 21 insertions(+), 9 deletions(-) diff --git a/app/controllers/users/messages_controller.rb b/app/controllers/users/messages_controller.rb index 0433d41a..24c2a193 100644 --- a/app/controllers/users/messages_controller.rb +++ b/app/controllers/users/messages_controller.rb @@ -25,7 +25,7 @@ class Users::MessagesController < Users::BaseController "sender": 4, "receiver": 2, "content": "Atme Message Content 2", - "status": 0, + "status": 2, "type": 2, "source": "IssueAtme", "notification_url": "http://www.baidu.com", @@ -47,7 +47,7 @@ class Users::MessagesController < Users::BaseController "sender": -1, "receiver": 2, "content": "Notification Message Content 2", - "status": 0, + "status": 2, "type": 1, "source": "IssueChanged", "notification_url": "http://www.baidu.com", @@ -58,7 +58,7 @@ class Users::MessagesController < Users::BaseController "sender": -1, "receiver": 2, "content": "Notification Message Content 3", - "status": 0, + "status": 2, "type": 1, "source": "ProjectJoined", "notification_url": "http://www.baidu.com", diff --git a/app/docs/slate/source/includes/_users.md b/app/docs/slate/source/includes/_users.md index f49fdcf6..71a16ee8 100644 --- a/app/docs/slate/source/includes/_users.md +++ b/app/docs/slate/source/includes/_users.md @@ -1,7 +1,7 @@ # Users @@ -67,7 +67,7 @@ await octokit.request('GET /api/users/:login/messages.json') 参数 | 类型 | 字段说明 --------- | ----------- | ----------- |type | string | 消息类型,不传为所有消息,notification为系统消息,atme为@我消息| -|status | integer | 是否已读,不传为所有消息,0为未读,1为已读 | +|status | integer | 是否已读,不传为所有消息,1为未读,2为已读 | |limit | integer | 每页个数 | |page | integer | 页码 | @@ -79,7 +79,7 @@ await octokit.request('GET /api/users/:login/messages.json') |unread_notification | integer | 未读系统通知数量 | |unread_atme | integer | 未读@我数量 | |messages.id | integer | 消息id | -|messages.status | integer | 消息是否已读,0为未读,1为已读 | +|messages.status | integer | 消息是否已读,1为未读,2为已读 | |messages.content | string | 消息内容 | |messages.notification_url | string | 消息跳转地址 | |messages.source | string | 消息来源 | @@ -136,6 +136,7 @@ await octokit.request('GET /api/users/:login/messages.json') "content": "Atme Message Content 1", "notification_url": "http://www.baidu.com", "source": "PullRequestAtme", + "time_ago": "1天前", "type": "atme", "sender": { "id": 5, @@ -151,6 +152,7 @@ await octokit.request('GET /api/users/:login/messages.json') "content": "Atme Message Content 2", "notification_url": "http://www.baidu.com", "source": "IssueAtme", + "time_ago": "1天前", "type": "atme", "sender": { "id": 4, @@ -166,6 +168,7 @@ await octokit.request('GET /api/users/:login/messages.json') "content": "Notification Message Content 1", "notification_url": "http://www.baidu.com", "source": "IssueDelete", + "time_ago": "1天前", "type": "notification" }, { @@ -174,6 +177,7 @@ await octokit.request('GET /api/users/:login/messages.json') "content": "Notification Message Content 2", "notification_url": "http://www.baidu.com", "source": "IssueChanged", + "time_ago": "1天前", "type": "notification" }, { @@ -182,6 +186,7 @@ await octokit.request('GET /api/users/:login/messages.json') "content": "Notification Message Content 3", "notification_url": "http://www.baidu.com", "source": "ProjectJoined", + "time_ago": "1天前", "type": "notification" } ] diff --git a/app/views/users/messages/_message.json.jbuilder b/app/views/users/messages/_message.json.jbuilder index 1d8a9b26..9f6f0c50 100644 --- a/app/views/users/messages/_message.json.jbuilder +++ b/app/views/users/messages/_message.json.jbuilder @@ -6,6 +6,8 @@ json.status message["status"] json.content message["content"] json.notification_url message["notification_url"] json.source message["source"] +json.time_ago time_from_now(message["created_at"].to_time) + case message["type"] when 1 json.type "notification" diff --git a/public/docs/api.html b/public/docs/api.html index b6083dcd..faabfbc7 100644 --- a/public/docs/api.html +++ b/public/docs/api.html @@ -921,7 +921,7 @@ Success — a happy kitten is an authenticated kitten!

    Users

    获取当前登陆用户信息

    @@ -1009,7 +1009,7 @@ Success — a happy kitten is an authenticated kitten!
    - + @@ -1058,7 +1058,7 @@ Success — a happy kitten is an authenticated kitten! - + @@ -1230,6 +1230,7 @@ Success — a happy kitten is an authenticated kitten! "content": "Atme Message Content 1", "notification_url": "http://www.baidu.com", "source": "PullRequestAtme", + "time_ago": "1天前", "type": "atme", "sender": { "id": 5, @@ -1245,6 +1246,7 @@ Success — a happy kitten is an authenticated kitten! "content": "Atme Message Content 2", "notification_url": "http://www.baidu.com", "source": "IssueAtme", + "time_ago": "1天前", "type": "atme", "sender": { "id": 4, @@ -1260,6 +1262,7 @@ Success — a happy kitten is an authenticated kitten! "content": "Notification Message Content 1", "notification_url": "http://www.baidu.com", "source": "IssueDelete", + "time_ago": "1天前", "type": "notification" }, { @@ -1268,6 +1271,7 @@ Success — a happy kitten is an authenticated kitten! "content": "Notification Message Content 2", "notification_url": "http://www.baidu.com", "source": "IssueChanged", + "time_ago": "1天前", "type": "notification" }, { @@ -1276,6 +1280,7 @@ Success — a happy kitten is an authenticated kitten! "content": "Notification Message Content 3", "notification_url": "http://www.baidu.com", "source": "ProjectJoined", + "time_ago": "1天前", "type": "notification" } ] From 465a3a67a59ca8f2e3f7d5b1c77bf542e72eb5a3 Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 13 Sep 2021 17:51:34 +0800 Subject: [PATCH 021/135] add: notice system api --- app/controllers/users/messages_controller.rb | 134 +++++++----------- app/forms/notice/write/create_atme_form.rb | 23 +++ .../notice/{ => read}/client_service.rb | 36 ++--- app/services/notice/read/count_service.rb | 25 ++++ app/services/notice/read/list_service.rb | 40 ++++++ .../notice/write/change_status_service.rb | 29 ++++ app/services/notice/write/client_service.rb | 108 ++++++++++++++ app/services/notice/write/create_service.rb | 37 +++++ app/services/notice/write/delete_service.rb | 27 ++++ config/configuration.yml.example | 4 +- config/routes.rb | 4 +- 11 files changed, 365 insertions(+), 102 deletions(-) create mode 100644 app/forms/notice/write/create_atme_form.rb rename app/services/notice/{ => read}/client_service.rb (65%) create mode 100644 app/services/notice/read/count_service.rb create mode 100644 app/services/notice/read/list_service.rb create mode 100644 app/services/notice/write/change_status_service.rb create mode 100644 app/services/notice/write/client_service.rb create mode 100644 app/services/notice/write/create_service.rb create mode 100644 app/services/notice/write/delete_service.rb diff --git a/app/controllers/users/messages_controller.rb b/app/controllers/users/messages_controller.rb index 24c2a193..8c704c1b 100644 --- a/app/controllers/users/messages_controller.rb +++ b/app/controllers/users/messages_controller.rb @@ -1,110 +1,80 @@ class Users::MessagesController < Users::BaseController before_action :private_user_resources! + before_action :find_receivers, only: [:create] def index - data = { - "receiver": 2, - "type": @message_type, - "unread_total": 5, - "unread_notification": 3, - "unread_atme": 2, - "records": [ - { - "id": 1, - "sender": 5, - "receiver": 2, - "content": "Atme Message Content 1", - "status": 1, - "type": 2, - "source": "PullRequestAtme", - "notification_url": "http://www.baidu.com", - "created_at": "2021-09-09 14:34:40" - }, - { - "id": 2, - "sender": 4, - "receiver": 2, - "content": "Atme Message Content 2", - "status": 2, - "type": 2, - "source": "IssueAtme", - "notification_url": "http://www.baidu.com", - "created_at": "2021-09-09 14:34:40" - }, - { - "id": 3, - "sender": -1, - "receiver": 2, - "content": "Notification Message Content 1", - "status": 1, - "type": 1, - "source": "IssueDelete", - "notification_url": "http://www.baidu.com", - "created_at": "2021-09-09 14:34:40" - }, - { - "id": 4, - "sender": -1, - "receiver": 2, - "content": "Notification Message Content 2", - "status": 2, - "type": 1, - "source": "IssueChanged", - "notification_url": "http://www.baidu.com", - "created_at": "2021-09-09 14:34:40" - }, - { - "id": 5, - "sender": -1, - "receiver": 2, - "content": "Notification Message Content 3", - "status": 2, - "type": 1, - "source": "ProjectJoined", - "notification_url": "http://www.baidu.com", - "created_at": "2021-09-09 14:34:40" - } - ], - "records_count": 5, - "page_num": 1, - "total_page_size": 1, - "page_size": 10 - } - result = [1, "请求成功", data] + limit = params[:limit] || params[:per_page] + limit = (limit.to_i.zero? || limit.to_i > 15) ? 15 : limit.to_i + page = params[:page].to_i.zero? ? 1 : params[:page].to_i + result = Notice::Read::ListService.call(observed_user.id, message_type, message_status, page, limit) return render_error if result.nil? - puts result - @data = result[2].stringify_keys - + @data = result[2] end def create - return render_forbidden unless %w(3).include(@message_type) + return render_forbidden unless %w(atme).include?(params[:type]) + case params[:type] + when 'atme' + Notice::Write::CreateAtmeForm.new(atme_params).validate! + result = Notice::Write::CreateService.call(@receivers.pluck(:id), '发送了一个@我消息', base_url, "IssueAtme", 2) + return render_error if result.nil? + end render_ok + rescue Exception => e + uid_logger_error(e.message) + tip_exception(e.message) end def delete - return render_forbidden unless %w(2).include(@message_type) + return render_forbidden unless %w(atme).include?(params[:type]) + result = Notice::Write::DeleteService.call(params[:ids], observed_user.id) + return render_error if result.nil? + render_ok + rescue Exception => e + uid_logger_error(e.message) + tip_exception(e.message) end def read - render_ok + return render_forbidden unless %w(notification atme).include?(params[:type]) + result = Notice::Write::ChangeStatusService.call(params[:ids], observed_user.id) + if result.nil? + render_error + else + render_ok + end + rescue Exception => e + uid_logger_error(e.message) + tip_exception(e.message) end private def message_type @message_type = begin case params[:type] - when "notification" - 1 - when "atme" - 2 + when "notification" then 1 + when "atme" then 2 else -1 end end end + def message_status + @message_status = begin + case params[:status] + when "1" then 1 + else + 2 + end + end + end + + def atme_params + params.permit(:atmeable_type, :atmeable_id, receivers_login: []) + end + def message_params { sender: current_user.id, @@ -114,8 +84,8 @@ class Users::MessagesController < Users::BaseController } end - - def find_receiver - @receiver = User.find_by(login: params[:receiver_login]) + def find_receivers + @receivers = User.where(login: params[:receivers_login]) + return render_not_found if @receivers.size == 0 end end \ No newline at end of file diff --git a/app/forms/notice/write/create_atme_form.rb b/app/forms/notice/write/create_atme_form.rb new file mode 100644 index 00000000..5ac3acc2 --- /dev/null +++ b/app/forms/notice/write/create_atme_form.rb @@ -0,0 +1,23 @@ +class Notice::Write::CreateAtmeForm + include ActiveModel::Model + + attr_accessor :receivers_login, :atmeable_type, :atmeable_id + + validate :check_receivers + + def check_receivers + receivers_login.each do |login| + receiver = User.find_by(login: login) || User.find_by_id(login) + raise 'receivers_login值无效.' unless receiver.present? + end + end + + def check_atmeable + begin + raise 'atmeable对象无效.' unless atmeable_type.constantize.find_by_id(atmeable_id).present? + rescue => exception + raise 'atmeable对象无效.' + end + end + +end \ No newline at end of file diff --git a/app/services/notice/client_service.rb b/app/services/notice/read/client_service.rb similarity index 65% rename from app/services/notice/client_service.rb rename to app/services/notice/read/client_service.rb index a2ada88c..39ba816c 100644 --- a/app/services/notice/client_service.rb +++ b/app/services/notice/read/client_service.rb @@ -1,4 +1,4 @@ -class Notice::ClientService < ApplicationService +class Notice::Read::ClientService < ApplicationService attr_reader :url, :params def initialize(options={}) @@ -7,7 +7,7 @@ class Notice::ClientService < ApplicationService end def post(url, params={}) - puts "[notice][POST] request params: #{params}" + puts "[notice][read][POST] request params: #{params}" conn.post do |req| req.url = full_url(url) req.body = params[:data].to_json @@ -15,7 +15,7 @@ class Notice::ClientService < ApplicationService end def get(url, params={}) - puts "[notice][GET] request params: #{params}" + puts "[notice][read][GET] request params: #{params}" conn.get do |req| req.url full_url(url, 'get') params.each_pair do |key, value| @@ -25,31 +25,31 @@ class Notice::ClientService < ApplicationService end def delete(url, params={}) - puts "[notice][DELETE] request params: #{params}" + puts "[notice][read][DELETE] request params: #{params}" conn.delete do |req| req.url full_url(url) - reb.body = params[:data].to_json + req.body = params[:data].to_json end end def patch(url, params={}) - puts "[notice][PATCH] request params: #{params}" + puts "[notice][read][PATCH] request params: #{params}" conn.patch do |req| req.url full_url(url) - reb.body = params[:data].to_json + req.body = params[:data].to_json end end def put(url, params={}) - puts "[notice][PUT] request params: #{params}" + puts "[notice][read][PUT] request params: #{params}" conn.put do |req| req.url full_url(url) - reb.body = params[:data].to_json + req.body = params[:data].to_json end end #private - def conn + def conn @client ||= begin Faraday.new(url: domain) do |req| req.request :url_encoded @@ -66,7 +66,7 @@ class Notice::ClientService < ApplicationService end def domain - Notice.notice_config[:domain] + Notice.notice_config[:read_domain] end def platform @@ -74,25 +74,25 @@ class Notice::ClientService < ApplicationService end def api_url - [domain, base_url].join('') + [domain, base_url, "/#{platform}"].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 "[notice] request url: #{url}" + puts "[notice][read] request url: #{url}" return url end def log_error(status, body) - puts "[notice] status: #{status}" - puts "[notice] body: #{body&.force_encoding('UTF-8')}" + puts "[notice][read] status: #{status}" + puts "[notice][read] body: #{body}" end def render_response(response) status = response.status - body = response&.body + body = JSON.parse(response&.body) log_error(status, body) @@ -100,8 +100,8 @@ class Notice::ClientService < ApplicationService if body["code"] == 1 return [body["code"], body["message"], body["data"]] else - puts "[notice][ERROR] code: #{body["code"]}" - puts "[notice][ERROR] message: #{body["message"]}" + puts "[notice][read][ERROR] code: #{body["code"]}" + puts "[notice][read][ERROR] message: #{body["message"]}" end end end diff --git a/app/services/notice/read/count_service.rb b/app/services/notice/read/count_service.rb new file mode 100644 index 00000000..502d57a6 --- /dev/null +++ b/app/services/notice/read/count_service.rb @@ -0,0 +1,25 @@ +class Notice::Read::CountService < Notice::Read::ClientService + attr_accessor :receiver, :type + + def initialize(receiver, type=-1) + @receiver = receiver + @type = type + end + + def call + result = get(url, request_params) + response = render_response(result) + end + + private + def request_params + { + receiver: receiver, + type: type + }.stringify_keys + end + + def url + "/count".freeze + end +end \ No newline at end of file diff --git a/app/services/notice/read/list_service.rb b/app/services/notice/read/list_service.rb new file mode 100644 index 00000000..69c5c57c --- /dev/null +++ b/app/services/notice/read/list_service.rb @@ -0,0 +1,40 @@ +class Notice::Read::ListService < Notice::Read::ClientService + attr_accessor :receiver, :type, :status, :page, :size + + def initialize(receiver, type=-1, status=2, page=1, size=15) + @receiver = receiver + @type = type + @status = status + @page = page + @size = size + end + + def call + result = get(url, request_params) + response = render_response(result) + end + + private + + def request_status + case status + when 1 then 1 + else + 2 + end + end + + def request_params + { + receiver: receiver, + page: page, + show: request_status, + size: size, + type: type + }.stringify_keys + end + + def url + "/list".freeze + end +end \ No newline at end of file diff --git a/app/services/notice/write/change_status_service.rb b/app/services/notice/write/change_status_service.rb new file mode 100644 index 00000000..c6a9b06c --- /dev/null +++ b/app/services/notice/write/change_status_service.rb @@ -0,0 +1,29 @@ +class Notice::Write::ChangeStatusService < Notice::Write::ClientService + attr_accessor :notification_ids, :receiver, :status + + def initialize(notification_ids, receiver, status=2) + @notification_ids = notification_ids + @receiver = receiver + @status = status + end + + def call + result = put("", request_params) + response = render_response(result) + end + + private + + def request_notification_ids + notification_ids.join(",") + end + + def request_params + Hash.new.merge(data: { + notificationIds: request_notification_ids, + receiver: receiver, + status: status + }.stringify_keys) + end + +end \ No newline at end of file diff --git a/app/services/notice/write/client_service.rb b/app/services/notice/write/client_service.rb new file mode 100644 index 00000000..51ba5656 --- /dev/null +++ b/app/services/notice/write/client_service.rb @@ -0,0 +1,108 @@ +class Notice::Write::ClientService < ApplicationService + attr_reader :url, :params + + def initialize(options={}) + @url = options[:url] + @params = options[:params] + end + + def post(url, params={}) + puts "[notice][write][POST] request params: #{params}" + conn.post do |req| + req.url full_url(url) + req.body = params[:data].to_json + end + end + + def get(url, params={}) + puts "[notice][write][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 delete(url, params={}) + puts "[notice][write][DELETE] request params: #{params}" + conn.delete do |req| + req.url full_url(url) + req.body = params[:data].to_json + end + end + + def patch(url, params={}) + puts "[notice][write][PATCH] request params: #{params}" + conn.patch do |req| + req.url full_url(url) + req.body = params[:data].to_json + end + end + + def put(url, params={}) + puts "[notice][write][PUT] request params: #{params}" + conn.put do |req| + req.url full_url(url) + req.body = params[:data].to_json + 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 + Notice.notice_config[:base_url] + end + + def domain + Notice.notice_config[:write_domain] + end + + def platform + Notice.notice_config[:platform] + end + + def api_url + [domain, base_url, "/#{platform}"].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 "[notice][write] request url: #{url}" + return url + end + + def log_error(status, body) + puts "[notice][write] status: #{status}" + puts "[notice][write] body: #{body}" + end + + def render_response(response) + status = response.status + body = JSON.parse(response&.body) + + log_error(status, body) + + if status == 200 + if body["code"] == 1 + return [body["code"], body["message"], body["data"]] + else + puts "[notice][write][ERROR] code: #{body["code"]}" + puts "[notice][write][ERROR] message: #{body["message"]}" + end + end + end +end \ No newline at end of file diff --git a/app/services/notice/write/create_service.rb b/app/services/notice/write/create_service.rb new file mode 100644 index 00000000..76883c67 --- /dev/null +++ b/app/services/notice/write/create_service.rb @@ -0,0 +1,37 @@ +class Notice::Write::CreateService < Notice::Write::ClientService + attr_accessor :receivers, :sender, :content, :notification_url, :source, :extra, :type + + def initialize(receivers, content, notification_url, source, type=1, extra={},sender=-1) + @receivers = receivers + @sender = sender + @content = content + @notification_url = notification_url + @source = source + @extra = extra + @type = type + end + + def call + result = post("", request_params) + response = render_response(result) + end + + private + + def request_receivers + receivers.join(",") + end + + def request_params + Hash.new.merge(data: { + receivers: request_receivers, + sender: sender, + content: content, + notification_url: notification_url, + source: source, + extra: extra.to_json.to_s, + type: type + }.stringify_keys) + end + +end \ No newline at end of file diff --git a/app/services/notice/write/delete_service.rb b/app/services/notice/write/delete_service.rb new file mode 100644 index 00000000..d2f0a9fd --- /dev/null +++ b/app/services/notice/write/delete_service.rb @@ -0,0 +1,27 @@ +class Notice::Write::DeleteService < Notice::Write::ClientService + attr_accessor :notification_ids, :receiver + + def initialize(notification_ids, receiver) + @notification_ids = notification_ids + @receiver = receiver + end + + def call + result = delete("", request_params) + response = render_response(result) + end + + private + + def request_notification_ids + notification_ids.join(",") + end + + def request_params + Hash.new.merge(data: { + notificationIds: request_notification_ids, + receiver: receiver + }.stringify_keys) + end + +end \ No newline at end of file diff --git a/config/configuration.yml.example b/config/configuration.yml.example index 61217d4e..4671e416 100644 --- a/config/configuration.yml.example +++ b/config/configuration.yml.example @@ -58,7 +58,9 @@ default: &default base_url: '/api/v1' notice: - domain: '' + platform: '' + write_domain: '' + read_domain: '' base_url: '' production: diff --git a/config/routes.rb b/config/routes.rb index 2d5bb9ed..06b634fc 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -302,11 +302,13 @@ Rails.application.routes.draw do # resource :unread_message_info, only: [:show] # 通知中心 - resources :messages, only: [:index, :create, :delete] do + resources :messages, only: [:index, :create] do collection do post :read + end end + delete 'messages', to: 'messages#delete' end resources :tidings, only: [:index] From 8ad087820efa3a1fc5c47d6c91d72c123bc1cc0c Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 13 Sep 2021 18:03:57 +0800 Subject: [PATCH 022/135] fix: message api doc --- app/docs/slate/source/includes/_users.md | 20 ++++++++++++++--- public/docs/api.html | 28 ++++++++++++++++++++---- 2 files changed, 41 insertions(+), 7 deletions(-) diff --git a/app/docs/slate/source/includes/_users.md b/app/docs/slate/source/includes/_users.md index 71a16ee8..b43ca410 100644 --- a/app/docs/slate/source/includes/_users.md +++ b/app/docs/slate/source/includes/_users.md @@ -1,7 +1,7 @@ # Users @@ -83,6 +83,7 @@ await octokit.request('GET /api/users/:login/messages.json') |messages.content | string | 消息内容 | |messages.notification_url | string | 消息跳转地址 | |messages.source | string | 消息来源 | +|messages.timeago | string | 消息时间 | |messages.type | string | 消息类型,notification为系统消息,atme为@我消息| |sender | object | 消息发送者 | @@ -197,7 +198,7 @@ await octokit.request('GET /api/users/:login/messages.json') ## 发送消息 -发送消息 +发送消息, 目前只支持atme > 示例: @@ -217,7 +218,20 @@ await octokit.request('POST /api/users/:login/messages.json') --------- | ----------- | ----------- |type | string | 消息类型 | |recervers_login | array | 需要发送消息的用户名数组| -|content | string | 消息内容 | +|atmeable_type | string | atme消息对象,是从哪里@我的,比如评论:Journal | +|atmeable_id | integer | atme消息对象id | + +> 请求的JSON示例: + +```json +{ + "type": "atme", + "receivers_login": ["yystopf", "testforge1"], + "atmeable_type": "Journal", + "atmeable_id": 67 +} +``` + > 返回的JSON示例: diff --git a/public/docs/api.html b/public/docs/api.html index faabfbc7..94b17743 100644 --- a/public/docs/api.html +++ b/public/docs/api.html @@ -921,7 +921,7 @@ Success — a happy kitten is an authenticated kitten!

    Users

    获取当前登陆用户信息

    @@ -1076,6 +1076,11 @@ Success — a happy kitten is an authenticated kitten!
    + + + + + @@ -1290,7 +1295,7 @@ Success — a happy kitten is an authenticated kitten! Success Data.

    发送消息

    -

    发送消息

    +

    发送消息, 目前只支持atme

    示例:

    @@ -1318,12 +1323,27 @@ Success — a happy kitten is an authenticated kitten!
    - + - + + + + + +
    参数
    status integer是否已读,不传为所有消息,0为未读,1为已读是否已读,不传为所有消息,1为未读,2为已读
    limit
    messages.status integer消息是否已读,0为未读,1为已读消息是否已读,1为未读,2为已读
    messages.content消息来源
    messages.timeagostring消息时间
    messages.type string 消息类型,notification为系统消息,atme为@我消息 需要发送消息的用户名数组
    contentatmeable_type string消息内容atme消息对象,是从哪里@我的,比如评论:Journal
    atmeable_idintegeratme消息对象id
    +
    +

    请求的JSON示例:

    +
    +
    {
    +    "type": "atme",
    +    "receivers_login": ["yystopf", "testforge1"],
    +    "atmeable_type": "Journal",
    +    "atmeable_id": 67
    +}
    +

    返回的JSON示例:

    From a0b60413940ba5a105a327511da9f25e38e0441d Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 13 Sep 2021 18:17:09 +0800 Subject: [PATCH 023/135] add: get user info unread total --- app/controllers/users_controller.rb | 2 ++ app/views/users/get_user_info.json.jbuilder | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 470c6143..c69dfdb6 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -91,6 +91,8 @@ class UsersController < ApplicationController def get_user_info begin @user = current_user + result = Notice::Read::CountService.call(current_user.id) + @message_unread_total = result.nil? ? 0 : result[2]["unread_notification"] # TODO 等消息上线再打开注释 #@tidding_count = unviewed_tiddings(current_user) if current_user.present? rescue Exception => e diff --git a/app/views/users/get_user_info.json.jbuilder b/app/views/users/get_user_info.json.jbuilder index bf5ab882..ff20f803 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 5 \ No newline at end of file +json.message_unread_total @message_unread_total \ No newline at end of file From a8c75f3b20e7967241ba1f8e03e945fdcd653952 Mon Sep 17 00:00:00 2001 From: yystopf Date: Tue, 14 Sep 2021 11:21:58 +0800 Subject: [PATCH 024/135] fix: messages list status select --- app/controllers/users/messages_controller.rb | 12 ++---------- app/services/notice/read/list_service.rb | 10 +--------- 2 files changed, 3 insertions(+), 19 deletions(-) diff --git a/app/controllers/users/messages_controller.rb b/app/controllers/users/messages_controller.rb index 8c704c1b..efff9e01 100644 --- a/app/controllers/users/messages_controller.rb +++ b/app/controllers/users/messages_controller.rb @@ -65,8 +65,9 @@ class Users::MessagesController < Users::BaseController @message_status = begin case params[:status] when "1" then 1 + when "2" then 2 else - 2 + -1 end end end @@ -75,15 +76,6 @@ class Users::MessagesController < Users::BaseController params.permit(:atmeable_type, :atmeable_id, receivers_login: []) end - def message_params - { - sender: current_user.id, - reservers: @receiver.id, - type: @message_type, - content: params[:content] - } - end - def find_receivers @receivers = User.where(login: params[:receivers_login]) return render_not_found if @receivers.size == 0 diff --git a/app/services/notice/read/list_service.rb b/app/services/notice/read/list_service.rb index 69c5c57c..e4b1fda4 100644 --- a/app/services/notice/read/list_service.rb +++ b/app/services/notice/read/list_service.rb @@ -16,19 +16,11 @@ class Notice::Read::ListService < Notice::Read::ClientService private - def request_status - case status - when 1 then 1 - else - 2 - end - end - def request_params { receiver: receiver, page: page, - show: request_status, + status: status, size: size, type: type }.stringify_keys From 91676492ab2f9dbc88bc7ff674d1a71f878e6664 Mon Sep 17 00:00:00 2001 From: yystopf Date: Tue, 14 Sep 2021 13:59:23 +0800 Subject: [PATCH 025/135] fix: some detail for messages --- api_document.md | 8 ++++---- app/controllers/users/messages_controller.rb | 6 +++--- app/services/notice/write/change_status_service.rb | 6 ++++-- app/services/notice/write/delete_service.rb | 8 +++++--- 4 files changed, 16 insertions(+), 12 deletions(-) diff --git a/api_document.md b/api_document.md index 8a579f8e..3f609ed3 100644 --- a/api_document.md +++ b/api_document.md @@ -26,11 +26,11 @@ POST accounts/remote_register *示例* ```bash curl -X POST \ --d "email=2456233122@qq.com" \ --d "password=djs_D_00001" \ --d "username=16895620" \ +-d "email=yystopf@163.com" \ +-d "password=a19960425" \ +-d "username=yystopf" \ -d "platform=forge" \ -http://localhost:3000/api/accounts/remote_register | jq +http://120.132.31.109:8080/api/accounts/remote_register | jq ``` *请求参数说明:* diff --git a/app/controllers/users/messages_controller.rb b/app/controllers/users/messages_controller.rb index efff9e01..648b38b1 100644 --- a/app/controllers/users/messages_controller.rb +++ b/app/controllers/users/messages_controller.rb @@ -16,7 +16,7 @@ class Users::MessagesController < Users::BaseController case params[:type] when 'atme' Notice::Write::CreateAtmeForm.new(atme_params).validate! - result = Notice::Write::CreateService.call(@receivers.pluck(:id), '发送了一个@我消息', base_url, "IssueAtme", 2) + result = Notice::Write::CreateService.call(@receivers.pluck(:id), '发送了一个@我消息', base_url, "IssueAtme", 2, {}, current_user.id) return render_error if result.nil? end render_ok @@ -27,7 +27,7 @@ class Users::MessagesController < Users::BaseController def delete return render_forbidden unless %w(atme).include?(params[:type]) - result = Notice::Write::DeleteService.call(params[:ids], observed_user.id) + result = Notice::Write::DeleteService.call(params[:ids], observed_user.id, message_type) return render_error if result.nil? render_ok @@ -38,7 +38,7 @@ class Users::MessagesController < Users::BaseController def read return render_forbidden unless %w(notification atme).include?(params[:type]) - result = Notice::Write::ChangeStatusService.call(params[:ids], observed_user.id) + result = Notice::Write::ChangeStatusService.call(params[:ids], observed_user.id, message_type) if result.nil? render_error else diff --git a/app/services/notice/write/change_status_service.rb b/app/services/notice/write/change_status_service.rb index c6a9b06c..9091d211 100644 --- a/app/services/notice/write/change_status_service.rb +++ b/app/services/notice/write/change_status_service.rb @@ -1,9 +1,10 @@ class Notice::Write::ChangeStatusService < Notice::Write::ClientService - attr_accessor :notification_ids, :receiver, :status + attr_accessor :notification_ids, :receiver, :type, :status - def initialize(notification_ids, receiver, status=2) + def initialize(notification_ids, receiver, type=-1, status=2) @notification_ids = notification_ids @receiver = receiver + @type = type @status = status end @@ -22,6 +23,7 @@ class Notice::Write::ChangeStatusService < Notice::Write::ClientService Hash.new.merge(data: { notificationIds: request_notification_ids, receiver: receiver, + type: type, status: status }.stringify_keys) end diff --git a/app/services/notice/write/delete_service.rb b/app/services/notice/write/delete_service.rb index d2f0a9fd..82ab904a 100644 --- a/app/services/notice/write/delete_service.rb +++ b/app/services/notice/write/delete_service.rb @@ -1,9 +1,10 @@ class Notice::Write::DeleteService < Notice::Write::ClientService - attr_accessor :notification_ids, :receiver + attr_accessor :notification_ids, :receiver, :type - def initialize(notification_ids, receiver) + def initialize(notification_ids, receiver, type=-1) @notification_ids = notification_ids @receiver = receiver + @type = type end def call @@ -20,7 +21,8 @@ class Notice::Write::DeleteService < Notice::Write::ClientService def request_params Hash.new.merge(data: { notificationIds: request_notification_ids, - receiver: receiver + receiver: receiver, + type: type }.stringify_keys) end From ca4f416f0ac9a259c6f1467582729e72a476f537 Mon Sep 17 00:00:00 2001 From: yystopf Date: Tue, 14 Sep 2021 17:39:58 +0800 Subject: [PATCH 026/135] add: message template content --- app/docs/slate/source/includes/_users.md | 8 ++- app/models/message_template.rb | 55 ++++++++++++++++--- app/models/message_template/followed_tip.rb | 16 ++++++ app/models/message_template/issue_assigned.rb | 13 +++-- .../message_template/issue_assigner_expire.rb | 13 +++-- app/models/message_template/issue_atme.rb | 15 ++--- app/models/message_template/issue_changed.rb | 13 +++-- .../message_template/issue_creator_expire.rb | 13 +++-- app/models/message_template/issue_deleted.rb | 13 +++-- app/models/message_template/issue_journal.rb | 13 +++-- app/models/message_template/login_ip_tip.rb | 13 +++-- .../message_template/organization_joined.rb | 13 +++-- .../message_template/organization_left.rb | 13 +++-- .../message_template/organization_role.rb | 13 +++-- app/models/message_template/project_delete.rb | 15 ----- .../message_template/project_deleted.rb | 16 ++++++ .../message_template/project_followed.rb | 13 +++-- app/models/message_template/project_forked.rb | 13 +++-- app/models/message_template/project_issue.rb | 13 +++-- app/models/message_template/project_joined.rb | 13 +++-- app/models/message_template/project_left.rb | 13 +++-- .../message_template/project_member_joined.rb | 13 +++-- .../message_template/project_member_left.rb | 13 +++-- .../message_template/project_milestone.rb | 13 +++-- .../message_template/project_praised.rb | 13 +++-- .../message_template/project_pull_request.rb | 13 +++-- app/models/message_template/project_role.rb | 13 +++-- .../project_setting_changed.rb | 13 +++-- .../message_template/project_transfer.rb | 15 ++--- .../message_template/project_version.rb | 13 +++-- .../message_template/pull_request_assigned.rb | 13 +++-- .../message_template/pull_request_atme.rb | 2 +- .../message_template/pull_request_changed.rb | 13 +++-- .../message_template/pull_request_closed.rb | 16 ++++++ .../message_template/pull_request_journal.rb | 13 +++-- .../message_template/pull_request_merged.rb | 16 ++++++ ...d_notification_url_to_message_templates.rb | 5 ++ public/docs/api.html | 12 +++- 38 files changed, 331 insertions(+), 198 deletions(-) create mode 100644 app/models/message_template/followed_tip.rb delete mode 100644 app/models/message_template/project_delete.rb create mode 100644 app/models/message_template/project_deleted.rb create mode 100644 app/models/message_template/pull_request_closed.rb create mode 100644 app/models/message_template/pull_request_merged.rb create mode 100644 db/migrate/20210914064456_add_notification_url_to_message_templates.rb diff --git a/app/docs/slate/source/includes/_users.md b/app/docs/slate/source/includes/_users.md index b43ca410..7225b90e 100644 --- a/app/docs/slate/source/includes/_users.md +++ b/app/docs/slate/source/includes/_users.md @@ -1,7 +1,7 @@ # Users @@ -101,7 +101,7 @@ await octokit.request('GET /api/users/:login/messages.json') |OrganizationJoined | 账号被拉入组织 | |OrganizationLeft | 账号被移出组织 | |OrganizationRole | 账号组织权限变更 | -|ProjectDelete | 我关注的仓库被删除 | +|ProjectDeleted | 我关注的仓库被删除 | |ProjectFollowed | 我管理的仓库被关注 | |ProjectForked | 我管理的仓库被复刻 | |ProjectIssue | 我管理/关注的仓库有新的易修 | @@ -119,7 +119,9 @@ await octokit.request('GET /api/users/:login/messages.json') |PullRequestAssigned | 有新指派给我的合并请求 | |PullReuqestAtme | 在合并请求中@我 | |PullRequestChanged | 我创建或负责的合并请求状态变更 | -|PullRequestJournal | 我创建或负责的合并请求有新的评论 | +|PullRequestClosed | 我创建或负责的合并请求被关闭 | +|PullRequestJournal | 我创建或负责的合并请求有新的评论 | +|PullRequestMerged | 我创建或负责的合并请求被合并 | > 返回的JSON示例: diff --git a/app/models/message_template.rb b/app/models/message_template.rb index f19b77fb..bee4ebae 100644 --- a/app/models/message_template.rb +++ b/app/models/message_template.rb @@ -2,13 +2,54 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # -class MessageTemplate < ApplicationRecord +class MessageTemplate {nickname}关注了你', notification_url: '{baseurl}/{login}') + self.create(type: 'MessageTemplate::IssueAssigned', sys_notice: '{nickname1}在{nickname2}/{repository}指派给你一个易修:{title}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') + self.create(type: 'MessageTemplate::IssueAssignerExpire', sys_notice: '您负责的易修{title}已临近截止日期,请尽快处理', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') + self.create(type: 'MessageTemplate::IssueAtme', sys_notice: '{nickname}在易修{title}中@我', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') + self.create(type: 'MessageTemplate::IssueChanged', sys_notice: '在项目{nickname2}/{repository1}的易修{title}中:{ifassigner}{nickname1}将负责人从{assigner1}修改为{assigner1}{endassigner}
    {ifstatus}{nickname1}将状态从{status1}修改为{status1}{endstatus}
    {iftracker}{nickname1}将类型从{tracker1}修改为{tracker1}{endtracker}
    {ifpriority}{nickname1}将优先度从{priority1}修改为{priority1}{endpriority}
    {ifmilestone}{nickname1}将里程碑从{milestone1}修改为{milestone1}{endmilestone}
    {iftag}{nickname1}将标签从{tag1}修改为{tag1}{endtag}
    {ifdoneratio}{nickname1}将完成度从{doneratio1}修改为{doneratio1}{enddoneratio}
    {ifbranch}{nickname1}将指定分支从{branch1}修改为{branch1}{endbranch}
    {ifstartdate}{nickname1}将开始日期从{startdate1}修改为{startdate1}{endstartdate}
    {ifduedate}{nickname1}将结束日期从{duedate1}修改为{duedate1}{endduedate}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') + self.create(type: 'MessageTemplate::IssueCreatorExpire', sys_notice: '您发布的易修{title}已临近截止日期,请尽快处理', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') + self.create(type: 'MessageTemplate::IssueDeleted', sys_notice: '{nickname}已将易修{title}删除', notification_url: '') + self.create(type: 'MessageTemplate::IssueJournal', sys_notice: '{nickname}评论易修{title}:{notes}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') + self.create(type: 'MessageTemplate::LoginIpTip', sys_notice: '您的账号{nickname}于{login_time)在非常用的IP地址{ip}登录,如非本人操作,请立即修改密码', notification_url: '') + self.create(type: 'MessageTemplate::OrganizationJoined', sys_notice: '你已加入{organization}组织', notification_url: '{baseurl}/{login}') + self.create(type: 'MessageTemplate::OrganizationLeft', sys_notice: '你已被移出{organization}组织', notification_url: '') + self.create(type: 'MessageTemplate::OrganizationRole', sys_notice: '组织{organization}已把你的角色改为{role}', notification_url: '{baseurl}/{owner}') + self.create(type: 'MessageTemplate::ProjectDeleted', sys_notice: '你关注的仓库{nickname}/{repository}已被删除', notification_url: '') + self.create(type: 'MessageTemplate::ProjectFollowed', sys_notice: '{nickname}关注了你管理的仓库', notification_url: '{baseurl}/{login}') + self.create(type: 'MessageTemplate::ProjectForked', sys_notice: '{nickname1}复刻了你管理的仓库{nickname1}/{repository1}到{nickname2}/{repository2}', notification_url: '{baseurl}/{owner}/{identifier}') + self.create(type: 'MessageTemplate::ProjectIssue', sys_notice: '{nickname1}在{nickname2}/{repository}新建易修:{title}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') + self.create(type: 'MessageTemplate::ProjectJoined', sys_notice: '你已加入{repository}项目', notification_url: '{baseurl}/{owner}/{identifier}') + self.create(type: 'MessageTemplate::ProjectLeft', sys_notice: '你已被移出{repository}项目', notification_url: '') + self.create(type: 'MessageTemplate::ProjectMemberJoined', sys_notice: '{nickname1}已加入项目{nickname2}/{repository}', notification_url: '{baseurl}/{owner}/{identifier}') + self.create(type: 'MessageTemplate::ProjectMemberLeft', sys_notice: '{nickname1}已被移出项目{nickname2}/{repository}', notification_url: '{baseurl}/{owner}/{identifier}') + self.create(type: 'MessageTemplate::ProjectMilestone', sys_notice: '{nickname1}在{nickname2}/{repository}创建了一个里程碑:{title}', notification_url: '{baseurl}/{owner}/{identifier}/milestones/{id}') + self.create(type: 'MessageTemplate::ProjectPraised', sys_notice: '{nickname}点赞了你管理的仓库', notification_url: '{baseurl}/{login}') + self.create(type: 'MessageTemplate::ProjectPullRequest', sys_notice: '{nickname1}在{nickname2}/{repository}提交了一个合并请求:{title}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') + self.create(type: 'MessageTemplate::ProjectRole', sys_notice: '仓库{repository}已把你的角色改为{role}', notification_url: '{baseurl}/{owner}/{identifier}') + self.create(type: 'MessageTemplate::ProjectSettingChanged', sys_notice: '{nickname1}更改了{nickname2}/{repository}仓库设置:{ifname}更改项目名称为"{name}";{endname}{ifdescription}更改项目简介为"{description}";{enddescription}{ifcategory}更改项目类别为"{category}";{endcategory}{iflanguage}更改项目语言为"{language}";{endlanguage}{ifpermission}将仓库设为"{permission}";{endpermission}{ifnavbar}将项目导航更改为"{navbar}";{endnavbar}', notification_url: '{baseurl}/{owner}/{identifier}/settings') + self.create(type: 'MessageTemplate::ProjectTransfer', sys_notice: '你关注的仓库{nickname1}/{repository1}已被转移至{nickname2}/{repository2}', notification_url: '{baseurl}/{owner}/{identifier}') + self.create(type: 'MessageTemplate::ProjectVersion', sys_notice: '{nickname1}在{nickname2}/{repository}创建了发行版:{title}', notification_url: '{baseurl}/{owner}/{identifier}/releases') + self.create(type: 'MessageTemplate::PullRequestAssigned', sys_notice: '{nickname1}在{nickname2}/{repository}指派给你一个合并请求:{title}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') + self.create(type: 'MessageTemplate::PullRequestAtme', sys_notice: '{nickname}在合并请求{title}中@我', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') + self.create(type: 'MessageTemplate::PullRequestChanged', sys_notice: '在项目{nickname2}/{repository1}的合并请求{title}中:{ifassigner}{nickname1}将审查成员从{assigner1}修改为{assigner1}{endassigner}
    {ifmilestone}{nickname1}将里程碑从{milestone1}修改为{milestone1}{endmilestone}
    {iftag}{nickname1}将标签从{tag1}修改为{tag1}{endtag}
    {ifpriority}{nickname1}将优先度从{priority1}修改为{priority1}{endpriority}
    ', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') + self.create(type: 'MessageTemplate::PullRequestClosed', sys_notice: '你提交的合并请求:{title]被拒绝', notification_url: '') + self.create(type: 'MessageTemplate::PullRequestJournal', sys_notice: '{nickname}评论合并请求{title}:{notes}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') + self.create(type: 'MessageTemplate::PullRequestMerged', sys_notice: '你提交的合并请求:{title}被合并', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') + end + + def self.sys_notice + self.last&.sys_notice + end end diff --git a/app/models/message_template/followed_tip.rb b/app/models/message_template/followed_tip.rb new file mode 100644 index 00000000..dd11982c --- /dev/null +++ b/app/models/message_template/followed_tip.rb @@ -0,0 +1,16 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) +# + +# 被关注提示 +class MessageTemplate::FollowedTip < MessageTemplate +end diff --git a/app/models/message_template/issue_assigned.rb b/app/models/message_template/issue_assigned.rb index 51e3e617..76e9781a 100644 --- a/app/models/message_template/issue_assigned.rb +++ b/app/models/message_template/issue_assigned.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 有新指派给我的易修 diff --git a/app/models/message_template/issue_assigner_expire.rb b/app/models/message_template/issue_assigner_expire.rb index 03af6163..b9afeae0 100644 --- a/app/models/message_template/issue_assigner_expire.rb +++ b/app/models/message_template/issue_assigner_expire.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 我负责的易修截止日期到达最后一天 diff --git a/app/models/message_template/issue_atme.rb b/app/models/message_template/issue_atme.rb index d0915582..2a87da11 100644 --- a/app/models/message_template/issue_atme.rb +++ b/app/models/message_template/issue_atme.rb @@ -2,14 +2,15 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 在易修中@我 class MessageTemplate::IssueAtme < MessageTemplate -end \ No newline at end of file +end diff --git a/app/models/message_template/issue_changed.rb b/app/models/message_template/issue_changed.rb index 98772ab0..0820d4bf 100644 --- a/app/models/message_template/issue_changed.rb +++ b/app/models/message_template/issue_changed.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 我创建或负责的易修状态变更 diff --git a/app/models/message_template/issue_creator_expire.rb b/app/models/message_template/issue_creator_expire.rb index ee194071..41c47152 100644 --- a/app/models/message_template/issue_creator_expire.rb +++ b/app/models/message_template/issue_creator_expire.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 我创建的易修截止日期到达最后一天 diff --git a/app/models/message_template/issue_deleted.rb b/app/models/message_template/issue_deleted.rb index d25fbffd..a6a0ef20 100644 --- a/app/models/message_template/issue_deleted.rb +++ b/app/models/message_template/issue_deleted.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 我创建或负责的易修删除 diff --git a/app/models/message_template/issue_journal.rb b/app/models/message_template/issue_journal.rb index 4252704c..e4f7572b 100644 --- a/app/models/message_template/issue_journal.rb +++ b/app/models/message_template/issue_journal.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 我创建或负责的易修有新的评论 diff --git a/app/models/message_template/login_ip_tip.rb b/app/models/message_template/login_ip_tip.rb index a86e03a5..898a30c7 100644 --- a/app/models/message_template/login_ip_tip.rb +++ b/app/models/message_template/login_ip_tip.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 登录异常提示 diff --git a/app/models/message_template/organization_joined.rb b/app/models/message_template/organization_joined.rb index 4440bb74..95c9611a 100644 --- a/app/models/message_template/organization_joined.rb +++ b/app/models/message_template/organization_joined.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 账号被拉入组织 diff --git a/app/models/message_template/organization_left.rb b/app/models/message_template/organization_left.rb index 9d346b7b..30df516e 100644 --- a/app/models/message_template/organization_left.rb +++ b/app/models/message_template/organization_left.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 账号被移出组织 diff --git a/app/models/message_template/organization_role.rb b/app/models/message_template/organization_role.rb index 1222a624..6ca82503 100644 --- a/app/models/message_template/organization_role.rb +++ b/app/models/message_template/organization_role.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 账号组织权限变更 diff --git a/app/models/message_template/project_delete.rb b/app/models/message_template/project_delete.rb deleted file mode 100644 index b03813f3..00000000 --- a/app/models/message_template/project_delete.rb +++ /dev/null @@ -1,15 +0,0 @@ -# == Schema Information -# -# Table name: message_templates -# -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null -# - -# 我关注的仓库被删除 -class MessageTemplate::ProjectDelete < MessageTemplate -end diff --git a/app/models/message_template/project_deleted.rb b/app/models/message_template/project_deleted.rb new file mode 100644 index 00000000..334c6d87 --- /dev/null +++ b/app/models/message_template/project_deleted.rb @@ -0,0 +1,16 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) +# + +# 我关注的仓库被删除 +class MessageTemplate::ProjectDeleted < MessageTemplate +end diff --git a/app/models/message_template/project_followed.rb b/app/models/message_template/project_followed.rb index 654e19c7..d7ade39e 100644 --- a/app/models/message_template/project_followed.rb +++ b/app/models/message_template/project_followed.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 我管理的仓库被关注 diff --git a/app/models/message_template/project_forked.rb b/app/models/message_template/project_forked.rb index 711460c0..b69892fa 100644 --- a/app/models/message_template/project_forked.rb +++ b/app/models/message_template/project_forked.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 我管理的仓库被复刻 diff --git a/app/models/message_template/project_issue.rb b/app/models/message_template/project_issue.rb index fc34d9a5..f657084a 100644 --- a/app/models/message_template/project_issue.rb +++ b/app/models/message_template/project_issue.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 我管理/关注的仓库有新的易修 diff --git a/app/models/message_template/project_joined.rb b/app/models/message_template/project_joined.rb index 6d21a39e..1da83b0c 100644 --- a/app/models/message_template/project_joined.rb +++ b/app/models/message_template/project_joined.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 账号被拉入项目 diff --git a/app/models/message_template/project_left.rb b/app/models/message_template/project_left.rb index f95467f0..63923502 100644 --- a/app/models/message_template/project_left.rb +++ b/app/models/message_template/project_left.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 账号被移出项目 diff --git a/app/models/message_template/project_member_joined.rb b/app/models/message_template/project_member_joined.rb index 6e4e1acc..0b402545 100644 --- a/app/models/message_template/project_member_joined.rb +++ b/app/models/message_template/project_member_joined.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 我管理的仓库有成员加入 diff --git a/app/models/message_template/project_member_left.rb b/app/models/message_template/project_member_left.rb index 3259034d..ed261e0f 100644 --- a/app/models/message_template/project_member_left.rb +++ b/app/models/message_template/project_member_left.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 我管理的仓库有成员移出 diff --git a/app/models/message_template/project_milestone.rb b/app/models/message_template/project_milestone.rb index b1ff0b9e..b28766c5 100644 --- a/app/models/message_template/project_milestone.rb +++ b/app/models/message_template/project_milestone.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 我管理的仓库有新的里程碑 diff --git a/app/models/message_template/project_praised.rb b/app/models/message_template/project_praised.rb index ebbdfd93..ec7a0564 100644 --- a/app/models/message_template/project_praised.rb +++ b/app/models/message_template/project_praised.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 我管理的仓库被点赞 diff --git a/app/models/message_template/project_pull_request.rb b/app/models/message_template/project_pull_request.rb index b1706eb9..43a8359b 100644 --- a/app/models/message_template/project_pull_request.rb +++ b/app/models/message_template/project_pull_request.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 我管理/关注的仓库有新的合并请求 diff --git a/app/models/message_template/project_role.rb b/app/models/message_template/project_role.rb index a59df536..95ebe5ba 100644 --- a/app/models/message_template/project_role.rb +++ b/app/models/message_template/project_role.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 账号仓库权限变更 diff --git a/app/models/message_template/project_setting_changed.rb b/app/models/message_template/project_setting_changed.rb index 1c4040f5..b983e6c6 100644 --- a/app/models/message_template/project_setting_changed.rb +++ b/app/models/message_template/project_setting_changed.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 我管理的仓库项目设置被更改 diff --git a/app/models/message_template/project_transfer.rb b/app/models/message_template/project_transfer.rb index 38998d03..ce422f09 100644 --- a/app/models/message_template/project_transfer.rb +++ b/app/models/message_template/project_transfer.rb @@ -2,14 +2,15 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 我关注的仓库被转移 class MessageTemplate::ProjectTransfer < MessageTemplate -end \ No newline at end of file +end diff --git a/app/models/message_template/project_version.rb b/app/models/message_template/project_version.rb index 330dfe95..afc25fc4 100644 --- a/app/models/message_template/project_version.rb +++ b/app/models/message_template/project_version.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 我关注的仓库有新的发行版 diff --git a/app/models/message_template/pull_request_assigned.rb b/app/models/message_template/pull_request_assigned.rb index 1be86530..d6d497da 100644 --- a/app/models/message_template/pull_request_assigned.rb +++ b/app/models/message_template/pull_request_assigned.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 有新指派给我的合并请求 diff --git a/app/models/message_template/pull_request_atme.rb b/app/models/message_template/pull_request_atme.rb index afa7a400..5ff526fa 100644 --- a/app/models/message_template/pull_request_atme.rb +++ b/app/models/message_template/pull_request_atme.rb @@ -11,5 +11,5 @@ # # 在合并请求中@我 -class MessageTemplate::PullReuqestAtme < MessageTemplate +class MessageTemplate::PullRequestAtme < MessageTemplate end \ No newline at end of file diff --git a/app/models/message_template/pull_request_changed.rb b/app/models/message_template/pull_request_changed.rb index 002de3a2..dcde72b8 100644 --- a/app/models/message_template/pull_request_changed.rb +++ b/app/models/message_template/pull_request_changed.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 我创建或负责的合并请求状态变更 diff --git a/app/models/message_template/pull_request_closed.rb b/app/models/message_template/pull_request_closed.rb new file mode 100644 index 00000000..0574b640 --- /dev/null +++ b/app/models/message_template/pull_request_closed.rb @@ -0,0 +1,16 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) +# + +# 我创建或负责的合并请求被关闭 +class MessageTemplate::PullRequestClosed < MessageTemplate +end diff --git a/app/models/message_template/pull_request_journal.rb b/app/models/message_template/pull_request_journal.rb index 0f79d166..6d3b4fe3 100644 --- a/app/models/message_template/pull_request_journal.rb +++ b/app/models/message_template/pull_request_journal.rb @@ -2,12 +2,13 @@ # # Table name: message_templates # -# id :integer not null, primary key -# type :string(255) -# sys_notice :text(65535) -# email :text(65535) -# created_at :datetime not null -# updated_at :datetime not null +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) # # 我创建或负责的合并请求有新的评论 diff --git a/app/models/message_template/pull_request_merged.rb b/app/models/message_template/pull_request_merged.rb new file mode 100644 index 00000000..b06687cb --- /dev/null +++ b/app/models/message_template/pull_request_merged.rb @@ -0,0 +1,16 @@ +# == Schema Information +# +# Table name: message_templates +# +# id :integer not null, primary key +# type :string(255) +# sys_notice :text(65535) +# email :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# notification_url :string(255) +# + +# 我创建或负责的合并请求被合并 +class MessageTemplate::PullRequestMerged < MessageTemplate +end diff --git a/db/migrate/20210914064456_add_notification_url_to_message_templates.rb b/db/migrate/20210914064456_add_notification_url_to_message_templates.rb new file mode 100644 index 00000000..2adb842c --- /dev/null +++ b/db/migrate/20210914064456_add_notification_url_to_message_templates.rb @@ -0,0 +1,5 @@ +class AddNotificationUrlToMessageTemplates < ActiveRecord::Migration[5.2] + def change + add_column :message_templates, :notification_url, :string + end +end diff --git a/public/docs/api.html b/public/docs/api.html index 94b17743..6446d796 100644 --- a/public/docs/api.html +++ b/public/docs/api.html @@ -921,7 +921,7 @@ Success — a happy kitten is an authenticated kitten!

    Users

    获取当前登陆用户信息

    @@ -1143,7 +1143,7 @@ Success — a happy kitten is an authenticated kitten! 账号组织权限变更 -ProjectDelete +ProjectDeleted 我关注的仓库被删除 @@ -1215,9 +1215,17 @@ Success — a happy kitten is an authenticated kitten! 我创建或负责的合并请求状态变更 +PullRequestClosed +我创建或负责的合并请求被关闭 + + PullRequestJournal 我创建或负责的合并请求有新的评论 + +PullRequestMerged +我创建或负责的合并请求被合并 +
    From 65af40c29b87632c0397324526f857ef125598ef Mon Sep 17 00:00:00 2001 From: yystopf Date: Tue, 14 Sep 2021 23:04:33 +0800 Subject: [PATCH 027/135] add: join message content be necessary --- app/models/message_template.rb | 20 +++- app/models/message_template/followed_tip.rb | 7 ++ app/models/message_template/issue_assigned.rb | 12 ++ .../message_template/issue_assigner_expire.rb | 12 ++ app/models/message_template/issue_atme.rb | 12 ++ app/models/message_template/issue_changed.rb | 113 ++++++++++++++++++ .../message_template/issue_creator_expire.rb | 12 ++ app/models/message_template/issue_deleted.rb | 11 ++ app/models/message_template/issue_journal.rb | 10 +- app/models/message_template/login_ip_tip.rb | 10 +- .../message_template/organization_joined.rb | 10 ++ .../message_template/organization_left.rb | 10 ++ .../message_template/organization_role.rb | 10 ++ .../message_template/project_deleted.rb | 10 +- .../message_template/project_followed.rb | 10 +- app/models/message_template/project_forked.rb | 10 +- app/models/message_template/project_issue.rb | 10 +- app/models/message_template/project_joined.rb | 10 ++ app/models/message_template/project_left.rb | 9 ++ .../message_template/project_member_joined.rb | 10 +- .../message_template/project_member_left.rb | 10 +- .../message_template/project_milestone.rb | 10 +- .../message_template/project_praised.rb | 10 +- .../message_template/project_pull_request.rb | 10 +- app/models/message_template/project_role.rb | 10 ++ .../project_setting_changed.rb | 60 ++++++++++ .../message_template/project_transfer.rb | 10 +- .../message_template/project_version.rb | 10 +- .../message_template/pull_request_assigned.rb | 12 ++ .../message_template/pull_request_atme.rb | 12 ++ .../message_template/pull_request_changed.rb | 54 +++++++++ .../message_template/pull_request_closed.rb | 12 ++ .../message_template/pull_request_journal.rb | 10 +- .../message_template/pull_request_merged.rb | 12 ++ 34 files changed, 542 insertions(+), 18 deletions(-) diff --git a/app/models/message_template.rb b/app/models/message_template.rb index bee4ebae..6c5e4df2 100644 --- a/app/models/message_template.rb +++ b/app/models/message_template.rb @@ -18,14 +18,14 @@ class MessageTemplate {nickname2}/{repository}指派给你一个易修:{title}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') self.create(type: 'MessageTemplate::IssueAssignerExpire', sys_notice: '您负责的易修{title}已临近截止日期,请尽快处理', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') self.create(type: 'MessageTemplate::IssueAtme', sys_notice: '{nickname}在易修{title}中@我', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') - self.create(type: 'MessageTemplate::IssueChanged', sys_notice: '在项目{nickname2}/{repository1}的易修{title}中:{ifassigner}{nickname1}将负责人从{assigner1}修改为{assigner1}{endassigner}
    {ifstatus}{nickname1}将状态从{status1}修改为{status1}{endstatus}
    {iftracker}{nickname1}将类型从{tracker1}修改为{tracker1}{endtracker}
    {ifpriority}{nickname1}将优先度从{priority1}修改为{priority1}{endpriority}
    {ifmilestone}{nickname1}将里程碑从{milestone1}修改为{milestone1}{endmilestone}
    {iftag}{nickname1}将标签从{tag1}修改为{tag1}{endtag}
    {ifdoneratio}{nickname1}将完成度从{doneratio1}修改为{doneratio1}{enddoneratio}
    {ifbranch}{nickname1}将指定分支从{branch1}修改为{branch1}{endbranch}
    {ifstartdate}{nickname1}将开始日期从{startdate1}修改为{startdate1}{endstartdate}
    {ifduedate}{nickname1}将结束日期从{duedate1}修改为{duedate1}{endduedate}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') + self.create(type: 'MessageTemplate::IssueChanged', sys_notice: '在项目{nickname2}/{repository}的易修{title}中:{ifassigner}{nickname1}将负责人从{assigner1}修改为{assigner2}
    {endassigner}{ifstatus}{nickname1}将状态从{status1}修改为{status2}
    {endstatus}{iftracker}{nickname1}将类型从{tracker1}修改为{tracker2}
    {endtracker}{ifpriority}{nickname1}将优先级从{priority1}修改为{priority2}
    {endpriority}{ifmilestone}{nickname1}将里程碑从{milestone1}修改为{milestone2}
    {endmilestone}{iftag}{nickname1}将标签从{tag1}修改为{tag2}
    {endtag}{ifdoneratio}{nickname1}将完成度从{doneratio2}修改为{doneratio1}{enddoneratio}
    {ifbranch}{nickname1}将指定分支从{branch1}修改为{branch2}
    {endbranch}{ifstartdate}{nickname1}将开始日期从{startdate1}修改为{startdate2}
    {endstartdate}{ifduedate}{nickname1}将结束日期从{duedate1}修改为{duedate2}
    {endduedate}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') self.create(type: 'MessageTemplate::IssueCreatorExpire', sys_notice: '您发布的易修{title}已临近截止日期,请尽快处理', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') self.create(type: 'MessageTemplate::IssueDeleted', sys_notice: '{nickname}已将易修{title}删除', notification_url: '') self.create(type: 'MessageTemplate::IssueJournal', sys_notice: '{nickname}评论易修{title}:{notes}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') self.create(type: 'MessageTemplate::LoginIpTip', sys_notice: '您的账号{nickname}于{login_time)在非常用的IP地址{ip}登录,如非本人操作,请立即修改密码', notification_url: '') self.create(type: 'MessageTemplate::OrganizationJoined', sys_notice: '你已加入{organization}组织', notification_url: '{baseurl}/{login}') self.create(type: 'MessageTemplate::OrganizationLeft', sys_notice: '你已被移出{organization}组织', notification_url: '') - self.create(type: 'MessageTemplate::OrganizationRole', sys_notice: '组织{organization}已把你的角色改为{role}', notification_url: '{baseurl}/{owner}') + self.create(type: 'MessageTemplate::OrganizationRole', sys_notice: '组织{organization}已把你的角色改为{role}', notification_url: '{baseurl}/{login}') self.create(type: 'MessageTemplate::ProjectDeleted', sys_notice: '你关注的仓库{nickname}/{repository}已被删除', notification_url: '') self.create(type: 'MessageTemplate::ProjectFollowed', sys_notice: '{nickname}关注了你管理的仓库', notification_url: '{baseurl}/{login}') self.create(type: 'MessageTemplate::ProjectForked', sys_notice: '{nickname1}复刻了你管理的仓库{nickname1}/{repository1}到{nickname2}/{repository2}', notification_url: '{baseurl}/{owner}/{identifier}') @@ -43,8 +43,8 @@ class MessageTemplate {nickname2}/{repository}
    创建了发行版:{title}', notification_url: '{baseurl}/{owner}/{identifier}/releases') self.create(type: 'MessageTemplate::PullRequestAssigned', sys_notice: '{nickname1}在{nickname2}/{repository}指派给你一个合并请求:{title}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') self.create(type: 'MessageTemplate::PullRequestAtme', sys_notice: '{nickname}在合并请求{title}中@我', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') - self.create(type: 'MessageTemplate::PullRequestChanged', sys_notice: '在项目{nickname2}/{repository1}的合并请求{title}中:{ifassigner}{nickname1}将审查成员从{assigner1}修改为{assigner1}{endassigner}
    {ifmilestone}{nickname1}将里程碑从{milestone1}修改为{milestone1}{endmilestone}
    {iftag}{nickname1}将标签从{tag1}修改为{tag1}{endtag}
    {ifpriority}{nickname1}将优先度从{priority1}修改为{priority1}{endpriority}
    ', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') - self.create(type: 'MessageTemplate::PullRequestClosed', sys_notice: '你提交的合并请求:{title]被拒绝', notification_url: '') + self.create(type: 'MessageTemplate::PullRequestChanged', sys_notice: '在项目{nickname2}/{repository}的合并请求{title}中:{ifassigner}{nickname1}将审查成员从{assigner1}修改为{assigner2}
    {endassigner}{ifmilestone}{nickname1}将里程碑从{milestone1}修改为{milestone2}
    {endmilestone}{iftag}{nickname1}将标签从{tag1}修改为{tag2}
    {endtag}{ifpriority}{nickname1}将优先级从{priority1}修改为{priority2}
    {endpriority}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') + self.create(type: 'MessageTemplate::PullRequestClosed', sys_notice: '你提交的合并请求:{title}被拒绝', notification_url: '') self.create(type: 'MessageTemplate::PullRequestJournal', sys_notice: '{nickname}评论合并请求{title}:{notes}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') self.create(type: 'MessageTemplate::PullRequestMerged', sys_notice: '你提交的合并请求:{title}被合并', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') end @@ -52,4 +52,16 @@ class MessageTemplate e + Rails.logger.info("MessageTemplate::IssueAssigned.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/issue_assigner_expire.rb b/app/models/message_template/issue_assigner_expire.rb index b9afeae0..dc7a34fa 100644 --- a/app/models/message_template/issue_assigner_expire.rb +++ b/app/models/message_template/issue_assigner_expire.rb @@ -13,4 +13,16 @@ # 我负责的易修截止日期到达最后一天 class MessageTemplate::IssueAssignerExpire < MessageTemplate + + # MessageTemplate::IssueAssignerExpire.get_message_content(User.where(login: 'yystopf'), Issue.last) + def self.get_message_content(receivers, issue) + project = issue&.project + owner = project&.owner + content = sys_notice.gsub('{title}', issue&.subject) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::IssueAssignerExpire.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/issue_atme.rb b/app/models/message_template/issue_atme.rb index 2a87da11..0aa1c946 100644 --- a/app/models/message_template/issue_atme.rb +++ b/app/models/message_template/issue_atme.rb @@ -13,4 +13,16 @@ # 在易修中@我 class MessageTemplate::IssueAtme < MessageTemplate + + # MessageTemplate::IssueAtme.get_message_content(User.where(login: 'yystopf'), User.last, Issue.last) + def self.get_message_content(receivers, operator, issue) + project = issue&.project + owner = project&.owner + content = sys_notice.gsub('{nickname}', operator&.nickname).gsub('{title}', issue&.subject) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifer}', project&.identifier).gsub('{id}', issue&.id.to_s) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::IssueAtme.get_message_content [ERROR] #{e}") + return 0, '', '' + end end diff --git a/app/models/message_template/issue_changed.rb b/app/models/message_template/issue_changed.rb index 0820d4bf..33cd6170 100644 --- a/app/models/message_template/issue_changed.rb +++ b/app/models/message_template/issue_changed.rb @@ -13,4 +13,117 @@ # 我创建或负责的易修状态变更 class MessageTemplate::IssueChanged < MessageTemplate + + # MessageTemplate::IssueChanged.get_message_content(User.where(login: 'yystopf'), User.last, Issue.last, {assigner: 'testforge2', milestone: '里程碑', tag: '标签', priority: '低', tracker: '支持', doneratio: '70', branch: 'master', startdate: Date.today, duedate: Date.today + 1.days}) + def self.get_message_content(receivers, operator, issue, change_params) + project = issue&.project + owner = project&.owner + content = MessageTemplate::IssueChanged.sys_notice.gsub('{nickname1}', operator&.nickname).gsub('{nickname2}', owner&.nickname).gsub('{repository}', project&.name).gsub('{title}', issue&.subject) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s) + # 易修负责人修改 + if change_params[:assigner].present? + assigner = issue&.get_assign_user&.nickname || '未指派成员' + content.sub!('{ifassigner}', '') + content.sub!('{endassigner}', '') + content.gsub!('{assigner1}', assigner) + content.gsub!('{assigner2}', change_params[:assigner]) + else + content.gsub!(/({ifassigner})(.*)({endassigner})/, '') + end + # 易修状态修改 + if change_params[:status].present? + status = issue&.issue_status&.name + content.sub!('{ifstatus}', '') + content.sub!('{endstatus}', '') + content.gsub!('{status1}', status) + content.gsub!('{status2}', change_params[:status]) + else + content.gsub!(/({ifstatus})(.*)({endstatus})/, '') + end + # 易修类型修改 + if change_params[:tracker].present? + tracker = issue&.tracker&.name + content.sub!('{iftracker}', '') + content.sub!('{endtracker}', '') + content.gsub!('{tracker1}', tracker) + content.gsub!('{tracker2}', change_params[:tracker]) + else + content.gsub!(/({iftracker})(.*)({endtracker})/, '') + end + # 合并请求里程碑修改 + if change_params[:milestone].present? + milestone = issue&.version&.name || '未选择里程碑' + content.sub!('{ifmilestone}', '') + content.sub!('{endmilestone}', '') + content.gsub!('{milestone1}', milestone) + content.gsub!('{milestone2}', change_params[:milestone]) + else + content.gsub!(/({ifmilestone})(.*)({endmilestone})/, '') + end + # 合并请求标签修改 + if change_params[:tag].present? + tag = issue&.issue_tags.distinct.pluck(:name).join(",") + tag = '未选择标签' if tag == '' + content.sub!('{iftag}', '') + content.sub!('{endtag}', '') + content.gsub!('{tag1}', tag) + content.gsub!('{tag2}', change_params[:tag]) + else + content.gsub!(/({iftag})(.*)({endtag})()/, '') + end + # 合并请求优先级修改 + if change_params[:priority].present? + priority = issue&.priority&.name + content.sub!('{ifpriority}', '') + content.sub!('{endpriority}', '') + content.gsub!('{priority1}', priority) + content.gsub!('{priority2}', change_params[:priority]) + else + content.gsub!(/({ifpriority})(.*)({endpriority})/, '') + end + # 易修完成度修改 + if change_params[:doneratio].present? + doneratio = issue&.done_ratio + content.sub!('{ifdoneratio}', '') + content.sub!('{enddoneratio}', '') + content.gsub!('{doneratio1}', "#{doneratio}%") + content.gsub!('{doneratio2}', "#{change_params[:doneratio]}%") + else + content.gsub!(/({ifdoneratio})(.*)({enddoneratio})/, '') + end + # 易修指定分支修改 + if change_params[:branch].present? + branch = issue&.branch_name || '分支未指定' + content.sub!('{ifbranch}', '') + content.sub!('{endbranch}', '') + content.gsub!('{branch1}', branch ) + content.gsub!('{branch2}', change_params[:branch]) + else + content.gsub!(/({ifbranch})(.*)({endbranch})/, '') + end + # 易修开始日期修改 + if change_params[:startdate].present? + startdate = issue&.start_date || "未选择开始日期" + content.sub!('{ifstartdate}', '') + content.sub!('{endstartdate}', '') + content.gsub!('{startdate1}', startdate.to_s ) + content.gsub!('{startdate2}', change_params[:startdate].to_s) + else + content.gsub!(/({ifstartdate})(.*)({endstartdate})/, '') + end + # 易修结束日期修改 + if change_params[:duedate].present? + duedate = issue&.due_date || '未选择结束日期' + content.sub!('{ifduedate}', '') + content.sub!('{endduedate}', '') + content.gsub!('{duedate1}', duedate.to_s) + content.gsub!('{duedate2}', change_params[:duedate].to_s) + else + content.gsub!(/({ifduedate})(.*)({endduedate})/, '') + end + return receivers_string(receivers), content, url + # rescue => e + # Rails.logger.info("MessageTemplate::IssueAssigned.get_message_content [ERROR] #{e}") + # return '', '', '' + end end diff --git a/app/models/message_template/issue_creator_expire.rb b/app/models/message_template/issue_creator_expire.rb index 41c47152..9878f37f 100644 --- a/app/models/message_template/issue_creator_expire.rb +++ b/app/models/message_template/issue_creator_expire.rb @@ -13,4 +13,16 @@ # 我创建的易修截止日期到达最后一天 class MessageTemplate::IssueCreatorExpire < MessageTemplate + + # MessageTemplate::IssueCreatorExpire.get_message_content(User.where(login: 'yystopf'), Issue.last) + def self.get_message_content(receivers, issue) + project = issue&.project + owner = project&.owner + content = sys_notice.gsub('{title}', issue&.subject) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::IssueAssignerExpire.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/issue_deleted.rb b/app/models/message_template/issue_deleted.rb index a6a0ef20..a261b713 100644 --- a/app/models/message_template/issue_deleted.rb +++ b/app/models/message_template/issue_deleted.rb @@ -13,4 +13,15 @@ # 我创建或负责的易修删除 class MessageTemplate::IssueDeleted < MessageTemplate + + # MessageTemplate::IssueDeleted.get_message_content(User.where(login: 'yystopf'), User.last, Issue.last) + def self.get_message_content(receivers, operator, issue) + project = issue&.project + owner = project&.owner + content = sys_notice.gsub('{nickname}', operator&.nickname).gsub('{title}', issue&.subject) + return receivers_string(receivers), content, notification_url + rescue => e + Rails.logger.info("MessageTemplate::IssueAtme.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/issue_journal.rb b/app/models/message_template/issue_journal.rb index e4f7572b..a24616f1 100644 --- a/app/models/message_template/issue_journal.rb +++ b/app/models/message_template/issue_journal.rb @@ -11,6 +11,14 @@ # notification_url :string(255) # -# 我创建或负责的易修有新的评论 +# TODO 我创建或负责的易修有新的评论 class MessageTemplate::IssueJournal < MessageTemplate + + # MessageTemplate::IssueJournal.get_message_content(User.where(login: 'yystopf')) + def self.get_message_content(receivers) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::IssueJournal.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/login_ip_tip.rb b/app/models/message_template/login_ip_tip.rb index 898a30c7..f7ecc776 100644 --- a/app/models/message_template/login_ip_tip.rb +++ b/app/models/message_template/login_ip_tip.rb @@ -11,6 +11,14 @@ # notification_url :string(255) # -# 登录异常提示 +# TODO 登录异常提示 class MessageTemplate::LoginIpTip < MessageTemplate + + # MessageTemplate::LoginIpTip.get_message_content(User.where(login: 'yystopf')) + def self.get_message_content(receivers) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::LoginIpTip.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/organization_joined.rb b/app/models/message_template/organization_joined.rb index 95c9611a..d3a7ca1d 100644 --- a/app/models/message_template/organization_joined.rb +++ b/app/models/message_template/organization_joined.rb @@ -13,4 +13,14 @@ # 账号被拉入组织 class MessageTemplate::OrganizationJoined < MessageTemplate + + # MessageTemplate::OrganizationJoined.get_message_content(User.where(login: 'yystopf'), Organization.last) + def self.get_message_content(receivers, organization) + content = sys_notice.gsub('{organization}', organization&.name) + url = notification_url.gsub('{login}', organization&.name) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::OrganizationJoined.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/organization_left.rb b/app/models/message_template/organization_left.rb index 30df516e..9fe84474 100644 --- a/app/models/message_template/organization_left.rb +++ b/app/models/message_template/organization_left.rb @@ -13,4 +13,14 @@ # 账号被移出组织 class MessageTemplate::OrganizationLeft < MessageTemplate + + # MessageTemplate::OrganizationLeft.get_message_content(User.where(login: 'yystopf'), Organization.last) + def self.get_message_content(receivers, organization) + content = sys_notice.gsub('{organization}', organization&.name) + url = notification_url.gsub('{login}', organization&.name) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::OrganizationLeft.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/organization_role.rb b/app/models/message_template/organization_role.rb index 6ca82503..223ecf8b 100644 --- a/app/models/message_template/organization_role.rb +++ b/app/models/message_template/organization_role.rb @@ -13,4 +13,14 @@ # 账号组织权限变更 class MessageTemplate::OrganizationRole < MessageTemplate + + # MessageTemplate::OrganizationRole.get_message_content(User.where(login: 'yystopf'), Organization.last, '管理员') + def self.get_message_content(receivers, organization, role) + content = sys_notice.gsub('{organization}', organization&.name).gsub('{role}', role) + url = notification_url.gsub('{login}', organization&.login) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::OrganizationRole.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_deleted.rb b/app/models/message_template/project_deleted.rb index 334c6d87..69f09452 100644 --- a/app/models/message_template/project_deleted.rb +++ b/app/models/message_template/project_deleted.rb @@ -11,6 +11,14 @@ # notification_url :string(255) # -# 我关注的仓库被删除 +# TODO 我关注的仓库被删除 class MessageTemplate::ProjectDeleted < MessageTemplate + + # MessageTemplate::ProjectDeleted.get_message_content(User.where(login: 'yystopf')) + def self.get_message_content(receivers) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectDeleted.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_followed.rb b/app/models/message_template/project_followed.rb index d7ade39e..07dadb7c 100644 --- a/app/models/message_template/project_followed.rb +++ b/app/models/message_template/project_followed.rb @@ -11,6 +11,14 @@ # notification_url :string(255) # -# 我管理的仓库被关注 +# TODO 我管理的仓库被关注 class MessageTemplate::ProjectFollowed < MessageTemplate + + # MessageTemplate::ProjectFollowed.get_message_content(User.where(login: 'yystopf')) + def self.get_message_content(receivers) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectFollowed.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_forked.rb b/app/models/message_template/project_forked.rb index b69892fa..a419bc8f 100644 --- a/app/models/message_template/project_forked.rb +++ b/app/models/message_template/project_forked.rb @@ -11,6 +11,14 @@ # notification_url :string(255) # -# 我管理的仓库被复刻 +# TODO 我管理的仓库被复刻 class MessageTemplate::ProjectForked < MessageTemplate + + # MessageTemplate::ProjectForked.get_message_content(User.where(login: 'yystopf')) + def self.get_message_content(receivers) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectForked.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_issue.rb b/app/models/message_template/project_issue.rb index f657084a..81904f23 100644 --- a/app/models/message_template/project_issue.rb +++ b/app/models/message_template/project_issue.rb @@ -11,6 +11,14 @@ # notification_url :string(255) # -# 我管理/关注的仓库有新的易修 +# TODO 我管理/关注的仓库有新的易修 class MessageTemplate::ProjectIssue < MessageTemplate + + # MessageTemplate::ProjectIssue.get_message_content(User.where(login: 'yystopf')) + def self.get_message_content(receivers) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectIssue.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_joined.rb b/app/models/message_template/project_joined.rb index 1da83b0c..91d4b3c1 100644 --- a/app/models/message_template/project_joined.rb +++ b/app/models/message_template/project_joined.rb @@ -13,4 +13,14 @@ # 账号被拉入项目 class MessageTemplate::ProjectJoined < MessageTemplate + + # MessageTemplate::ProjectJoined.get_message_content(User.where(login: 'yystopf'), Project.last) + def self.get_message_content(receivers, project) + content = sys_notice.gsub('{repository}', project&.name) + url = notification_url.gsub('{owner}', project&.owner&.login).gsub('{identifier}', project&.identifier) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectJoined.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_left.rb b/app/models/message_template/project_left.rb index 63923502..e83b027a 100644 --- a/app/models/message_template/project_left.rb +++ b/app/models/message_template/project_left.rb @@ -14,4 +14,13 @@ # 账号被移出项目 class MessageTemplate::ProjectLeft < MessageTemplate + # MessageTemplate::ProjectLeft.get_message_content(User.where(login: 'yystopf'), Project.last) + def self.get_message_content(receivers, project) + content = sys_notice.gsub('{repository}', project&.name) + url = notification_url.gsub('{owner}', project&.owner&.login).gsub('{identifier}', project&.identifier) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectLeft.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_member_joined.rb b/app/models/message_template/project_member_joined.rb index 0b402545..c10edb59 100644 --- a/app/models/message_template/project_member_joined.rb +++ b/app/models/message_template/project_member_joined.rb @@ -11,6 +11,14 @@ # notification_url :string(255) # -# 我管理的仓库有成员加入 +# TODO 我管理的仓库有成员加入 class MessageTemplate::ProjectMemberJoined < MessageTemplate + + # MessageTemplate::ProjectMemberJoined.get_message_content(User.where(login: 'yystopf')) + def self.get_message_content(receivers) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectMemberJoined.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_member_left.rb b/app/models/message_template/project_member_left.rb index ed261e0f..b7133e05 100644 --- a/app/models/message_template/project_member_left.rb +++ b/app/models/message_template/project_member_left.rb @@ -11,6 +11,14 @@ # notification_url :string(255) # -# 我管理的仓库有成员移出 +# TODO 我管理的仓库有成员移出 class MessageTemplate::ProjectMemberLeft < MessageTemplate + + # MessageTemplate::ProjectMemberLeft.get_message_content(User.where(login: 'yystopf')) + def self.get_message_content(receivers) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectMemberLeft.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_milestone.rb b/app/models/message_template/project_milestone.rb index b28766c5..79e83485 100644 --- a/app/models/message_template/project_milestone.rb +++ b/app/models/message_template/project_milestone.rb @@ -11,6 +11,14 @@ # notification_url :string(255) # -# 我管理的仓库有新的里程碑 +# TODO 我管理的仓库有新的里程碑 class MessageTemplate::ProjectMilestone < MessageTemplate + + # MessageTemplate::ProjectMilestone.get_message_content(User.where(login: 'yystopf')) + def self.get_message_content(receivers) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectMilestone.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_praised.rb b/app/models/message_template/project_praised.rb index ec7a0564..1af2ce88 100644 --- a/app/models/message_template/project_praised.rb +++ b/app/models/message_template/project_praised.rb @@ -11,6 +11,14 @@ # notification_url :string(255) # -# 我管理的仓库被点赞 +# TODO 我管理的仓库被点赞 class MessageTemplate::ProjectPraised < MessageTemplate + + # MessageTemplate::ProjectPraised.get_message_content(User.where(login: 'yystopf')) + def self.get_message_content(receivers) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectPraised.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_pull_request.rb b/app/models/message_template/project_pull_request.rb index 43a8359b..f0c642d1 100644 --- a/app/models/message_template/project_pull_request.rb +++ b/app/models/message_template/project_pull_request.rb @@ -11,6 +11,14 @@ # notification_url :string(255) # -# 我管理/关注的仓库有新的合并请求 +# TODO 我管理/关注的仓库有新的合并请求 class MessageTemplate::ProjectPullRequest < MessageTemplate + + # MessageTemplate::ProjectPullRequest.get_message_content(User.where(login: 'yystopf')) + def self.get_message_content(receivers) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectPullRequest.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_role.rb b/app/models/message_template/project_role.rb index 95ebe5ba..cb229007 100644 --- a/app/models/message_template/project_role.rb +++ b/app/models/message_template/project_role.rb @@ -13,4 +13,14 @@ # 账号仓库权限变更 class MessageTemplate::ProjectRole < MessageTemplate + + # MessageTemplate::ProjectRole.get_message_content(User.where(login: 'yystopf'), Project.last, '管理员') + def self.get_message_content(receivers, project, role) + content = sys_notice.gsub('{repository}', project&.name).gsub('{role}', role) + url = notification_url.gsub('{owner}', project&.owner&.login).gsub('{identifier}', project&.identifier) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectRole.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_setting_changed.rb b/app/models/message_template/project_setting_changed.rb index b983e6c6..b62b52e4 100644 --- a/app/models/message_template/project_setting_changed.rb +++ b/app/models/message_template/project_setting_changed.rb @@ -13,4 +13,64 @@ # 我管理的仓库项目设置被更改 class MessageTemplate::ProjectSettingChanged < MessageTemplate + + # MessageTemplate::ProjectSettingChanged.get_message_content(User.where(login: 'yystopf'), User.last, Project.last, {description: '测试修改项目简介', category: '大数据', language: 'Ruby', permission: '公有', navbar: '易修, 合并请求'}) + def self.get_message_content(receivers, operator, project, change_params) + owner = project&.owner + content = sys_notice.gsub('{nickname1}', operator&.nickname).gsub('{nickname2}', owner&.nickname).gsub('{repository}', project&.name) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier) + # 项目名称更改 + if change_params[:name].present? + content.sub!('{ifname}', '') + content.sub!('{endname}', '') + content.gsub!('{name}', change_params[:name]) + else + content.gsub!(/({ifname})(.*)({endname})/, '') + end + # 项目简介更改 + if change_params[:description].present? + content.sub!('{ifdescription}', '') + content.sub!('{enddescription}', '') + content.gsub!('{description}', change_params[:description]) + else + content.gsub!(/({ifdescription})(.*)({enddescription})/, '') + end + # 项目类别更改 + if change_params[:category].present? + content.sub!('{ifcategory}', '') + content.sub!('{endcategory}', '') + content.gsub!('{category}', change_params[:category]) + else + content.gsub!(/({ifcategory})(.*)({endcategory})/, '') + end + # 项目语言更改 + if change_params[:language].present? + content.sub!('{iflanguage}', '') + content.sub!('{endlanguage}', '') + content.gsub!('{language}', change_params[:language]) + else + content.gsub!(/({iflanguage})(.*)({endlanguage})/, '') + end + # 项目公私有更改 + if change_params[:permission].present? + content.sub!('{ifpermission}', '') + content.sub!('{endpermission}', '') + content.gsub!('{permission}', change_params[:permission]) + else + content.gsub!(/({ifpermission})(.*)({endpermission})/, '') + end + # 项目导航更改 + if change_params[:navbar].present? + content.sub!('{ifnavbar}', '') + content.sub!('{endnavbar}', '') + content.gsub!('{navbar}', change_params[:navbar]) + else + content.gsub!(/({ifnavbar})(.*)({endnavbar})/, '') + end + + return receivers_string(receivers.where.not(id: operator.id)), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectSettingChanged.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_transfer.rb b/app/models/message_template/project_transfer.rb index ce422f09..e931e7b1 100644 --- a/app/models/message_template/project_transfer.rb +++ b/app/models/message_template/project_transfer.rb @@ -11,6 +11,14 @@ # notification_url :string(255) # -# 我关注的仓库被转移 +# TODO 我关注的仓库被转移 class MessageTemplate::ProjectTransfer < MessageTemplate + + # MessageTemplate::ProjectTransfer.get_message_content(User.where(login: 'yystopf')) + def self.get_message_content(receivers) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectTransfer.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_version.rb b/app/models/message_template/project_version.rb index afc25fc4..26067b7f 100644 --- a/app/models/message_template/project_version.rb +++ b/app/models/message_template/project_version.rb @@ -11,6 +11,14 @@ # notification_url :string(255) # -# 我关注的仓库有新的发行版 +# TODO 我关注的仓库有新的发行版 class MessageTemplate::ProjectVersion < MessageTemplate + + # MessageTemplate::ProjectVersion.get_message_content(User.where(login: 'yystopf')) + def self.get_message_content(receivers) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectVersion.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/pull_request_assigned.rb b/app/models/message_template/pull_request_assigned.rb index d6d497da..132a3615 100644 --- a/app/models/message_template/pull_request_assigned.rb +++ b/app/models/message_template/pull_request_assigned.rb @@ -13,4 +13,16 @@ # 有新指派给我的合并请求 class MessageTemplate::PullRequestAssigned < MessageTemplate + + # MessageTemplate::PullRequestAssigned.get_message_content(User.where(login: 'yystopf'), User.last, PullRequest.last) + def self.get_message_content(receivers, operator, pull_request) + project = pull_request&.project + owner = project&.owner + content = sys_notice.gsub('{nickname1}', operator&.nickname).gsub('{nickname2}', owner&.nickname).gsub('{repository}', project&.name).gsub('{title}', pull_request&.title) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', pull_request&.id.to_s) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::PullRequestAssigned.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/pull_request_atme.rb b/app/models/message_template/pull_request_atme.rb index 5ff526fa..d940b235 100644 --- a/app/models/message_template/pull_request_atme.rb +++ b/app/models/message_template/pull_request_atme.rb @@ -12,4 +12,16 @@ # 在合并请求中@我 class MessageTemplate::PullRequestAtme < MessageTemplate + + # MessageTemplate::PullRequestAtme.get_message_content(User.where(login: 'yystopf'), User.last, PullRequest.last) + def self.get_message_content(receivers, operator, pull_request) + project = pull_request&.project + owner = project&.owner + content = sys_notice.gsub('{nickname}', operator&.nickname).gsub('{title}', pull_request&.title) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', pull_request&.id.to_s) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::PullRequestAtme.get_message_content [ERROR] #{e}") + return '', '', '' + end end \ No newline at end of file diff --git a/app/models/message_template/pull_request_changed.rb b/app/models/message_template/pull_request_changed.rb index dcde72b8..487b250b 100644 --- a/app/models/message_template/pull_request_changed.rb +++ b/app/models/message_template/pull_request_changed.rb @@ -13,4 +13,58 @@ # 我创建或负责的合并请求状态变更 class MessageTemplate::PullRequestChanged < MessageTemplate + + # MessageTemplate::PullRequestChanged.get_message_content(User.where(login: 'yystopf'), User.last, PullRequest.last, {assigner: 'testforge2', tag: '标签', priority: '低'}) + def self.get_message_content(receivers, operator, pull_request, change_params) + project = pull_request&.project + owner = project&.owner + issue = pull_request&.issue + content = sys_notice.gsub('{nickname1}', operator&.nickname).gsub('{nickname2}', owner&.nickname).gsub('{repository}', project&.name) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', pull_request&.id.to_s) + # 合并请求审查成员修改 + if change_params[:assigner].present? + assigner = issue&.get_assign_user&.nickname || '未指派成员' + content.sub!('{ifassigner}', '') + content.sub!('{endassigner}', '') + content.gsub!('{assigner1}', assigner) + content.gsub!('{assigner2}', change_params[:assigner]) + else + content.gsub!(/({ifassigner})(.*)({endassigner})/, '') + end + # 合并请求里程碑修改 + if change_params[:milestone].present? + milestone = issue&.version&.name || '未选择里程碑' + content.sub!('{ifmilestone}', '') + content.sub!('{endmilestone}', '') + content.gsub!('{milestone1}', milestone) + content.gsub!('{milestone2}', change_params[:milestone]) + else + content.gsub!(/({ifmilestone})(.*)({endmilestone})/, '') + end + # 合并请求标签修改 + if change_params[:tag].present? + tag = issue&.issue_tags.distinct.pluck(:name).join(",") + tag = '未选择标签' if tag == '' + content.sub!('{iftag}', '') + content.sub!('{endtag}', '') + content.gsub!('{tag1}', tag) + content.gsub!('{tag2}', change_params[:tag]) + else + content.gsub!(/({iftag})(.*)({endtag})()/, '') + end + # 合并请求优先级修改 + if change_params[:priority].present? + priority = issue&.priority&.name + content.sub!('{ifpriority}', '') + content.sub!('{endpriority}', '') + content.gsub!('{priority1}', priority) + content.gsub!('{priority2}', change_params[:priority]) + else + content.gsub!(/({ifpriority})(.*)({endpriority})/, '') + end + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::PullRequestChanged.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/pull_request_closed.rb b/app/models/message_template/pull_request_closed.rb index 0574b640..6e5bfbe1 100644 --- a/app/models/message_template/pull_request_closed.rb +++ b/app/models/message_template/pull_request_closed.rb @@ -13,4 +13,16 @@ # 我创建或负责的合并请求被关闭 class MessageTemplate::PullRequestClosed < MessageTemplate + + # MessageTemplate::PullRequestClosed.get_message_content(User.where(login: 'yystopf'), User.last, PullRequest.last) + def self.get_message_content(receivers, operator, pull_request) + project = pull_request&.project + owner = project&.owner + content = sys_notice.gsub('{title}', pull_request&.title) + url = notification_url + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::PullRequestClosed.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/pull_request_journal.rb b/app/models/message_template/pull_request_journal.rb index 6d3b4fe3..9c68e64f 100644 --- a/app/models/message_template/pull_request_journal.rb +++ b/app/models/message_template/pull_request_journal.rb @@ -11,6 +11,14 @@ # notification_url :string(255) # -# 我创建或负责的合并请求有新的评论 +# TODO 我创建或负责的合并请求有新的评论 class MessageTemplate::PullRequestJournal < MessageTemplate + + # MessageTemplate::PullRequestJournal.get_message_content(User.where(login: 'yystopf')) + def self.get_message_content(receivers) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::PullRequestJournal.get_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/pull_request_merged.rb b/app/models/message_template/pull_request_merged.rb index b06687cb..2d229bb6 100644 --- a/app/models/message_template/pull_request_merged.rb +++ b/app/models/message_template/pull_request_merged.rb @@ -13,4 +13,16 @@ # 我创建或负责的合并请求被合并 class MessageTemplate::PullRequestMerged < MessageTemplate + + # MessageTemplate::PullRequestMerged.get_message_content(User.where(login: 'yystopf'), User.last, PullRequest.last) + def self.get_message_content(receivers, operator, pull_request) + project = pull_request&.project + owner = project&.owner + content = sys_notice.gsub('{title}', pull_request&.title) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', pull_request&.id.to_s) + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::PullRequestMerged.get_message_content [ERROR] #{e}") + return '', '', '' + end end From fa0021b504e7e889d3740412bbcebd56498d4ef8 Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 15 Sep 2021 11:10:09 +0800 Subject: [PATCH 028/135] fix --- app/jobs/send_template_message_job.rb | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 app/jobs/send_template_message_job.rb diff --git a/app/jobs/send_template_message_job.rb b/app/jobs/send_template_message_job.rb new file mode 100644 index 00000000..e8e4a82a --- /dev/null +++ b/app/jobs/send_template_message_job.rb @@ -0,0 +1,12 @@ +class SendTemplateMessageJob < ApplicationJob + queue_as :default + + def perform(source, *args) + Rails.logger.info "SendTemplateMessageJob [args] #{args}" + case source + when 'FollowTip' + receivers, followeder = args + Rails.logger.info "#{receivers} #{followeder}" + end + end +end \ No newline at end of file From 8a02981a2ef6a3dda6afd2b8cd2535185cd740ac Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 15 Sep 2021 11:28:38 +0800 Subject: [PATCH 029/135] fix: mirror broadcast error and retry --- app/jobs/broadcast_mirror_repo_msg_job.rb | 19 ++++++++++++++++++- app/jobs/migrate_remote_repository_job.rb | 1 + app/jobs/sync_mirrored_repository_job.rb | 1 + app/models/mirror.rb | 2 +- 4 files changed, 21 insertions(+), 2 deletions(-) diff --git a/app/jobs/broadcast_mirror_repo_msg_job.rb b/app/jobs/broadcast_mirror_repo_msg_job.rb index 6372ae2e..a62bfaba 100644 --- a/app/jobs/broadcast_mirror_repo_msg_job.rb +++ b/app/jobs/broadcast_mirror_repo_msg_job.rb @@ -18,12 +18,29 @@ class BroadcastMirrorRepoMsgJob < ApplicationJob id: project.id, type: project.numerical_for_project_type } + # 新增失败重试机制, 重试三次 + result = broadcast(project, json_data) + + if result == 0 + count = 3 + while count > 0 + result = broadcast(project, json_data) + if result > 0 + break + end + count -= 1 + end + end + end + + def broadcast(project, json_data) puts "############ broadcast start.......... " puts "############ broadcast channel_name: channel_room_#{project.id}" puts "############ broadcast project data: #{json_data} " cable_result = ActionCable.server.broadcast "channel_room_#{project.id}", project: json_data - puts "############ broadcast result: #{cable_result == 1 ? 'successed' : 'failed'} " + puts "############ broadcast result: #{cable_result > 0 ? 'successed' : 'failed'} " + return cable_result end end diff --git a/app/jobs/migrate_remote_repository_job.rb b/app/jobs/migrate_remote_repository_job.rb index 340e006e..e54eaf2b 100644 --- a/app/jobs/migrate_remote_repository_job.rb +++ b/app/jobs/migrate_remote_repository_job.rb @@ -16,5 +16,6 @@ class MigrateRemoteRepositoryJob < ApplicationJob else repo&.mirror&.failed! end + BroadcastMirrorRepoMsgJob.perform_later(repo.id) unless repo&.mirror.waiting? end end diff --git a/app/jobs/sync_mirrored_repository_job.rb b/app/jobs/sync_mirrored_repository_job.rb index a1408153..63abbfd8 100644 --- a/app/jobs/sync_mirrored_repository_job.rb +++ b/app/jobs/sync_mirrored_repository_job.rb @@ -26,6 +26,7 @@ class SyncMirroredRepositoryJob < ApplicationJob result = Gitea::Repository::SyncMirroredService.call(repo.owner.login, repo.identifier, token: user.gitea_token) repo&.mirror.set_status! if result[:status] === 200 + BroadcastMirrorRepoMsgJob.perform_later(repo.id) unless repo&.mirror.waiting? end end diff --git a/app/models/mirror.rb b/app/models/mirror.rb index 67ef7377..b71dce3f 100644 --- a/app/models/mirror.rb +++ b/app/models/mirror.rb @@ -18,7 +18,7 @@ class Mirror < ApplicationRecord # 0: 同步镜像成功;1: 正在同步镜像;2: 同步失败; 默认值为0 enum status: { succeeded: 0, waiting: 1, failed: 2 } - after_update :websocket_boardcast, if: :saved_change_to_status? + # after_update :websocket_boardcast, if: :saved_change_to_status? belongs_to :repository, foreign_key: :repo_id From 91e6e0384edcdcdba1d9d7e847e5bfec625188ab Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 15 Sep 2021 11:32:58 +0800 Subject: [PATCH 030/135] fix --- app/jobs/broadcast_mirror_repo_msg_job.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/app/jobs/broadcast_mirror_repo_msg_job.rb b/app/jobs/broadcast_mirror_repo_msg_job.rb index a62bfaba..4dee6894 100644 --- a/app/jobs/broadcast_mirror_repo_msg_job.rb +++ b/app/jobs/broadcast_mirror_repo_msg_job.rb @@ -24,6 +24,7 @@ class BroadcastMirrorRepoMsgJob < ApplicationJob if result == 0 count = 3 while count > 0 + sleep 3.seconds result = broadcast(project, json_data) if result > 0 break From 88bc5f29ffa09c3817c120565841e7e7d917a04c Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 15 Sep 2021 18:55:58 +0800 Subject: [PATCH 031/135] add: message touch condition --- app/controllers/issues_controller.rb | 16 ++ app/controllers/members_controller.rb | 13 ++ .../organizations/team_users_controller.rb | 1 + .../projects/project_units_controller.rb | 3 +- app/controllers/projects_controller.rb | 1 + app/controllers/pull_requests_controller.rb | 11 +- app/controllers/users/messages_controller.rb | 17 +- app/docs/slate/source/includes/_users.md | 6 +- app/jobs/send_template_message_job.rb | 148 +++++++++++++++++- app/models/message_template/issue_atme.rb | 2 +- app/models/message_template/issue_changed.rb | 112 +++++++------ app/models/message_template/issue_deleted.rb | 8 +- .../project_setting_changed.rb | 38 +++-- .../message_template/pull_request_changed.rb | 44 +++--- app/models/organization_user.rb | 11 ++ app/models/project_unit.rb | 4 + app/models/team.rb | 11 ++ app/models/watcher.rb | 5 + app/services/notice/write/create_service.rb | 5 +- public/docs/api.html | 6 +- 20 files changed, 362 insertions(+), 100 deletions(-) diff --git a/app/controllers/issues_controller.rb b/app/controllers/issues_controller.rb index 266d746d..e383a4f5 100644 --- a/app/controllers/issues_controller.rb +++ b/app/controllers/issues_controller.rb @@ -111,6 +111,7 @@ class IssuesController < ApplicationController Issues::CreateForm.new({subject:issue_params[:subject]}).validate! @issue = Issue.new(issue_params) if @issue.save! + SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @issue&.id) if params[:attachment_ids].present? params[:attachment_ids].each do |id| attachment = Attachment.select(:id, :container_id, :container_type)&.find_by_id(id) @@ -202,6 +203,20 @@ class IssuesController < ApplicationController issue_params = issue_send_params(params).except(:issue_classify, :author_id, :project_id) Issues::UpdateForm.new({subject:issue_params[:subject]}).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)) + SendTemplateMessageJob.perform_later('PullRequestAssigned', current_user.id, @issue&.pull_request&.id ) if @issue.previous_changes[:assigned_to_id].present? + else + previous_changes = @issue.previous_changes.slice(:status_id, :assigned_to_id, :tracker_id, :priority_id, :fixed_version_id, :done_ratio, :issue_tags_value, :branch_name) + if @issue.previous_changes[:start_date].present? + previous_changes.merge!(start_date: [@issue.previous_changes[:start_date][0].to_s, @issue.previous_changes[:start_date][1].to_s]) + end + if @issue.previous_changes[:due_date].present? + previous_changes.merge!(due_date: [@issue.previous_changes[:due_date][0].to_s, @issue.previous_changes[:due_date][1].to_s]) + end + SendTemplateMessageJob.perform_later('IssueChanged', current_user.id, @issue&.id, previous_changes) + SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @issue&.id) if @issue.previous_changes[:assigned_to_id].present? + end if params[:status_id].to_i == 5 #任务由非关闭状态到关闭状态时 @issue.issue_times.update_all(end_time: Time.now) @issue.update_closed_issues_count_in_project! @@ -253,6 +268,7 @@ class IssuesController < ApplicationController status_id = @issue.status_id token = @issue.token login = @issue.user.try(:login) + SendTemplateMessageJob.perform_later('IssueDeleted', current_user.id, @issue&.subject, @issue.assigned_to_id, @issue.author_id) if @issue.destroy if issue_type == "2" && status_id != 5 post_to_chain("add", token, login) diff --git a/app/controllers/members_controller.rb b/app/controllers/members_controller.rb index 7fb211e3..36c57b5b 100644 --- a/app/controllers/members_controller.rb +++ b/app/controllers/members_controller.rb @@ -9,6 +9,7 @@ class MembersController < ApplicationController def create interactor = Projects::AddMemberInteractor.call(@project.owner, @project, @user) + SendTemplateMessageJob.perform_later('ProjectJoined', @user.id, @project.id) render_response(interactor) rescue Exception => e uid_logger_error(e.message) @@ -28,6 +29,7 @@ class MembersController < ApplicationController def remove interactor = Projects::DeleteMemberInteractor.call(@project.owner, @project, @user) + SendTemplateMessageJob.perform_later('ProjectLeft', @user.id, @project.id) render_response(interactor) rescue Exception => e uid_logger_error(e.message) @@ -36,6 +38,7 @@ class MembersController < ApplicationController def change_role interactor = Projects::ChangeMemberRoleInteractor.call(@project.owner, @project, @user, params[:role]) + SendTemplateMessageJob.perform_later('ProjectRole', @user.id, @project.id, message_role_name) render_response(interactor) rescue Exception => e uid_logger_error(e.message) @@ -66,4 +69,14 @@ class MembersController < ApplicationController def check_user_profile_completed require_user_profile_completed(@user) end + + def message_role_name + case params[:role] + when 'Manager' then '管理员' + when 'Developer' then '开发者' + when 'Reporter' then '报告者' + else + '' + end + end end diff --git a/app/controllers/organizations/team_users_controller.rb b/app/controllers/organizations/team_users_controller.rb index 43ed1070..c6300526 100644 --- a/app/controllers/organizations/team_users_controller.rb +++ b/app/controllers/organizations/team_users_controller.rb @@ -18,6 +18,7 @@ class Organizations::TeamUsersController < Organizations::BaseController ActiveRecord::Base.transaction do @team_user = TeamUser.build(@organization.id, @operate_user.id, @team.id) @organization_user = OrganizationUser.build(@organization.id, @operate_user.id) + SendTemplateMessageJob.perform_later('OrganizationRole', @operate_user.id, @organization.id, @team.authorize_name) Gitea::Organization::TeamUser::CreateService.call(@organization.gitea_token, @team.gtid, @operate_user.login) end rescue Exception => e diff --git a/app/controllers/projects/project_units_controller.rb b/app/controllers/projects/project_units_controller.rb index e21fa388..e8b8f67a 100644 --- a/app/controllers/projects/project_units_controller.rb +++ b/app/controllers/projects/project_units_controller.rb @@ -6,7 +6,8 @@ class Projects::ProjectUnitsController < Projects::BaseController def create if current_user.admin? || @project.manager?(current_user) ActiveRecord::Base.transaction do - ProjectUnit.update_by_unit_types!(@project, unit_types) + before_units, after_units = ProjectUnit.update_by_unit_types!(@project, unit_types) + SendTemplateMessageJob.perform_later('ProjectSettingChanged', current_user.id, @project&.id, {navbar: true}) unless before_units.eql?(after_units) render_ok end else diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index 325d76cc..78056bee 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -139,6 +139,7 @@ class ProjectsController < ApplicationController @project.repository.update_column(:hidden, private) end end + SendTemplateMessageJob.perform_later('ProjectSettingChanged', current_user.id, @project&.id, @project.previous_changes.slice(:name, :description, :project_category_id, :project_language_id, :is_public)) end rescue Exception => e uid_logger_error(e.message) diff --git a/app/controllers/pull_requests_controller.rb b/app/controllers/pull_requests_controller.rb index 79221a66..0799beb5 100644 --- a/app/controllers/pull_requests_controller.rb +++ b/app/controllers/pull_requests_controller.rb @@ -59,6 +59,7 @@ class PullRequestsController < ApplicationController @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"]) + SendTemplateMessageJob.perform_later('PullRequestAssigned', current_user.id, @pull_request&.id) render_ok else render_error("create pull request error: #{@gitea_pull_request[:status]}") @@ -91,6 +92,8 @@ class PullRequestsController < ApplicationController end if @issue.update_attributes(@issue_params) + SendTemplateMessageJob.perform_later('PullRequestChanged', current_user.id, @pull_request&.id, @issue.previous_changes.slice(:assigned_to_id, :priority_id, :fixed_version_id, :issue_tags_value)) + SendTemplateMessageJob.perform_later('PullRequestAssigned', current_user.id, @pull_request&.id ) if @issue.previous_changes[:assigned_to_id].present? if @pull_request.update_attributes(@local_params.compact) gitea_pull = Gitea::PullRequest::UpdateService.call(@owner.login, @repository.identifier, @pull_request.gitea_number, @requests_params, current_user.gitea_token) @@ -125,7 +128,12 @@ class PullRequestsController < ApplicationController ActiveRecord::Base.transaction do begin colsed = PullRequests::CloseService.call(@owner, @repository, @pull_request, current_user) - colsed === true ? normal_status(1, "已拒绝") : normal_status(-1, '合并失败') + if colsed === true + SendTemplateMessageJob.perform_later('PullRequestClosed', current_user.id, @pull_request.id) + normal_status(1, "已拒绝") + else + normal_status(-1, '合并失败') + end rescue => e normal_status(-1, e.message) raise ActiveRecord::Rollback @@ -164,6 +172,7 @@ class PullRequestsController < ApplicationController if success_condition && @pull_request.merge! @pull_request.project_trend_status! @issue&.custom_journal_detail("merge", "", "该合并请求已被合并", current_user&.id) + SendTemplateMessageJob.perform_later('PullRequestMerged', current_user.id, @pull_request.id) normal_status(1, "合并成功") else normal_status(-1, result.message) diff --git a/app/controllers/users/messages_controller.rb b/app/controllers/users/messages_controller.rb index 648b38b1..035441cc 100644 --- a/app/controllers/users/messages_controller.rb +++ b/app/controllers/users/messages_controller.rb @@ -16,8 +16,21 @@ class Users::MessagesController < Users::BaseController case params[:type] when 'atme' Notice::Write::CreateAtmeForm.new(atme_params).validate! - result = Notice::Write::CreateService.call(@receivers.pluck(:id), '发送了一个@我消息', base_url, "IssueAtme", 2, {}, current_user.id) - return render_error if result.nil? + case atme_params[:atmeable_type] + when 'Issue' + SendTemplateMessageJob.perform_now('IssueAtme', @receivers, current_user.id, atme_params[:atmeable_id]) + when 'PullRequest' + SendTemplateMessageJob.perform_now('PullRequestAtme', @receivers, current_user.id, atme_params[:atmeable_id]) + when 'Journal' + journal = Journal.find_by_id(atme_params[:atmeable_id]) + if journal.present? + if journal&.issue&.pull_request.present? + SendTemplateMessageJob.perform_now('PullRequestAtme', @receivers, current_user.id, atme_params[:atmeable_id]) + else + SendTemplateMessageJob.perform_now('IssueAtme', @receivers, current_user.id, atme_params[:atmeable_id]) + end + end + end end render_ok rescue Exception => e diff --git a/app/docs/slate/source/includes/_users.md b/app/docs/slate/source/includes/_users.md index 7225b90e..9d6b8092 100644 --- a/app/docs/slate/source/includes/_users.md +++ b/app/docs/slate/source/includes/_users.md @@ -1,7 +1,7 @@ # Users @@ -219,8 +219,8 @@ await octokit.request('POST /api/users/:login/messages.json') 参数 | 类型 | 字段说明 --------- | ----------- | ----------- |type | string | 消息类型 | -|recervers_login | array | 需要发送消息的用户名数组| -|atmeable_type | string | atme消息对象,是从哪里@我的,比如评论:Journal | +|receivers_login | array | 需要发送消息的用户名数组| +|atmeable_type | string | atme消息对象,是从哪里@我的,比如评论:Journal、易修:Issue、合并请求:PullRequest | |atmeable_id | integer | atme消息对象id | > 请求的JSON示例: diff --git a/app/jobs/send_template_message_job.rb b/app/jobs/send_template_message_job.rb index e8e4a82a..f1e73a7e 100644 --- a/app/jobs/send_template_message_job.rb +++ b/app/jobs/send_template_message_job.rb @@ -5,8 +5,152 @@ class SendTemplateMessageJob < ApplicationJob Rails.logger.info "SendTemplateMessageJob [args] #{args}" case source when 'FollowTip' - receivers, followeder = args - Rails.logger.info "#{receivers} #{followeder}" + watcher_id = args[0] + watcher = Watcher.find_by_id(watcher_id) + return unless watcher.present? + receivers = User.where(id: watcher.watchable_id) + followeder = User.find_by_id(watcher.user_id) + receivers_string, content, notification_url = MessageTemplate::FollowedTip.get_message_content(receivers, followeder) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {watcher_id: watcher.id}) + when 'IssueAssigned' + operator_id, issue_id = args[0], args[1] + operator = User.find_by_id(operator_id) + issue = Issue.find_by_id(issue_id) + return unless operator.present? && issue.present? + receivers = User.where(id: issue&.assigned_to_id) + receivers_string, content, notification_url = MessageTemplate::IssueAssigned.get_message_content(receivers, operator, issue) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_id: issue.id}) + when 'IssueAssignerExpire' + issue_id = args[0] + issue = Issue.find_by_id(issue_id) + return unless issue.present? + receivers = User.where(id: issue&.assigned_to_id) + receivers_string, content, notification_url = MessageTemplate::IssueAssignerExpire.get_message_content(receivers, issue) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {issue_id: issue.id}) + when 'IssueAtme' + receivers, operator_id, issue_id = args[0], args[1], args[2] + operator = User.find_by_id(operator_id) + issue = Issue.find_by_id(issue_id) + return unless operator.present? && issue.present? + receivers_string, content, notification_url = MessageTemplate::IssueAtme.get_message_content(receivers, operator, issue) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_id: issue.id}, 2) + when 'IssueChanged' + operator_id, issue_id, change_params = args[0], args[1], args[2] + operator = User.find_by_id(operator_id) + issue = Issue.find_by_id(issue_id) + return unless operator.present? && issue.present? + receivers = User.where(id: [issue&.assigned_to_id, issue&.author_id]) + receivers_string, content, notification_url = MessageTemplate::IssueChanged.get_message_content(receivers, operator, issue, change_params) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_id: issue.id, change_params: change_params.symbolize_keys}) + when 'IssueCreatorExpire' + issue_id = args[0] + issue = Issue.find_by_id(issue_id) + return unless issue.present? + receivers = User.where(id: issue&.author_id) + receivers_string, content, notification_url = MessageTemplate::IssueCreatorExpire.get_message_content(receivers, issue) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {issue_id: issue.id}) + when 'IssueDeleted' + operator_id, issue_title, issue_assigned_to_id, issue_author_id = args[0], args[1], args[2], args[3] + operator = User.find_by_id(operator_id) + return unless operator.present? + receivers = User.where(id: [issue_assigned_to_id, issue_author_id]) + receivers_string, content, notification_url = MessageTemplate::IssueDeleted.get_message_content(receivers, operator, issue_title) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_title: issue_title}) + when 'OrganizationJoined' + user_id, organization_id = args[0], args[1] + user = User.find_by_id(user_id) + organization = Organization.find_by_id(organization_id) + return unless user.present? && organization.present? + receivers = User.where(id: user.id) + receivers_string, content, notification_url = MessageTemplate::OrganizationJoined.get_message_content(receivers, organization) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {user_id: user.id, organization_id: organization.id}) + when 'OrganizationLeft' + user_id, organization_id = args[0], args[1] + user = User.find_by_id(user_id) + organization = Organization.find_by_id(organization_id) + return unless user.present? && organization.present? + receivers = User.where(id: user.id) + receivers_string, content, notification_url = MessageTemplate::OrganizationLeft.get_message_content(receivers, organization) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {user_id: user.id, organization_id: organization.id}) + when 'OrganizationRole' + user_id, organization_id, role = args[0], args[1], args[2] + user = User.find_by_id(user_id) + organization = Organization.find_by_id(organization_id) + return unless user.present? && organization.present? + receivers = User.where(id: user.id) + receivers_string, content, notification_url = MessageTemplate::OrganizationRole.get_message_content(receivers, organization, role) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {user_id: user.id, organization_id: organization.id, role: role}) + when 'ProjectJoined' + user_id, project_id = args[0], args[1] + user = User.find_by_id(user_id) + project = Project.find_by_id(project_id) + return unless user.present? && project.present? + receivers = User.where(id: user.user_id) + receivers_string, content, notification_url = MessageTemplate::ProjectJoined.get_message_content(receivers, project) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {user_id: user.id, project_id: project.id}) + when 'ProjectLeft' + user_id, project_id = args[0], args[1] + user = User.find_by_id(user_id) + project = Project.find_by_id(project_id) + return unless user.present? && project.present? + receivers = User.where(id: user.user_id) + receivers_string, content, notification_url = MessageTemplate::ProjectJoined.get_message_content(receivers, project) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {user_id: user.id, project_id: project.id}) + when 'ProjectRole' + user_id, project_id, role = args[0], args[1], args[2] + user = User.find_by_id(user_id) + project = Project.find_by_id(project_id) + return unless user.present? && project.present? + receivers = User.where(id: user.user_id) + receivers_string, content, notification_url = MessageTemplate::ProjectRole.get_message_content(receivers, project, role) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {user_id: user.id, project_id: project.id, role: role}) + when 'ProjectSettingChanged' + operator_id, project_id, change_params = args[0], args[1], args[2] + operator = User.find_by_id(operator_id) + project = Project.find_by_id(project_id) + return unless operator.present? && project.present? + receivers = project.all_managers + receivers_string, content, notification_url = MessageTemplate::ProjectSettingChanged.get_message_content(receivers, operator, project, change_params.symbolize_keys) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, project_id: project.id, change_params: change_params}) + when 'PullRequestAssigned' + operator_id, pull_request_id = args[0], args[1] + operator = User.find_by_id(operator_id) + pull_request = PullRequest.find_by_id(pull_request_id) + return unless operator.present? && pull_request.present? + receivers = User.where(id: pull_request&.issue&.assigned_to_id) + receivers_string, content, notification_url = MessageTemplate::PullRequestAssigned.get_message_content(receivers, operator, pull_request) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, pull_request_id: pull_request.id}) + when 'PullRequestAtme' + receivers, operator_id, pull_request_id = args[0], args[1], args[2] + operator = User.find_by_id(operator_id) + pull_request = PullRequest.find_by_id(pull_request_id) + return unless operator.present? && pull_request.present? + receivers_string, content, notification_url = MessageTemplate::PullRequestAtme.get_message_content(receivers, operator, pull_request) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, pull_request_id: pull_request.id}, 2) + when 'PullRequestChanged' + operator_id, pull_request_id, change_params = args[0], args[1], args[2] + operator = User.find_by_id(operator_id) + pull_request = PullRequest.find_by_id(pull_request_id) + return unless operator.present? && pull_request.present? + receivers = User.where(id: [pull_request&.issue&.assigned_to_id, pull_request&.user_id]) + receivers_string, content, notification_url = MessageTemplate::PullRequestChanged.get_message_content(receivers, operator, pull_request, change_params.symbolize_keys) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, pull_request_id: pull_request.id, change_params: change_params}) + when 'PullRequestClosed' + operator_id, pull_request_id = args[0], args[1] + operator = User.find_by_id(operator_id) + pull_request = PullRequest.find_by_id(pull_request_id) + return unless operator.present? && pull_request.present? + receivers = User.where(id: [pull_request&.issue&.assigned_to_id, pull_request&.user_id]) + receivers_string, content, notification_url = MessageTemplate::PullRequestClosed.get_message_content(receivers, operator, pull_request) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, pull_request_id: pull_request.id}) + when 'PullRequestMerged' + operator_id, pull_request_id = args[0], args[1] + operator = User.find_by_id(operator_id) + pull_request = PullRequest.find_by_id(pull_request_id) + return unless operator.present? && pull_request.present? + receivers = User.where(id: [pull_request&.issue&.assigned_to_id, pull_request&.user_id]) + receivers_string, content, notification_url = MessageTemplate::PullRequestMerged.get_message_content(receivers, operator, pull_request) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, pull_request_id: pull_request.id}) end end end \ No newline at end of file diff --git a/app/models/message_template/issue_atme.rb b/app/models/message_template/issue_atme.rb index 0aa1c946..1738838e 100644 --- a/app/models/message_template/issue_atme.rb +++ b/app/models/message_template/issue_atme.rb @@ -19,7 +19,7 @@ class MessageTemplate::IssueAtme < MessageTemplate project = issue&.project owner = project&.owner content = sys_notice.gsub('{nickname}', operator&.nickname).gsub('{title}', issue&.subject) - url = notification_url.gsub('{owner}', owner&.login).gsub('{identifer}', project&.identifier).gsub('{id}', issue&.id.to_s) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s) return receivers_string(receivers), content, url rescue => e Rails.logger.info("MessageTemplate::IssueAtme.get_message_content [ERROR] #{e}") diff --git a/app/models/message_template/issue_changed.rb b/app/models/message_template/issue_changed.rb index 33cd6170..ddecab80 100644 --- a/app/models/message_template/issue_changed.rb +++ b/app/models/message_template/issue_changed.rb @@ -14,116 +14,132 @@ # 我创建或负责的易修状态变更 class MessageTemplate::IssueChanged < MessageTemplate - # MessageTemplate::IssueChanged.get_message_content(User.where(login: 'yystopf'), User.last, Issue.last, {assigner: 'testforge2', milestone: '里程碑', tag: '标签', priority: '低', tracker: '支持', doneratio: '70', branch: 'master', startdate: Date.today, duedate: Date.today + 1.days}) + # MessageTemplate::IssueChanged.get_message_content(User.where(login: 'yystopf'), User.last, Issue.last, {status_id: [1, 2], assigned_to_id: [nil, 203], tracker_id: [4, 3], priority_id: [2, 4], fixed_version_id: [nil, 5], due_date: ['', '2021-09-11'], done_ratio: [0, 40], issue_tags_value: ["", "7"], branch_name: ["", "master"]}) def self.get_message_content(receivers, operator, issue, change_params) + return '', '', '' if change_params.blank? project = issue&.project owner = project&.owner content = MessageTemplate::IssueChanged.sys_notice.gsub('{nickname1}', operator&.nickname).gsub('{nickname2}', owner&.nickname).gsub('{repository}', project&.name).gsub('{title}', issue&.subject) url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s) # 易修负责人修改 - if change_params[:assigner].present? - assigner = issue&.get_assign_user&.nickname || '未指派成员' + if change_params[:assigned_to_id].present? + assigner1 = User.find_by_id(change_params[:assigned_to_id][0]) + assigner2 = User.find_by_id(change_params[:assigned_to_id][1]) content.sub!('{ifassigner}', '') content.sub!('{endassigner}', '') - content.gsub!('{assigner1}', assigner) - content.gsub!('{assigner2}', change_params[:assigner]) + content.gsub!('{assigner1}', assigner1.present? ? assigner1&.nickname || assigner1.login : '未指派成员') + content.gsub!('{assigner2}', assigner2.present? ? assigner2&.nickname || assigner2.login : '未指派成员') else content.gsub!(/({ifassigner})(.*)({endassigner})/, '') end # 易修状态修改 - if change_params[:status].present? - status = issue&.issue_status&.name + if change_params[:status_id].present? + status1 = IssueStatus.find_by_id(change_params[:status_id][0]) + status2 = IssueStatus.find_by_id(change_params[:status_id][1]) content.sub!('{ifstatus}', '') content.sub!('{endstatus}', '') - content.gsub!('{status1}', status) - content.gsub!('{status2}', change_params[:status]) + content.gsub!('{status1}', status1&.name) + content.gsub!('{status2}', status2&.name) else content.gsub!(/({ifstatus})(.*)({endstatus})/, '') end # 易修类型修改 - if change_params[:tracker].present? - tracker = issue&.tracker&.name + if change_params[:tracker_id].present? + tracker1 = Tracker.find_by_id(change_params[:tracker_id][0]) + tracker2 = Tracker.find_by_id(change_params[:tracker_id][1]) content.sub!('{iftracker}', '') content.sub!('{endtracker}', '') - content.gsub!('{tracker1}', tracker) - content.gsub!('{tracker2}', change_params[:tracker]) + content.gsub!('{tracker1}', tracker1&.name) + content.gsub!('{tracker2}', tracker2&.name) else content.gsub!(/({iftracker})(.*)({endtracker})/, '') end - # 合并请求里程碑修改 - if change_params[:milestone].present? - milestone = issue&.version&.name || '未选择里程碑' + # 易修里程碑修改 + if change_params[:fixed_version_id].present? + fix_version1 = Version.find_by_id(change_params[:fixed_version_id][0]) + fix_version2 = Version.find_by_id(change_params[:fixed_version_id][1]) content.sub!('{ifmilestone}', '') content.sub!('{endmilestone}', '') - content.gsub!('{milestone1}', milestone) - content.gsub!('{milestone2}', change_params[:milestone]) + content.gsub!('{milestone1}', fix_version1.present? ? fix_version1&.name : '未选择里程碑') + content.gsub!('{milestone2}', fix_version2.present? ? fix_version2&.name : '未选择里程碑') else content.gsub!(/({ifmilestone})(.*)({endmilestone})/, '') end - # 合并请求标签修改 - if change_params[:tag].present? - tag = issue&.issue_tags.distinct.pluck(:name).join(",") - tag = '未选择标签' if tag == '' + # 易修标签修改 + if change_params[:issue_tags_value].present? + issue_tags1 = IssueTag.where(id: change_params[:issue_tags_value][0]).distinct + issue_tags2 = IssueTag.where(id: change_params[:issue_tags_value][1]).distinct + tag1 = issue_tags1.pluck(:name).join(",").blank? ? '未选择标签' : issue_tags1.pluck(:name).join(",") + tag2 = issue_tags2.pluck(:name).join(",").blank? ? '未选择标签' : issue_tags2.pluck(:name).join(",") content.sub!('{iftag}', '') content.sub!('{endtag}', '') - content.gsub!('{tag1}', tag) - content.gsub!('{tag2}', change_params[:tag]) + content.gsub!('{tag1}', tag1) + content.gsub!('{tag2}', tag2) else content.gsub!(/({iftag})(.*)({endtag})()/, '') end - # 合并请求优先级修改 - if change_params[:priority].present? - priority = issue&.priority&.name + # 易修优先级修改 + if change_params[:priority_id].present? + priority1 = IssuePriority.find_by_id(change_params[:priority_id][0]) + priority2 = IssuePriority.find_by_id(change_params[:priority_id][1]) + content.sub!('{ifpriority}', '') content.sub!('{endpriority}', '') - content.gsub!('{priority1}', priority) - content.gsub!('{priority2}', change_params[:priority]) + content.gsub!('{priority1}', priority1&.name) + content.gsub!('{priority2}', priority2&.name) else content.gsub!(/({ifpriority})(.*)({endpriority})/, '') end # 易修完成度修改 - if change_params[:doneratio].present? - doneratio = issue&.done_ratio + if change_params[:done_ratio].present? + doneratio1 = change_params[:done_ratio][0] + doneratio2 = change_params[:done_ratio][1] + content.sub!('{ifdoneratio}', '') content.sub!('{enddoneratio}', '') - content.gsub!('{doneratio1}', "#{doneratio}%") - content.gsub!('{doneratio2}', "#{change_params[:doneratio]}%") + content.gsub!('{doneratio1}', "#{doneratio1}%") + content.gsub!('{doneratio2}', "#{doneratio2}%") else content.gsub!(/({ifdoneratio})(.*)({enddoneratio})/, '') end # 易修指定分支修改 - if change_params[:branch].present? - branch = issue&.branch_name || '分支未指定' + if change_params[:branch_name].present? + branch1 = change_params[:branch_name][0].blank? ? '分支未指定' : change_params[:branch_name][0] + branch2 = change_params[:branch_name][1].blank? ? '分支未指定' : change_params[:branch_name][1] + content.sub!('{ifbranch}', '') content.sub!('{endbranch}', '') - content.gsub!('{branch1}', branch ) - content.gsub!('{branch2}', change_params[:branch]) + content.gsub!('{branch1}', branch1) + content.gsub!('{branch2}', branch2) else content.gsub!(/({ifbranch})(.*)({endbranch})/, '') end # 易修开始日期修改 - if change_params[:startdate].present? - startdate = issue&.start_date || "未选择开始日期" + if change_params[:start_date].present? + startdate1 = change_params[:start_date][0].blank? ? "未选择开始日期" : change_params[:start_date][0] + startdate2 = change_params[:start_date][1].blank? ? "未选择开始日期" : change_params[:start_date][1] + content.sub!('{ifstartdate}', '') content.sub!('{endstartdate}', '') - content.gsub!('{startdate1}', startdate.to_s ) - content.gsub!('{startdate2}', change_params[:startdate].to_s) + content.gsub!('{startdate1}', startdate1 ) + content.gsub!('{startdate2}', startdate2) else content.gsub!(/({ifstartdate})(.*)({endstartdate})/, '') end # 易修结束日期修改 - if change_params[:duedate].present? - duedate = issue&.due_date || '未选择结束日期' + if change_params[:due_date].present? + duedate1 = change_params[:due_date][0].blank? ? '未选择结束日期' : change_params[:due_date][0] + duedate2 = change_params[:due_date][1].blank? ? '未选择结束日期' : change_params[:due_date][1] content.sub!('{ifduedate}', '') content.sub!('{endduedate}', '') - content.gsub!('{duedate1}', duedate.to_s) - content.gsub!('{duedate2}', change_params[:duedate].to_s) + content.gsub!('{duedate1}', duedate1) + content.gsub!('{duedate2}', duedate2) else content.gsub!(/({ifduedate})(.*)({endduedate})/, '') end return receivers_string(receivers), content, url - # rescue => e - # Rails.logger.info("MessageTemplate::IssueAssigned.get_message_content [ERROR] #{e}") - # return '', '', '' + rescue => e + Rails.logger.info("MessageTemplate::IssueAssigned.get_message_content [ERROR] #{e}") + return '', '', '' end end diff --git a/app/models/message_template/issue_deleted.rb b/app/models/message_template/issue_deleted.rb index a261b713..8decdd15 100644 --- a/app/models/message_template/issue_deleted.rb +++ b/app/models/message_template/issue_deleted.rb @@ -14,11 +14,9 @@ # 我创建或负责的易修删除 class MessageTemplate::IssueDeleted < MessageTemplate - # MessageTemplate::IssueDeleted.get_message_content(User.where(login: 'yystopf'), User.last, Issue.last) - def self.get_message_content(receivers, operator, issue) - project = issue&.project - owner = project&.owner - content = sys_notice.gsub('{nickname}', operator&.nickname).gsub('{title}', issue&.subject) + # MessageTemplate::IssueDeleted.get_message_content(User.where(login: 'yystopf'), User.last, "hahah") + def self.get_message_content(receivers, operator, issue_title) + content = sys_notice.gsub('{nickname}', operator&.nickname).gsub('{title}', issue_title) return receivers_string(receivers), content, notification_url rescue => e Rails.logger.info("MessageTemplate::IssueAtme.get_message_content [ERROR] #{e}") diff --git a/app/models/message_template/project_setting_changed.rb b/app/models/message_template/project_setting_changed.rb index b62b52e4..fe9da7c5 100644 --- a/app/models/message_template/project_setting_changed.rb +++ b/app/models/message_template/project_setting_changed.rb @@ -16,6 +16,7 @@ class MessageTemplate::ProjectSettingChanged < MessageTemplate # MessageTemplate::ProjectSettingChanged.get_message_content(User.where(login: 'yystopf'), User.last, Project.last, {description: '测试修改项目简介', category: '大数据', language: 'Ruby', permission: '公有', navbar: '易修, 合并请求'}) def self.get_message_content(receivers, operator, project, change_params) + return '', '', '' if change_params.blank? owner = project&.owner content = sys_notice.gsub('{nickname1}', operator&.nickname).gsub('{nickname2}', owner&.nickname).gsub('{repository}', project&.name) url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier) @@ -23,7 +24,7 @@ class MessageTemplate::ProjectSettingChanged < MessageTemplate if change_params[:name].present? content.sub!('{ifname}', '') content.sub!('{endname}', '') - content.gsub!('{name}', change_params[:name]) + content.gsub!('{name}', change_params[:name][1]) else content.gsub!(/({ifname})(.*)({endname})/, '') end @@ -31,46 +32,57 @@ class MessageTemplate::ProjectSettingChanged < MessageTemplate if change_params[:description].present? content.sub!('{ifdescription}', '') content.sub!('{enddescription}', '') - content.gsub!('{description}', change_params[:description]) + content.gsub!('{description}', change_params[:description][1]) else content.gsub!(/({ifdescription})(.*)({enddescription})/, '') end # 项目类别更改 - if change_params[:category].present? + if change_params[:project_category_id].present? + category = ProjectCategory.find_by_id(change_params[:project_category_id][1]) content.sub!('{ifcategory}', '') content.sub!('{endcategory}', '') - content.gsub!('{category}', change_params[:category]) + content.gsub!('{category}', category&.name) else content.gsub!(/({ifcategory})(.*)({endcategory})/, '') end # 项目语言更改 - if change_params[:language].present? + if change_params[:project_language_id].present? + language = ProjectLanguage.find_by_id(change_params[:project_language_id][1]) content.sub!('{iflanguage}', '') content.sub!('{endlanguage}', '') - content.gsub!('{language}', change_params[:language]) + content.gsub!('{language}', language&.name) else content.gsub!(/({iflanguage})(.*)({endlanguage})/, '') end # 项目公私有更改 - if change_params[:permission].present? + if change_params[:is_public].present? + permission = change_params[:is_public][1] ? '公有' : '私有' content.sub!('{ifpermission}', '') content.sub!('{endpermission}', '') - content.gsub!('{permission}', change_params[:permission]) + content.gsub!('{permission}', permission) else content.gsub!(/({ifpermission})(.*)({endpermission})/, '') end # 项目导航更改 - if change_params[:navbar].present? + if change_params[:navbar].present? || navbar_is_changed_by_time + navbar = project.project_units.order(unit_type: :asc).pluck(:unit_type).join(',') + navbar.gsub!('code,', '') + navbar.gsub!('issues', '易修') + navbar.gsub!('pulls', '合并请求') + navbar.gsub!('wiki', 'Wiki') + navbar.gsub!('devops', '工作流') + navbar.gsub!('versions', '里程碑') + navbar.gsub!('resources', '资源库') content.sub!('{ifnavbar}', '') content.sub!('{endnavbar}', '') - content.gsub!('{navbar}', change_params[:navbar]) + content.gsub!('{navbar}', navbar) else content.gsub!(/({ifnavbar})(.*)({endnavbar})/, '') end return receivers_string(receivers.where.not(id: operator.id)), content, url - rescue => e - Rails.logger.info("MessageTemplate::ProjectSettingChanged.get_message_content [ERROR] #{e}") - return '', '', '' + # rescue => e + # Rails.logger.info("MessageTemplate::ProjectSettingChanged.get_message_content [ERROR] #{e}") + # return '', '', '' end end diff --git a/app/models/message_template/pull_request_changed.rb b/app/models/message_template/pull_request_changed.rb index 487b250b..6107a969 100644 --- a/app/models/message_template/pull_request_changed.rb +++ b/app/models/message_template/pull_request_changed.rb @@ -14,51 +14,57 @@ # 我创建或负责的合并请求状态变更 class MessageTemplate::PullRequestChanged < MessageTemplate - # MessageTemplate::PullRequestChanged.get_message_content(User.where(login: 'yystopf'), User.last, PullRequest.last, {assigner: 'testforge2', tag: '标签', priority: '低'}) + # MessageTemplate::PullRequestChanged.get_message_content(User.where(login: 'yystopf'), User.last, PullRequest.last, {assigned_to_id: [nil, 203], priority_id: [2, 4], fixed_version_id: [nil, 5], issue_tags_value: ["", "7"]}) def self.get_message_content(receivers, operator, pull_request, change_params) + return '', '', '' if change_params.blank? project = pull_request&.project owner = project&.owner issue = pull_request&.issue - content = sys_notice.gsub('{nickname1}', operator&.nickname).gsub('{nickname2}', owner&.nickname).gsub('{repository}', project&.name) + content = sys_notice.gsub('{nickname1}', operator&.nickname).gsub('{nickname2}', owner&.nickname).gsub('{repository}', project&.name).gsub("{title}", pull_request&.title) url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', pull_request&.id.to_s) # 合并请求审查成员修改 - if change_params[:assigner].present? - assigner = issue&.get_assign_user&.nickname || '未指派成员' + if change_params[:assigned_to_id].present? + assigner1 = User.find_by_id(change_params[:assigned_to_id][0]) + assigner2 = User.find_by_id(change_params[:assigned_to_id][1]) content.sub!('{ifassigner}', '') content.sub!('{endassigner}', '') - content.gsub!('{assigner1}', assigner) - content.gsub!('{assigner2}', change_params[:assigner]) + content.gsub!('{assigner1}', assigner1.present? ? assigner1&.nickname || assigner1.login : '未指派成员') + content.gsub!('{assigner2}', assigner2.present? ? assigner2&.nickname || assigner2.login : '未指派成员') else content.gsub!(/({ifassigner})(.*)({endassigner})/, '') end # 合并请求里程碑修改 - if change_params[:milestone].present? - milestone = issue&.version&.name || '未选择里程碑' + if change_params[:fixed_version_id].present? + fix_version1 = Version.find_by_id(change_params[:fixed_version_id][0]) + fix_version2 = Version.find_by_id(change_params[:fixed_version_id][1]) content.sub!('{ifmilestone}', '') content.sub!('{endmilestone}', '') - content.gsub!('{milestone1}', milestone) - content.gsub!('{milestone2}', change_params[:milestone]) + content.gsub!('{milestone1}', fix_version1.present? ? fix_version1&.name : '未选择里程碑') + content.gsub!('{milestone2}', fix_version2.present? ? fix_version2&.name : '未选择里程碑') else content.gsub!(/({ifmilestone})(.*)({endmilestone})/, '') end # 合并请求标签修改 - if change_params[:tag].present? - tag = issue&.issue_tags.distinct.pluck(:name).join(",") - tag = '未选择标签' if tag == '' + if change_params[:issue_tags_value].present? + issue_tags1 = IssueTag.where(id: change_params[:issue_tags_value][0]).distinct + issue_tags2 = IssueTag.where(id: change_params[:issue_tags_value][1]).distinct + tag1 = issue_tags1.pluck(:name).join(",").blank? ? '未选择标签' : issue_tags1.pluck(:name).join(",") + tag2 = issue_tags2.pluck(:name).join(",").blank? ? '未选择标签' : issue_tags2.pluck(:name).join(",") content.sub!('{iftag}', '') content.sub!('{endtag}', '') - content.gsub!('{tag1}', tag) - content.gsub!('{tag2}', change_params[:tag]) + content.gsub!('{tag1}', tag1) + content.gsub!('{tag2}', tag2) else content.gsub!(/({iftag})(.*)({endtag})()/, '') end # 合并请求优先级修改 - if change_params[:priority].present? - priority = issue&.priority&.name + if change_params[:priority_id].present? + priority1 = IssuePriority.find_by_id(change_params[:priority_id][0]) + priority2 = IssuePriority.find_by_id(change_params[:priority_id][1]) content.sub!('{ifpriority}', '') content.sub!('{endpriority}', '') - content.gsub!('{priority1}', priority) - content.gsub!('{priority2}', change_params[:priority]) + content.gsub!('{priority1}', priority1&.name) + content.gsub!('{priority2}', priority2&.name) else content.gsub!(/({ifpriority})(.*)({endpriority})/, '') end diff --git a/app/models/organization_user.rb b/app/models/organization_user.rb index cf9e2237..1ad2abd9 100644 --- a/app/models/organization_user.rb +++ b/app/models/organization_user.rb @@ -22,6 +22,9 @@ class OrganizationUser < ApplicationRecord validates :user_id, uniqueness: {scope: :organization_id} + after_create :send_create_message_to_notice_system + after_destroy :send_destroy_message_to_notice_system + def self.build(organization_id, user_id) org_user = self.find_by(organization_id: organization_id, user_id: user_id) return org_user unless org_user.nil? @@ -31,4 +34,12 @@ class OrganizationUser < ApplicationRecord def teams organization.teams.joins(:team_users).where(team_users: {user_id: user_id}) end + + def send_create_message_to_notice_system + SendTemplateMessageJob.perform_later('OrganizationJoined', self.user_id, self.organization_id) + end + + def send_destroy_message_to_notice_system + SendTemplateMessageJob.perform_later('OrganizationLeft', self.user_id, self.organization_id) + end end diff --git a/app/models/project_unit.rb b/app/models/project_unit.rb index 5c519e1d..cc35a6b2 100644 --- a/app/models/project_unit.rb +++ b/app/models/project_unit.rb @@ -32,9 +32,13 @@ class ProjectUnit < ApplicationRecord types.delete("pulls") if project.sync_mirror? # 默认code类型自动创建 types << "code" + before_units = project.project_units.pluck(:unit_type).sort project.project_units.where.not(unit_type: types).each(&:destroy!) types.each do |type| project.project_units.find_or_create_by!(unit_type: type) end + after_units = project.project_units.pluck(:unit_type).sort + return before_units, after_units end + end diff --git a/app/models/team.rb b/app/models/team.rb index 72df0509..481e8c34 100644 --- a/app/models/team.rb +++ b/app/models/team.rb @@ -54,4 +54,15 @@ class Team < ApplicationRecord team_users.where(user_id: user_id).present? end + def authorize_name + case self.authorize + when 'read' then '报告者' + when 'write' then '开发者' + when 'admin' then '管理员' + when 'owner' then '管理员' + else + '' + end + end + end diff --git a/app/models/watcher.rb b/app/models/watcher.rb index ccc8eefa..7ff20943 100644 --- a/app/models/watcher.rb +++ b/app/models/watcher.rb @@ -24,6 +24,7 @@ class Watcher < ApplicationRecord after_save :reset_cache_data after_destroy :reset_cache_data + after_create :send_create_message_to_notice_system def reset_cache_data if self.watchable.is_a?(User) @@ -35,4 +36,8 @@ class Watcher < ApplicationRecord self.reset_platform_cache_async_job end + def send_create_message_to_notice_system + SendTemplateMessageJob.perform_later('FollowTip', self.id) if self.watchable.is_a?(User) + end + end diff --git a/app/services/notice/write/create_service.rb b/app/services/notice/write/create_service.rb index 76883c67..9c1b8492 100644 --- a/app/services/notice/write/create_service.rb +++ b/app/services/notice/write/create_service.rb @@ -1,7 +1,7 @@ class Notice::Write::CreateService < Notice::Write::ClientService attr_accessor :receivers, :sender, :content, :notification_url, :source, :extra, :type - def initialize(receivers, content, notification_url, source, type=1, extra={},sender=-1) + def initialize(receivers, content, notification_url, source, extra={}, type=1, sender=-1) @receivers = receivers @sender = sender @content = content @@ -12,6 +12,7 @@ class Notice::Write::CreateService < Notice::Write::ClientService end def call + return nil if request_receivers.blank? result = post("", request_params) response = render_response(result) end @@ -19,7 +20,7 @@ class Notice::Write::CreateService < Notice::Write::ClientService private def request_receivers - receivers.join(",") + receivers.is_a?(Array) ? receivers.join(",") : receivers end def request_params diff --git a/public/docs/api.html b/public/docs/api.html index 6446d796..c77c0898 100644 --- a/public/docs/api.html +++ b/public/docs/api.html @@ -921,7 +921,7 @@ Success — a happy kitten is an authenticated kitten!

    Users

    获取当前登陆用户信息

    @@ -1326,14 +1326,14 @@ Success — a happy kitten is an authenticated kitten! 消息类型 -recervers_login +receivers_login array 需要发送消息的用户名数组 atmeable_type string -atme消息对象,是从哪里@我的,比如评论:Journal +atme消息对象,是从哪里@我的,比如评论:Journal、易修:Issue、合并请求:PullRequest atmeable_id From cb76a946ef5f870db50e063655e47f99a4a45a3a Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 16 Sep 2021 09:21:35 +0800 Subject: [PATCH 032/135] fix --- app/jobs/send_template_message_job.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/jobs/send_template_message_job.rb b/app/jobs/send_template_message_job.rb index f1e73a7e..52d4f31b 100644 --- a/app/jobs/send_template_message_job.rb +++ b/app/jobs/send_template_message_job.rb @@ -85,7 +85,7 @@ class SendTemplateMessageJob < ApplicationJob user = User.find_by_id(user_id) project = Project.find_by_id(project_id) return unless user.present? && project.present? - receivers = User.where(id: user.user_id) + receivers = User.where(id: user.id) receivers_string, content, notification_url = MessageTemplate::ProjectJoined.get_message_content(receivers, project) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {user_id: user.id, project_id: project.id}) when 'ProjectLeft' @@ -93,7 +93,7 @@ class SendTemplateMessageJob < ApplicationJob user = User.find_by_id(user_id) project = Project.find_by_id(project_id) return unless user.present? && project.present? - receivers = User.where(id: user.user_id) + receivers = User.where(id: user.id) receivers_string, content, notification_url = MessageTemplate::ProjectJoined.get_message_content(receivers, project) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {user_id: user.id, project_id: project.id}) when 'ProjectRole' @@ -101,7 +101,7 @@ class SendTemplateMessageJob < ApplicationJob user = User.find_by_id(user_id) project = Project.find_by_id(project_id) return unless user.present? && project.present? - receivers = User.where(id: user.user_id) + receivers = User.where(id: user.id) receivers_string, content, notification_url = MessageTemplate::ProjectRole.get_message_content(receivers, project, role) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {user_id: user.id, project_id: project.id, role: role}) when 'ProjectSettingChanged' From b8a52107a5d14453ee7b466a4584a618fa97eebe Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 16 Sep 2021 10:10:05 +0800 Subject: [PATCH 033/135] add: expire issue send message --- app/jobs/delay_expired_issue_job.rb | 11 +++++++++++ app/jobs/send_template_message_job.rb | 4 ++-- .../message_template/project_setting_changed.rb | 2 +- config/sidekiq.yml | 1 + config/sidekiq_cron.yml | 5 +++++ 5 files changed, 20 insertions(+), 3 deletions(-) create mode 100644 app/jobs/delay_expired_issue_job.rb diff --git a/app/jobs/delay_expired_issue_job.rb b/app/jobs/delay_expired_issue_job.rb new file mode 100644 index 00000000..4633a953 --- /dev/null +++ b/app/jobs/delay_expired_issue_job.rb @@ -0,0 +1,11 @@ +class DelayExpiredIssueJob < ApplicationJob + queue_as :message + + def perform + Issue.where(due_date: Date.today + 1.days).find_each do |issue| + SendTemplateMessageJob.perform_later('IssueAssignerExpire', issue.id) + SendTemplateMessageJob.perform_later('IssueCreatorExpire', issue.id) + end + end + +end \ No newline at end of file diff --git a/app/jobs/send_template_message_job.rb b/app/jobs/send_template_message_job.rb index 52d4f31b..9c94e16e 100644 --- a/app/jobs/send_template_message_job.rb +++ b/app/jobs/send_template_message_job.rb @@ -1,5 +1,5 @@ class SendTemplateMessageJob < ApplicationJob - queue_as :default + queue_as :message def perform(source, *args) Rails.logger.info "SendTemplateMessageJob [args] #{args}" @@ -94,7 +94,7 @@ class SendTemplateMessageJob < ApplicationJob project = Project.find_by_id(project_id) return unless user.present? && project.present? receivers = User.where(id: user.id) - receivers_string, content, notification_url = MessageTemplate::ProjectJoined.get_message_content(receivers, project) + receivers_string, content, notification_url = MessageTemplate::ProjectLeft.get_message_content(receivers, project) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {user_id: user.id, project_id: project.id}) when 'ProjectRole' user_id, project_id, role = args[0], args[1], args[2] diff --git a/app/models/message_template/project_setting_changed.rb b/app/models/message_template/project_setting_changed.rb index fe9da7c5..8c272f65 100644 --- a/app/models/message_template/project_setting_changed.rb +++ b/app/models/message_template/project_setting_changed.rb @@ -64,7 +64,7 @@ class MessageTemplate::ProjectSettingChanged < MessageTemplate content.gsub!(/({ifpermission})(.*)({endpermission})/, '') end # 项目导航更改 - if change_params[:navbar].present? || navbar_is_changed_by_time + if change_params[:navbar].present? navbar = project.project_units.order(unit_type: :asc).pluck(:unit_type).join(',') navbar.gsub!('code,', '') navbar.gsub!('issues', '易修') diff --git a/config/sidekiq.yml b/config/sidekiq.yml index a50c1c1a..f8981a8b 100644 --- a/config/sidekiq.yml +++ b/config/sidekiq.yml @@ -8,3 +8,4 @@ - [notify, 100] - [mailers, 101] - [cache, 10] + - [message, 20] diff --git a/config/sidekiq_cron.yml b/config/sidekiq_cron.yml index 3e807fa1..448e9c94 100644 --- a/config/sidekiq_cron.yml +++ b/config/sidekiq_cron.yml @@ -2,3 +2,8 @@ sync_gitea_repo_update_time: cron: "0 0 * * *" class: "SyncRepoUpdateTimeJob" queue: default + +delay_expired_issue: + cron: "0 0 * * *" + class: "DelayExpiredIssueJob" + queue: message From dbcbc01251c38ba64bb682650487353779ff52d2 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 16 Sep 2021 16:54:49 +0800 Subject: [PATCH 034/135] fix and add some message feature --- api_document.md | 8 +- app/controllers/issues_controller.rb | 22 ++++- app/controllers/members_controller.rb | 8 +- app/controllers/pull_requests_controller.rb | 1 + app/controllers/users_controller.rb | 8 +- app/jobs/send_template_message_job.rb | 83 ++++++++++++++----- app/models/message_template.rb | 6 +- app/models/message_template/followed_tip.rb | 2 +- app/models/message_template/issue_assigned.rb | 2 +- app/models/message_template/issue_atme.rb | 2 +- app/models/message_template/issue_changed.rb | 72 ++++++++++++---- app/models/message_template/issue_deleted.rb | 2 +- .../message_template/organization_joined.rb | 2 +- .../message_template/organization_left.rb | 2 +- .../message_template/organization_role.rb | 2 +- app/models/message_template/project_issue.rb | 10 ++- .../message_template/project_member_joined.rb | 6 +- .../message_template/project_member_left.rb | 8 +- .../message_template/project_pull_request.rb | 10 ++- .../project_setting_changed.rb | 47 ++++++++--- .../message_template/pull_request_assigned.rb | 2 +- .../message_template/pull_request_atme.rb | 2 +- .../message_template/pull_request_changed.rb | 30 +++++-- app/services/projects/accept_join_service.rb | 2 + 24 files changed, 250 insertions(+), 89 deletions(-) diff --git a/api_document.md b/api_document.md index 3f609ed3..8a579f8e 100644 --- a/api_document.md +++ b/api_document.md @@ -26,11 +26,11 @@ POST accounts/remote_register *示例* ```bash curl -X POST \ --d "email=yystopf@163.com" \ --d "password=a19960425" \ --d "username=yystopf" \ +-d "email=2456233122@qq.com" \ +-d "password=djs_D_00001" \ +-d "username=16895620" \ -d "platform=forge" \ -http://120.132.31.109:8080/api/accounts/remote_register | jq +http://localhost:3000/api/accounts/remote_register | jq ``` *请求参数说明:* diff --git a/app/controllers/issues_controller.rb b/app/controllers/issues_controller.rb index e383a4f5..208e68a4 100644 --- a/app/controllers/issues_controller.rb +++ b/app/controllers/issues_controller.rb @@ -112,6 +112,7 @@ class IssuesController < ApplicationController @issue = Issue.new(issue_params) if @issue.save! SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @issue&.id) + SendTemplateMessageJob.perform_later('ProjectIssue', current_user.id, @issue&.id) if params[:attachment_ids].present? params[:attachment_ids].each do |id| attachment = Attachment.select(:id, :container_id, :container_type)&.find_by_id(id) @@ -288,8 +289,12 @@ class IssuesController < ApplicationController def clean #批量删除,暂时只能删除未悬赏的 issue_ids = params[:ids] - if issue_ids.present? - if Issue.where(id: issue_ids, issue_type: "1").destroy_all + issues = Issue.where(id: issue_ids, issue_type: "1") + if issues.present? + issues.find_each do |i| + SendTemplateMessageJob.perform_later('IssueDeleted', current_user.id, i&.subject, i.assigned_to_id, i.author_id) + end + if issues.destroy_all normal_status(0, "删除成功") else normal_status(-1, "删除失败") @@ -323,7 +328,18 @@ class IssuesController < ApplicationController if update_hash.blank? normal_status(-1, "请选择批量更新内容") elsif issues&.update(update_hash) - issues.map{|i| i.create_journal_detail(false, [], [], current_user&.id) if i.previous_changes.present?} + issues.each do |i| + i.create_journal_detail(false, [], [], current_user&.id) if i.previous_changes.present? + previous_changes = i.previous_changes.slice(:status_id, :assigned_to_id, :tracker_id, :priority_id, :fixed_version_id, :done_ratio, :issue_tags_value, :branch_name) + if i.previous_changes[:start_date].present? + previous_changes.merge!(start_date: [i.previous_changes[:start_date][0].to_s, i.previous_changes[:start_date][1].to_s]) + end + if i.previous_changes[:due_date].present? + previous_changes.merge!(due_date: [i.previous_changes[:due_date][0].to_s, i.previous_changes[:due_date][1].to_s]) + end + SendTemplateMessageJob.perform_later('IssueChanged', current_user.id, i&.id, previous_changes) + SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, i&.id) if i.previous_changes[:assigned_to_id].present? + end normal_status(0, "批量更新成功") else normal_status(-1, "批量更新失败") diff --git a/app/controllers/members_controller.rb b/app/controllers/members_controller.rb index 36c57b5b..0af4898f 100644 --- a/app/controllers/members_controller.rb +++ b/app/controllers/members_controller.rb @@ -9,7 +9,8 @@ class MembersController < ApplicationController def create interactor = Projects::AddMemberInteractor.call(@project.owner, @project, @user) - SendTemplateMessageJob.perform_later('ProjectJoined', @user.id, @project.id) + SendTemplateMessageJob.perform_later('ProjectJoined', current_user.id, @user.id, @project.id) + SendTemplateMessageJob.perform_later('ProjectMemberJoined', current_user.id, @user.id, @project.id) render_response(interactor) rescue Exception => e uid_logger_error(e.message) @@ -29,7 +30,8 @@ class MembersController < ApplicationController def remove interactor = Projects::DeleteMemberInteractor.call(@project.owner, @project, @user) - SendTemplateMessageJob.perform_later('ProjectLeft', @user.id, @project.id) + SendTemplateMessageJob.perform_later('ProjectLeft', current_user.id, @user.id, @project.id) + SendTemplateMessageJob.perform_later('ProjectMemberLeft', current_user.id, @user.id, @project.id) render_response(interactor) rescue Exception => e uid_logger_error(e.message) @@ -38,7 +40,7 @@ class MembersController < ApplicationController def change_role interactor = Projects::ChangeMemberRoleInteractor.call(@project.owner, @project, @user, params[:role]) - SendTemplateMessageJob.perform_later('ProjectRole', @user.id, @project.id, message_role_name) + SendTemplateMessageJob.perform_later('ProjectRole', current_user.id, @user.id, @project.id, message_role_name) render_response(interactor) rescue Exception => e uid_logger_error(e.message) diff --git a/app/controllers/pull_requests_controller.rb b/app/controllers/pull_requests_controller.rb index 0799beb5..fe1edab5 100644 --- a/app/controllers/pull_requests_controller.rb +++ b/app/controllers/pull_requests_controller.rb @@ -60,6 +60,7 @@ class PullRequestsController < ApplicationController if @gitea_pull_request[:status] == :success @pull_request.bind_gitea_pull_request!(@gitea_pull_request[:body]["number"]) SendTemplateMessageJob.perform_later('PullRequestAssigned', current_user.id, @pull_request&.id) + SendTemplateMessageJob.perform_later('ProjectPullRequest', current_user.id, @pull_request&.id) render_ok else render_error("create pull request error: #{@gitea_pull_request[:status]}") diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index c69dfdb6..b80827ef 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -91,8 +91,12 @@ class UsersController < ApplicationController def get_user_info begin @user = current_user - result = Notice::Read::CountService.call(current_user.id) - @message_unread_total = result.nil? ? 0 : result[2]["unread_notification"] + 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 diff --git a/app/jobs/send_template_message_job.rb b/app/jobs/send_template_message_job.rb index 9c94e16e..d3593806 100644 --- a/app/jobs/send_template_message_job.rb +++ b/app/jobs/send_template_message_job.rb @@ -17,7 +17,7 @@ class SendTemplateMessageJob < ApplicationJob operator = User.find_by_id(operator_id) issue = Issue.find_by_id(issue_id) return unless operator.present? && issue.present? - receivers = User.where(id: issue&.assigned_to_id) + receivers = User.where(id: issue&.assigned_to_id).where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::IssueAssigned.get_message_content(receivers, operator, issue) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_id: issue.id}) when 'IssueAssignerExpire' @@ -32,6 +32,7 @@ class SendTemplateMessageJob < ApplicationJob operator = User.find_by_id(operator_id) issue = Issue.find_by_id(issue_id) return unless operator.present? && issue.present? + receivers = receivers.where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::IssueAtme.get_message_content(receivers, operator, issue) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_id: issue.id}, 2) when 'IssueChanged' @@ -39,7 +40,7 @@ class SendTemplateMessageJob < ApplicationJob operator = User.find_by_id(operator_id) issue = Issue.find_by_id(issue_id) return unless operator.present? && issue.present? - receivers = User.where(id: [issue&.assigned_to_id, issue&.author_id]) + receivers = User.where(id: [issue&.assigned_to_id, issue&.author_id]).where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::IssueChanged.get_message_content(receivers, operator, issue, change_params) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_id: issue.id, change_params: change_params.symbolize_keys}) when 'IssueCreatorExpire' @@ -53,7 +54,7 @@ class SendTemplateMessageJob < ApplicationJob operator_id, issue_title, issue_assigned_to_id, issue_author_id = args[0], args[1], args[2], args[3] operator = User.find_by_id(operator_id) return unless operator.present? - receivers = User.where(id: [issue_assigned_to_id, issue_author_id]) + receivers = User.where(id: [issue_assigned_to_id, issue_author_id]).where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::IssueDeleted.get_message_content(receivers, operator, issue_title) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_title: issue_title}) when 'OrganizationJoined' @@ -80,36 +81,75 @@ class SendTemplateMessageJob < ApplicationJob receivers = User.where(id: user.id) receivers_string, content, notification_url = MessageTemplate::OrganizationRole.get_message_content(receivers, organization, role) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {user_id: user.id, organization_id: organization.id, role: role}) + when 'ProjectIssue' + operator_id, issue_id = args[0], args[1] + operator = User.find_by_id(operator_id) + issue = Issue.find_by_id(issue_id) + return unless operator.present? && issue.present? && issue&.project.present? + managers = issue&.project&.all_managers.where.not(id: operator&.id) + followers = [] # TODO + receivers_string, content, notification_url = MessageTemplate::ProjectIssue.get_message_content(managers, followers, operator, issue) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_id: issue.id}) when 'ProjectJoined' - user_id, project_id = args[0], args[1] + operator_id, user_id, project_id = args[0], args[1], args[2] + operator = User.find_by_id(operator_id) user = User.find_by_id(user_id) project = Project.find_by_id(project_id) - return unless user.present? && project.present? - receivers = User.where(id: user.id) + return unless operator.present? && user.present? && project.present? + receivers = User.where(id: user.id).where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::ProjectJoined.get_message_content(receivers, project) - Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {user_id: user.id, project_id: project.id}) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, user_id: user.id, project_id: project.id}) when 'ProjectLeft' - user_id, project_id = args[0], args[1] + operator_id, user_id, project_id = args[0], args[1], args[2] + operator = User.find_by_id(operator_id) user = User.find_by_id(user_id) project = Project.find_by_id(project_id) - return unless user.present? && project.present? - receivers = User.where(id: user.id) + return unless operator.present? && user.present? && project.present? + receivers = User.where(id: user.id).where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::ProjectLeft.get_message_content(receivers, project) - Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {user_id: user.id, project_id: project.id}) - when 'ProjectRole' - user_id, project_id, role = args[0], args[1], args[2] + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, user_id: user.id, project_id: project.id}) + when 'ProjectMemberJoined' + operator_id, user_id, project_id = args[0], args[1], args[2] + operator = User.find_by_id(operator_id) user = User.find_by_id(user_id) project = Project.find_by_id(project_id) - return unless user.present? && project.present? - receivers = User.where(id: user.id) + return unless operator.present? && user.present? && project.present? + receivers = project&.all_managers.where.not(id: operator&.id) + receivers_string, content, notification_url = MessageTemplate::ProjectMemberJoined.get_message_content(receivers, user, project) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, user_id: user.id, project_id: project.id}) + when 'ProjectMemberLeft' + operator_id, user_id, project_id = args[0], args[1], args[2] + operator = User.find_by_id(operator_id) + user = User.find_by_id(user_id) + project = Project.find_by_id(project_id) + return unless operator.present? && user.present? && project.present? + receivers = project&.all_managers.where.not(id: operator&.id) + receivers_string, content, notification_url = MessageTemplate::ProjectMemberLeft.get_message_content(receivers, user, project) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, user_id: user.id, project_id: project.id}) + when 'ProjectPullRequest' + operator_id, pull_request_id = args[0], args[1] + operator = User.find_by_id(operator_id) + pull_request = PullRequest.find_by_id(pull_request_id) + return unless operator.present? && pull_request.present? && pull_request&.project.present? + managers = pull_request&.project&.all_managers.where.not(id: operator&.id) + followers = [] # TODO + receivers_string, content, notification_url = MessageTemplate::ProjectPullRequest.get_message_content(managers, followers, operator, pull_request) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, pull_request_id: pull_request.id}) + when 'ProjectRole' + operator_id, user_id, project_id, role = args[0], args[1], args[2], args[3] + operator = User.find_by_id(operator_id) + user = User.find_by_id(user_id) + project = Project.find_by_id(project_id) + return unless operator.present? && user.present? && project.present? + receivers = User.where(id: user.id).where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::ProjectRole.get_message_content(receivers, project, role) - Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {user_id: user.id, project_id: project.id, role: role}) + Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, user_id: user.id, project_id: project.id, role: role}) when 'ProjectSettingChanged' operator_id, project_id, change_params = args[0], args[1], args[2] operator = User.find_by_id(operator_id) project = Project.find_by_id(project_id) return unless operator.present? && project.present? - receivers = project.all_managers + receivers = project.all_managers.where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::ProjectSettingChanged.get_message_content(receivers, operator, project, change_params.symbolize_keys) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, project_id: project.id, change_params: change_params}) when 'PullRequestAssigned' @@ -117,7 +157,7 @@ class SendTemplateMessageJob < ApplicationJob operator = User.find_by_id(operator_id) pull_request = PullRequest.find_by_id(pull_request_id) return unless operator.present? && pull_request.present? - receivers = User.where(id: pull_request&.issue&.assigned_to_id) + receivers = User.where(id: pull_request&.issue&.assigned_to_id).where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::PullRequestAssigned.get_message_content(receivers, operator, pull_request) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, pull_request_id: pull_request.id}) when 'PullRequestAtme' @@ -125,6 +165,7 @@ class SendTemplateMessageJob < ApplicationJob operator = User.find_by_id(operator_id) pull_request = PullRequest.find_by_id(pull_request_id) return unless operator.present? && pull_request.present? + receivers = receivers.where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::PullRequestAtme.get_message_content(receivers, operator, pull_request) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, pull_request_id: pull_request.id}, 2) when 'PullRequestChanged' @@ -132,7 +173,7 @@ class SendTemplateMessageJob < ApplicationJob operator = User.find_by_id(operator_id) pull_request = PullRequest.find_by_id(pull_request_id) return unless operator.present? && pull_request.present? - receivers = User.where(id: [pull_request&.issue&.assigned_to_id, pull_request&.user_id]) + receivers = User.where(id: [pull_request&.issue&.assigned_to_id, pull_request&.user_id]).where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::PullRequestChanged.get_message_content(receivers, operator, pull_request, change_params.symbolize_keys) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, pull_request_id: pull_request.id, change_params: change_params}) when 'PullRequestClosed' @@ -140,7 +181,7 @@ class SendTemplateMessageJob < ApplicationJob operator = User.find_by_id(operator_id) pull_request = PullRequest.find_by_id(pull_request_id) return unless operator.present? && pull_request.present? - receivers = User.where(id: [pull_request&.issue&.assigned_to_id, pull_request&.user_id]) + receivers = User.where(id: [pull_request&.issue&.assigned_to_id, pull_request&.user_id]).where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::PullRequestClosed.get_message_content(receivers, operator, pull_request) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, pull_request_id: pull_request.id}) when 'PullRequestMerged' @@ -148,7 +189,7 @@ class SendTemplateMessageJob < ApplicationJob operator = User.find_by_id(operator_id) pull_request = PullRequest.find_by_id(pull_request_id) return unless operator.present? && pull_request.present? - receivers = User.where(id: [pull_request&.issue&.assigned_to_id, pull_request&.user_id]) + receivers = User.where(id: [pull_request&.issue&.assigned_to_id, pull_request&.user_id]).where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::PullRequestMerged.get_message_content(receivers, operator, pull_request) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, pull_request_id: pull_request.id}) end diff --git a/app/models/message_template.rb b/app/models/message_template.rb index 6c5e4df2..42aa64a4 100644 --- a/app/models/message_template.rb +++ b/app/models/message_template.rb @@ -18,7 +18,7 @@ class MessageTemplate {nickname2}/{repository}
    指派给你一个易修:{title}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') self.create(type: 'MessageTemplate::IssueAssignerExpire', sys_notice: '您负责的易修{title}已临近截止日期,请尽快处理', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') self.create(type: 'MessageTemplate::IssueAtme', sys_notice: '{nickname}在易修{title}中@我', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') - self.create(type: 'MessageTemplate::IssueChanged', sys_notice: '在项目{nickname2}/{repository}的易修{title}中:{ifassigner}{nickname1}将负责人从{assigner1}修改为{assigner2}
    {endassigner}{ifstatus}{nickname1}将状态从{status1}修改为{status2}
    {endstatus}{iftracker}{nickname1}将类型从{tracker1}修改为{tracker2}
    {endtracker}{ifpriority}{nickname1}将优先级从{priority1}修改为{priority2}
    {endpriority}{ifmilestone}{nickname1}将里程碑从{milestone1}修改为{milestone2}
    {endmilestone}{iftag}{nickname1}将标签从{tag1}修改为{tag2}
    {endtag}{ifdoneratio}{nickname1}将完成度从{doneratio2}修改为{doneratio1}{enddoneratio}
    {ifbranch}{nickname1}将指定分支从{branch1}修改为{branch2}
    {endbranch}{ifstartdate}{nickname1}将开始日期从{startdate1}修改为{startdate2}
    {endstartdate}{ifduedate}{nickname1}将结束日期从{duedate1}修改为{duedate2}
    {endduedate}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') + self.create(type: 'MessageTemplate::IssueChanged', sys_notice: '在项目{nickname2}/{repository}的易修{title}中:{ifassigner}{nickname1}将负责人从{assigner1}修改为{assigner2}{endassigner}{ifstatus}{nickname1}将状态从{status1}修改为{status2}{endstatus}{iftracker}{nickname1}将类型从{tracker1}修改为{tracker2}{endtracker}{ifpriority}{nickname1}将优先级从{priority1}修改为{priority2}{endpriority}{ifmilestone}{nickname1}将里程碑从{milestone1}修改为{milestone2}{endmilestone}{iftag}{nickname1}将标签从{tag1}修改为{tag2}{endtag}{ifdoneratio}{nickname1}将完成度从{doneratio1}修改为{doneratio2}{enddoneratio}{ifbranch}{nickname1}将指定分支从{branch1}修改为{branch2}{endbranch}{ifstartdate}{nickname1}将开始日期从{startdate1}修改为{startdate2}{endstartdate}{ifduedate}{nickname1}将结束日期从{duedate1}修改为{duedate2}{endduedate}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') self.create(type: 'MessageTemplate::IssueCreatorExpire', sys_notice: '您发布的易修{title}已临近截止日期,请尽快处理', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') self.create(type: 'MessageTemplate::IssueDeleted', sys_notice: '{nickname}已将易修{title}删除', notification_url: '') self.create(type: 'MessageTemplate::IssueJournal', sys_notice: '{nickname}评论易修{title}:{notes}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') @@ -38,12 +38,12 @@ class MessageTemplate {nickname}
    点赞了你管理的仓库', notification_url: '{baseurl}/{login}') self.create(type: 'MessageTemplate::ProjectPullRequest', sys_notice: '{nickname1}在{nickname2}/{repository}提交了一个合并请求:{title}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') self.create(type: 'MessageTemplate::ProjectRole', sys_notice: '仓库{repository}已把你的角色改为{role}', notification_url: '{baseurl}/{owner}/{identifier}') - self.create(type: 'MessageTemplate::ProjectSettingChanged', sys_notice: '{nickname1}更改了{nickname2}/{repository}仓库设置:{ifname}更改项目名称为"{name}";{endname}{ifdescription}更改项目简介为"{description}";{enddescription}{ifcategory}更改项目类别为"{category}";{endcategory}{iflanguage}更改项目语言为"{language}";{endlanguage}{ifpermission}将仓库设为"{permission}";{endpermission}{ifnavbar}将项目导航更改为"{navbar}";{endnavbar}', notification_url: '{baseurl}/{owner}/{identifier}/settings') + self.create(type: 'MessageTemplate::ProjectSettingChanged', sys_notice: '{nickname1}更改了{nickname2}/{repository}仓库设置:{ifname}更改项目名称为"{name}"{endname}{ifdescription}更改项目简介为"{description}"{enddescription}{ifcategory}更改项目类别为"{category}"{endcategory}{iflanguage}更改项目语言为"{language}"{endlanguage}{ifpermission}将仓库设为"{permission}"{endpermission}{ifnavbar}将项目导航更改为"{navbar}"{endnavbar}', notification_url: '{baseurl}/{owner}/{identifier}/settings') self.create(type: 'MessageTemplate::ProjectTransfer', sys_notice: '你关注的仓库{nickname1}/{repository1}已被转移至{nickname2}/{repository2}', notification_url: '{baseurl}/{owner}/{identifier}') self.create(type: 'MessageTemplate::ProjectVersion', sys_notice: '{nickname1}在{nickname2}/{repository}创建了发行版:{title}', notification_url: '{baseurl}/{owner}/{identifier}/releases') self.create(type: 'MessageTemplate::PullRequestAssigned', sys_notice: '{nickname1}在{nickname2}/{repository}指派给你一个合并请求:{title}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') self.create(type: 'MessageTemplate::PullRequestAtme', sys_notice: '{nickname}在合并请求{title}中@我', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') - self.create(type: 'MessageTemplate::PullRequestChanged', sys_notice: '在项目{nickname2}/{repository}的合并请求{title}中:{ifassigner}{nickname1}将审查成员从{assigner1}修改为{assigner2}
    {endassigner}{ifmilestone}{nickname1}将里程碑从{milestone1}修改为{milestone2}
    {endmilestone}{iftag}{nickname1}将标签从{tag1}修改为{tag2}
    {endtag}{ifpriority}{nickname1}将优先级从{priority1}修改为{priority2}
    {endpriority}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') + self.create(type: 'MessageTemplate::PullRequestChanged', sys_notice: '在项目{nickname2}/{repository}的合并请求{title}中:{ifassigner}{nickname1}将审查成员从{assigner1}修改为{assigner2}{endassigner}{ifmilestone}{nickname1}将里程碑从{milestone1}修改为{milestone2}{endmilestone}{iftag}{nickname1}将标签从{tag1}修改为{tag2}{endtag}{ifpriority}{nickname1}将优先级从{priority1}修改为{priority2}{endpriority}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') self.create(type: 'MessageTemplate::PullRequestClosed', sys_notice: '你提交的合并请求:{title}被拒绝', notification_url: '') self.create(type: 'MessageTemplate::PullRequestJournal', sys_notice: '{nickname}评论合并请求{title}:{notes}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') self.create(type: 'MessageTemplate::PullRequestMerged', sys_notice: '你提交的合并请求:{title}被合并', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') diff --git a/app/models/message_template/followed_tip.rb b/app/models/message_template/followed_tip.rb index 15a074fb..d8c6cba2 100644 --- a/app/models/message_template/followed_tip.rb +++ b/app/models/message_template/followed_tip.rb @@ -16,7 +16,7 @@ class MessageTemplate::FollowedTip < MessageTemplate # MessageTemplate::FollowedTip.get_message_content(User.where(login: 'yystopf'), User.last) def self.get_message_content(receivers, followeder) - return receivers_string(receivers), sys_notice.gsub('{nickname}', followeder&.nickname), notification_url.gsub('{login}', followeder.login) + return receivers_string(receivers), sys_notice.gsub('{nickname}', followeder&.real_name), notification_url.gsub('{login}', followeder.login) rescue return '', '', '' end diff --git a/app/models/message_template/issue_assigned.rb b/app/models/message_template/issue_assigned.rb index ccef717e..0507f2ac 100644 --- a/app/models/message_template/issue_assigned.rb +++ b/app/models/message_template/issue_assigned.rb @@ -18,7 +18,7 @@ class MessageTemplate::IssueAssigned < MessageTemplate def self.get_message_content(receivers, operator, issue) project = issue&.project owner = project&.owner - content = sys_notice.gsub('{nickname1}', operator&.nickname).gsub('{nickname2}', owner&.nickname).gsub('{repository}', project&.name).gsub('{title}', issue&.subject) + content = sys_notice.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub('{title}', issue&.subject) url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s) return receivers_string(receivers), content, url rescue => e diff --git a/app/models/message_template/issue_atme.rb b/app/models/message_template/issue_atme.rb index 1738838e..5678b31d 100644 --- a/app/models/message_template/issue_atme.rb +++ b/app/models/message_template/issue_atme.rb @@ -18,7 +18,7 @@ class MessageTemplate::IssueAtme < MessageTemplate def self.get_message_content(receivers, operator, issue) project = issue&.project owner = project&.owner - content = sys_notice.gsub('{nickname}', operator&.nickname).gsub('{title}', issue&.subject) + content = sys_notice.gsub('{nickname}', operator&.real_name).gsub('{title}', issue&.subject) url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s) return receivers_string(receivers), content, url rescue => e diff --git a/app/models/message_template/issue_changed.rb b/app/models/message_template/issue_changed.rb index ddecab80..f6f44367 100644 --- a/app/models/message_template/issue_changed.rb +++ b/app/models/message_template/issue_changed.rb @@ -19,16 +19,21 @@ class MessageTemplate::IssueChanged < MessageTemplate return '', '', '' if change_params.blank? project = issue&.project owner = project&.owner - content = MessageTemplate::IssueChanged.sys_notice.gsub('{nickname1}', operator&.nickname).gsub('{nickname2}', owner&.nickname).gsub('{repository}', project&.name).gsub('{title}', issue&.subject) + content = MessageTemplate::IssueChanged.sys_notice.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub('{title}', issue&.subject) url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s) + change_count = change_params.keys.size # 易修负责人修改 if change_params[:assigned_to_id].present? assigner1 = User.find_by_id(change_params[:assigned_to_id][0]) assigner2 = User.find_by_id(change_params[:assigned_to_id][1]) - content.sub!('{ifassigner}', '') + if change_count > 1 + content.sub!('{ifassigner}', '
    ') + else + content.sub!('{ifassigner}', '') + end content.sub!('{endassigner}', '') - content.gsub!('{assigner1}', assigner1.present? ? assigner1&.nickname || assigner1.login : '未指派成员') - content.gsub!('{assigner2}', assigner2.present? ? assigner2&.nickname || assigner2.login : '未指派成员') + content.gsub!('{assigner1}', assigner1.present? ? assigner1&.real_name : '未指派成员') + content.gsub!('{assigner2}', assigner2.present? ? assigner2&.real_name : '未指派成员') else content.gsub!(/({ifassigner})(.*)({endassigner})/, '') end @@ -36,7 +41,11 @@ class MessageTemplate::IssueChanged < MessageTemplate if change_params[:status_id].present? status1 = IssueStatus.find_by_id(change_params[:status_id][0]) status2 = IssueStatus.find_by_id(change_params[:status_id][1]) - content.sub!('{ifstatus}', '') + if change_count > 1 + content.sub!('{ifstatus}', '
    ') + else + content.sub!('{ifstatus}', '') + end content.sub!('{endstatus}', '') content.gsub!('{status1}', status1&.name) content.gsub!('{status2}', status2&.name) @@ -47,7 +56,11 @@ class MessageTemplate::IssueChanged < MessageTemplate if change_params[:tracker_id].present? tracker1 = Tracker.find_by_id(change_params[:tracker_id][0]) tracker2 = Tracker.find_by_id(change_params[:tracker_id][1]) - content.sub!('{iftracker}', '') + if change_count > 1 + content.sub!('{iftracker}', '
    ') + else + content.sub!('{iftracker}', '') + end content.sub!('{endtracker}', '') content.gsub!('{tracker1}', tracker1&.name) content.gsub!('{tracker2}', tracker2&.name) @@ -58,7 +71,11 @@ class MessageTemplate::IssueChanged < MessageTemplate if change_params[:fixed_version_id].present? fix_version1 = Version.find_by_id(change_params[:fixed_version_id][0]) fix_version2 = Version.find_by_id(change_params[:fixed_version_id][1]) - content.sub!('{ifmilestone}', '') + if change_count > 1 + content.sub!('{ifmilestone}', '
    ') + else + content.sub!('{ifmilestone}', '') + end content.sub!('{endmilestone}', '') content.gsub!('{milestone1}', fix_version1.present? ? fix_version1&.name : '未选择里程碑') content.gsub!('{milestone2}', fix_version2.present? ? fix_version2&.name : '未选择里程碑') @@ -71,8 +88,11 @@ class MessageTemplate::IssueChanged < MessageTemplate issue_tags2 = IssueTag.where(id: change_params[:issue_tags_value][1]).distinct tag1 = issue_tags1.pluck(:name).join(",").blank? ? '未选择标签' : issue_tags1.pluck(:name).join(",") tag2 = issue_tags2.pluck(:name).join(",").blank? ? '未选择标签' : issue_tags2.pluck(:name).join(",") - content.sub!('{iftag}', '') - content.sub!('{endtag}', '') + if change_count > 1 + content.sub!('{iftag}', '
    ') + else + content.sub!('{endtag}', '') + end content.gsub!('{tag1}', tag1) content.gsub!('{tag2}', tag2) else @@ -82,8 +102,11 @@ class MessageTemplate::IssueChanged < MessageTemplate if change_params[:priority_id].present? priority1 = IssuePriority.find_by_id(change_params[:priority_id][0]) priority2 = IssuePriority.find_by_id(change_params[:priority_id][1]) - - content.sub!('{ifpriority}', '') + if change_count > 1 + content.sub!('{ifpriority}', '
    ') + else + content.sub!('{ifpriority}', '') + end content.sub!('{endpriority}', '') content.gsub!('{priority1}', priority1&.name) content.gsub!('{priority2}', priority2&.name) @@ -94,8 +117,11 @@ class MessageTemplate::IssueChanged < MessageTemplate if change_params[:done_ratio].present? doneratio1 = change_params[:done_ratio][0] doneratio2 = change_params[:done_ratio][1] - - content.sub!('{ifdoneratio}', '') + if change_count > 1 + content.sub!('{ifdoneratio}', '
    ') + else + content.sub!('{ifdoneratio}', '') + end content.sub!('{enddoneratio}', '') content.gsub!('{doneratio1}', "#{doneratio1}%") content.gsub!('{doneratio2}', "#{doneratio2}%") @@ -106,8 +132,11 @@ class MessageTemplate::IssueChanged < MessageTemplate if change_params[:branch_name].present? branch1 = change_params[:branch_name][0].blank? ? '分支未指定' : change_params[:branch_name][0] branch2 = change_params[:branch_name][1].blank? ? '分支未指定' : change_params[:branch_name][1] - - content.sub!('{ifbranch}', '') + if change_count > 1 + content.sub!('{ifbranch}', '
    ') + else + content.sub!('{ifbranch}', '') + end content.sub!('{endbranch}', '') content.gsub!('{branch1}', branch1) content.gsub!('{branch2}', branch2) @@ -118,8 +147,11 @@ class MessageTemplate::IssueChanged < MessageTemplate if change_params[:start_date].present? startdate1 = change_params[:start_date][0].blank? ? "未选择开始日期" : change_params[:start_date][0] startdate2 = change_params[:start_date][1].blank? ? "未选择开始日期" : change_params[:start_date][1] - - content.sub!('{ifstartdate}', '') + if change_count > 1 + content.sub!('{ifstartdate}', '
    ') + else + content.sub!('{ifstartdate}', '') + end content.sub!('{endstartdate}', '') content.gsub!('{startdate1}', startdate1 ) content.gsub!('{startdate2}', startdate2) @@ -130,7 +162,11 @@ class MessageTemplate::IssueChanged < MessageTemplate if change_params[:due_date].present? duedate1 = change_params[:due_date][0].blank? ? '未选择结束日期' : change_params[:due_date][0] duedate2 = change_params[:due_date][1].blank? ? '未选择结束日期' : change_params[:due_date][1] - content.sub!('{ifduedate}', '') + if change_count > 1 + content.sub!('{ifduedate}', '
    ') + else + content.sub!('{ifduedate}', '') + end content.sub!('{endduedate}', '') content.gsub!('{duedate1}', duedate1) content.gsub!('{duedate2}', duedate2) diff --git a/app/models/message_template/issue_deleted.rb b/app/models/message_template/issue_deleted.rb index 8decdd15..46d7d6e6 100644 --- a/app/models/message_template/issue_deleted.rb +++ b/app/models/message_template/issue_deleted.rb @@ -16,7 +16,7 @@ class MessageTemplate::IssueDeleted < MessageTemplate # MessageTemplate::IssueDeleted.get_message_content(User.where(login: 'yystopf'), User.last, "hahah") def self.get_message_content(receivers, operator, issue_title) - content = sys_notice.gsub('{nickname}', operator&.nickname).gsub('{title}', issue_title) + content = sys_notice.gsub('{nickname}', operator&.real_name).gsub('{title}', issue_title) return receivers_string(receivers), content, notification_url rescue => e Rails.logger.info("MessageTemplate::IssueAtme.get_message_content [ERROR] #{e}") diff --git a/app/models/message_template/organization_joined.rb b/app/models/message_template/organization_joined.rb index d3a7ca1d..81ae2a67 100644 --- a/app/models/message_template/organization_joined.rb +++ b/app/models/message_template/organization_joined.rb @@ -16,7 +16,7 @@ class MessageTemplate::OrganizationJoined < MessageTemplate # MessageTemplate::OrganizationJoined.get_message_content(User.where(login: 'yystopf'), Organization.last) def self.get_message_content(receivers, organization) - content = sys_notice.gsub('{organization}', organization&.name) + content = sys_notice.gsub('{organization}', organization&.real_name) url = notification_url.gsub('{login}', organization&.name) return receivers_string(receivers), content, url rescue => e diff --git a/app/models/message_template/organization_left.rb b/app/models/message_template/organization_left.rb index 9fe84474..16652d30 100644 --- a/app/models/message_template/organization_left.rb +++ b/app/models/message_template/organization_left.rb @@ -16,7 +16,7 @@ class MessageTemplate::OrganizationLeft < MessageTemplate # MessageTemplate::OrganizationLeft.get_message_content(User.where(login: 'yystopf'), Organization.last) def self.get_message_content(receivers, organization) - content = sys_notice.gsub('{organization}', organization&.name) + content = sys_notice.gsub('{organization}', organization&.real_name) url = notification_url.gsub('{login}', organization&.name) return receivers_string(receivers), content, url rescue => e diff --git a/app/models/message_template/organization_role.rb b/app/models/message_template/organization_role.rb index 223ecf8b..33c32651 100644 --- a/app/models/message_template/organization_role.rb +++ b/app/models/message_template/organization_role.rb @@ -16,7 +16,7 @@ class MessageTemplate::OrganizationRole < MessageTemplate # MessageTemplate::OrganizationRole.get_message_content(User.where(login: 'yystopf'), Organization.last, '管理员') def self.get_message_content(receivers, organization, role) - content = sys_notice.gsub('{organization}', organization&.name).gsub('{role}', role) + content = sys_notice.gsub('{organization}', organization&.real_name).gsub('{role}', role) url = notification_url.gsub('{login}', organization&.login) return receivers_string(receivers), content, url rescue => e diff --git a/app/models/message_template/project_issue.rb b/app/models/message_template/project_issue.rb index 81904f23..700932ad 100644 --- a/app/models/message_template/project_issue.rb +++ b/app/models/message_template/project_issue.rb @@ -14,8 +14,14 @@ # TODO 我管理/关注的仓库有新的易修 class MessageTemplate::ProjectIssue < MessageTemplate - # MessageTemplate::ProjectIssue.get_message_content(User.where(login: 'yystopf')) - def self.get_message_content(receivers) + # MessageTemplate::ProjectIssue.get_message_content(User.where(login: 'yystopf'), User.where(login: 'forgetest1'), User.last, Issue.last) + def self.get_message_content(managers, followers, operator, issue) + project = issue&.project + owner = project&.owner + receivers = managers + followers + content = sys_notice.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub('{title}', issue&.subject) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s) + return receivers_string(receivers), content, url rescue => e Rails.logger.info("MessageTemplate::ProjectIssue.get_message_content [ERROR] #{e}") diff --git a/app/models/message_template/project_member_joined.rb b/app/models/message_template/project_member_joined.rb index c10edb59..a510265b 100644 --- a/app/models/message_template/project_member_joined.rb +++ b/app/models/message_template/project_member_joined.rb @@ -11,11 +11,13 @@ # notification_url :string(255) # -# TODO 我管理的仓库有成员加入 +# 我管理的仓库有成员加入 class MessageTemplate::ProjectMemberJoined < MessageTemplate # MessageTemplate::ProjectMemberJoined.get_message_content(User.where(login: 'yystopf')) - def self.get_message_content(receivers) + def self.get_message_content(receivers, user, project) + content = sys_notice.gsub('{nickname1}', user&.real_name).gsub('{nickname2}', project&.owner&.real_name).gsub('{repository}', project&.name) + url = notification_url.gsub('{owner}', project&.owner&.login).gsub('{identifier}', project&.identifier) return receivers_string(receivers), content, url rescue => e Rails.logger.info("MessageTemplate::ProjectMemberJoined.get_message_content [ERROR] #{e}") diff --git a/app/models/message_template/project_member_left.rb b/app/models/message_template/project_member_left.rb index b7133e05..9d26e102 100644 --- a/app/models/message_template/project_member_left.rb +++ b/app/models/message_template/project_member_left.rb @@ -11,11 +11,13 @@ # notification_url :string(255) # -# TODO 我管理的仓库有成员移出 +# 我管理的仓库有成员移出 class MessageTemplate::ProjectMemberLeft < MessageTemplate - # MessageTemplate::ProjectMemberLeft.get_message_content(User.where(login: 'yystopf')) - def self.get_message_content(receivers) + # MessageTemplate::ProjectMemberLeft.get_message_content(User.where(login: 'yystopf'), User.last, Project.last) + def self.get_message_content(receivers, user, project) + content = sys_notice.gsub('{nickname1}', user&.real_name).gsub('{nickname2}', project&.owner&.real_name).gsub('{repository}', project&.name) + url = notification_url.gsub('{owner}', project&.owner&.login).gsub('{identifier}', project&.identifier) return receivers_string(receivers), content, url rescue => e Rails.logger.info("MessageTemplate::ProjectMemberLeft.get_message_content [ERROR] #{e}") diff --git a/app/models/message_template/project_pull_request.rb b/app/models/message_template/project_pull_request.rb index f0c642d1..2db1021a 100644 --- a/app/models/message_template/project_pull_request.rb +++ b/app/models/message_template/project_pull_request.rb @@ -14,8 +14,14 @@ # TODO 我管理/关注的仓库有新的合并请求 class MessageTemplate::ProjectPullRequest < MessageTemplate - # MessageTemplate::ProjectPullRequest.get_message_content(User.where(login: 'yystopf')) - def self.get_message_content(receivers) + # MessageTemplate::ProjectPullRequest.get_message_content(User.where(login: 'yystopf'), User.where(login: 'testforge2'), User.last, PullRequest.last) + def self.get_message_content(managers, followers, operator, pull_request) + project = pull_request&.project + owner = project&.owner + receivers = managers + followers + content = sys_notice.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub('{title}', pull_request&.title) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', pull_request&.id.to_s) + return receivers_string(receivers), content, url rescue => e Rails.logger.info("MessageTemplate::ProjectPullRequest.get_message_content [ERROR] #{e}") diff --git a/app/models/message_template/project_setting_changed.rb b/app/models/message_template/project_setting_changed.rb index 8c272f65..f973f99d 100644 --- a/app/models/message_template/project_setting_changed.rb +++ b/app/models/message_template/project_setting_changed.rb @@ -18,11 +18,16 @@ class MessageTemplate::ProjectSettingChanged < MessageTemplate def self.get_message_content(receivers, operator, project, change_params) return '', '', '' if change_params.blank? owner = project&.owner - content = sys_notice.gsub('{nickname1}', operator&.nickname).gsub('{nickname2}', owner&.nickname).gsub('{repository}', project&.name) + content = sys_notice.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name) url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier) + change_count = change_params.keys.size # 项目名称更改 if change_params[:name].present? - content.sub!('{ifname}', '') + if change_count > 1 + content.sub!('{ifname}', '
    ') + else + content.sub!('{ifname}', '') + end content.sub!('{endname}', '') content.gsub!('{name}', change_params[:name][1]) else @@ -30,7 +35,11 @@ class MessageTemplate::ProjectSettingChanged < MessageTemplate end # 项目简介更改 if change_params[:description].present? - content.sub!('{ifdescription}', '') + if change_count > 1 + content.sub!('{ifdescription}', '
    ') + else + content.sub!('{ifdescription}', '') + end content.sub!('{enddescription}', '') content.gsub!('{description}', change_params[:description][1]) else @@ -39,7 +48,11 @@ class MessageTemplate::ProjectSettingChanged < MessageTemplate # 项目类别更改 if change_params[:project_category_id].present? category = ProjectCategory.find_by_id(change_params[:project_category_id][1]) - content.sub!('{ifcategory}', '') + if change_count > 1 + content.sub!('{ifcategory}', '
    ') + else + content.sub!('{ifcategory}', '') + end content.sub!('{endcategory}', '') content.gsub!('{category}', category&.name) else @@ -48,7 +61,11 @@ class MessageTemplate::ProjectSettingChanged < MessageTemplate # 项目语言更改 if change_params[:project_language_id].present? language = ProjectLanguage.find_by_id(change_params[:project_language_id][1]) - content.sub!('{iflanguage}', '') + if change_count > 1 + content.sub!('{iflanguage}', '
    ') + else + content.sub!('{iflanguage}', '') + end content.sub!('{endlanguage}', '') content.gsub!('{language}', language&.name) else @@ -57,7 +74,11 @@ class MessageTemplate::ProjectSettingChanged < MessageTemplate # 项目公私有更改 if change_params[:is_public].present? permission = change_params[:is_public][1] ? '公有' : '私有' - content.sub!('{ifpermission}', '') + if change_count > 1 + content.sub!('{ifpermission}', '
    ') + else + content.sub!('{ifpermission}', '') + end content.sub!('{endpermission}', '') content.gsub!('{permission}', permission) else @@ -73,16 +94,20 @@ class MessageTemplate::ProjectSettingChanged < MessageTemplate navbar.gsub!('devops', '工作流') navbar.gsub!('versions', '里程碑') navbar.gsub!('resources', '资源库') - content.sub!('{ifnavbar}', '') + if change_count > 1 + content.sub!('{ifnavbar}', '
    ') + else + content.sub!('{ifnavbar}', '') + end content.sub!('{endnavbar}', '') content.gsub!('{navbar}', navbar) else content.gsub!(/({ifnavbar})(.*)({endnavbar})/, '') end - return receivers_string(receivers.where.not(id: operator.id)), content, url - # rescue => e - # Rails.logger.info("MessageTemplate::ProjectSettingChanged.get_message_content [ERROR] #{e}") - # return '', '', '' + return receivers_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectSettingChanged.get_message_content [ERROR] #{e}") + return '', '', '' end end diff --git a/app/models/message_template/pull_request_assigned.rb b/app/models/message_template/pull_request_assigned.rb index 132a3615..5b3e6538 100644 --- a/app/models/message_template/pull_request_assigned.rb +++ b/app/models/message_template/pull_request_assigned.rb @@ -18,7 +18,7 @@ class MessageTemplate::PullRequestAssigned < MessageTemplate def self.get_message_content(receivers, operator, pull_request) project = pull_request&.project owner = project&.owner - content = sys_notice.gsub('{nickname1}', operator&.nickname).gsub('{nickname2}', owner&.nickname).gsub('{repository}', project&.name).gsub('{title}', pull_request&.title) + content = sys_notice.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub('{title}', pull_request&.title) url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', pull_request&.id.to_s) return receivers_string(receivers), content, url rescue => e diff --git a/app/models/message_template/pull_request_atme.rb b/app/models/message_template/pull_request_atme.rb index d940b235..b9764e2b 100644 --- a/app/models/message_template/pull_request_atme.rb +++ b/app/models/message_template/pull_request_atme.rb @@ -17,7 +17,7 @@ class MessageTemplate::PullRequestAtme < MessageTemplate def self.get_message_content(receivers, operator, pull_request) project = pull_request&.project owner = project&.owner - content = sys_notice.gsub('{nickname}', operator&.nickname).gsub('{title}', pull_request&.title) + content = sys_notice.gsub('{nickname}', operator&.real_name).gsub('{title}', pull_request&.title) url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', pull_request&.id.to_s) return receivers_string(receivers), content, url rescue => e diff --git a/app/models/message_template/pull_request_changed.rb b/app/models/message_template/pull_request_changed.rb index 6107a969..1f34f2d0 100644 --- a/app/models/message_template/pull_request_changed.rb +++ b/app/models/message_template/pull_request_changed.rb @@ -20,16 +20,21 @@ class MessageTemplate::PullRequestChanged < MessageTemplate project = pull_request&.project owner = project&.owner issue = pull_request&.issue - content = sys_notice.gsub('{nickname1}', operator&.nickname).gsub('{nickname2}', owner&.nickname).gsub('{repository}', project&.name).gsub("{title}", pull_request&.title) + content = sys_notice.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub("{title}", pull_request&.title) url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', pull_request&.id.to_s) + change_count = change_params.keys.size # 合并请求审查成员修改 if change_params[:assigned_to_id].present? assigner1 = User.find_by_id(change_params[:assigned_to_id][0]) assigner2 = User.find_by_id(change_params[:assigned_to_id][1]) - content.sub!('{ifassigner}', '') + if change_count > 1 + content.sub!('{ifassigner}', '
    ') + else + content.sub!('{ifassigner}', '') + end content.sub!('{endassigner}', '') - content.gsub!('{assigner1}', assigner1.present? ? assigner1&.nickname || assigner1.login : '未指派成员') - content.gsub!('{assigner2}', assigner2.present? ? assigner2&.nickname || assigner2.login : '未指派成员') + content.gsub!('{assigner1}', assigner1.present? ? assigner1&.real_name : '未指派成员') + content.gsub!('{assigner2}', assigner2.present? ? assigner2&.real_name : '未指派成员') else content.gsub!(/({ifassigner})(.*)({endassigner})/, '') end @@ -37,7 +42,11 @@ class MessageTemplate::PullRequestChanged < MessageTemplate if change_params[:fixed_version_id].present? fix_version1 = Version.find_by_id(change_params[:fixed_version_id][0]) fix_version2 = Version.find_by_id(change_params[:fixed_version_id][1]) - content.sub!('{ifmilestone}', '') + if change_count > 1 + content.sub!('{ifmilestone}', '
    ') + else + content.sub!('{ifmilestone}', '') + end content.sub!('{endmilestone}', '') content.gsub!('{milestone1}', fix_version1.present? ? fix_version1&.name : '未选择里程碑') content.gsub!('{milestone2}', fix_version2.present? ? fix_version2&.name : '未选择里程碑') @@ -50,7 +59,11 @@ class MessageTemplate::PullRequestChanged < MessageTemplate issue_tags2 = IssueTag.where(id: change_params[:issue_tags_value][1]).distinct tag1 = issue_tags1.pluck(:name).join(",").blank? ? '未选择标签' : issue_tags1.pluck(:name).join(",") tag2 = issue_tags2.pluck(:name).join(",").blank? ? '未选择标签' : issue_tags2.pluck(:name).join(",") - content.sub!('{iftag}', '') + if change_count > 1 + content.sub!('{iftag}', '
    ') + else + content.sub!('{iftag}', '') + end content.sub!('{endtag}', '') content.gsub!('{tag1}', tag1) content.gsub!('{tag2}', tag2) @@ -61,6 +74,11 @@ class MessageTemplate::PullRequestChanged < MessageTemplate if change_params[:priority_id].present? priority1 = IssuePriority.find_by_id(change_params[:priority_id][0]) priority2 = IssuePriority.find_by_id(change_params[:priority_id][1]) + if change_count > 1 + content.sub!('{ifpriority}', '
    ') + else + content.sub!('{ifpriority}', '') + end content.sub!('{ifpriority}', '') content.sub!('{endpriority}', '') content.gsub!('{priority1}', priority1&.name) diff --git a/app/services/projects/accept_join_service.rb b/app/services/projects/accept_join_service.rb index 69cb9760..b1a996fd 100644 --- a/app/services/projects/accept_join_service.rb +++ b/app/services/projects/accept_join_service.rb @@ -53,6 +53,8 @@ class Projects::AcceptJoinService < ApplicationService def operate_project_member Projects::AddMemberInteractor.call(@project.owner, @project, @applied_project.user, permission) + SendTemplateMessageJob.perform_later('ProjectJoined', @user.id, @applied_project.user_id, @project.id) + SendTemplateMessageJob.perform_later('ProjectMemberJoined', @user.id, @applied_project.user_id, @project.id) end def send_apply_message From a1679cfc53c3ddcdca9c296e28effcdec23abbd4 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 16 Sep 2021 17:29:07 +0800 Subject: [PATCH 035/135] fix some template and add copy issue message --- app/controllers/issues_controller.rb | 2 ++ app/models/message_template.rb | 6 +++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/app/controllers/issues_controller.rb b/app/controllers/issues_controller.rb index 208e68a4..118e8010 100644 --- a/app/controllers/issues_controller.rb +++ b/app/controllers/issues_controller.rb @@ -353,6 +353,8 @@ class IssuesController < ApplicationController @new_issue = @issue.dup @new_issue.author_id = current_user.id if @new_issue.save + SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @new_issue&.id) + SendTemplateMessageJob.perform_later('ProjectIssue', current_user.id, @new_issue&.id) issue_tags = @issue.issue_tags.pluck(:id) if issue_tags.present? issue_tags.each do |tag| diff --git a/app/models/message_template.rb b/app/models/message_template.rb index 42aa64a4..593369c5 100644 --- a/app/models/message_template.rb +++ b/app/models/message_template.rb @@ -18,7 +18,7 @@ class MessageTemplate {nickname2}/{repository}
    指派给你一个易修:{title}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') self.create(type: 'MessageTemplate::IssueAssignerExpire', sys_notice: '您负责的易修{title}已临近截止日期,请尽快处理', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') self.create(type: 'MessageTemplate::IssueAtme', sys_notice: '{nickname}在易修{title}中@我', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') - self.create(type: 'MessageTemplate::IssueChanged', sys_notice: '在项目{nickname2}/{repository}的易修{title}中:{ifassigner}{nickname1}将负责人从{assigner1}修改为{assigner2}{endassigner}{ifstatus}{nickname1}将状态从{status1}修改为{status2}{endstatus}{iftracker}{nickname1}将类型从{tracker1}修改为{tracker2}{endtracker}{ifpriority}{nickname1}将优先级从{priority1}修改为{priority2}{endpriority}{ifmilestone}{nickname1}将里程碑从{milestone1}修改为{milestone2}{endmilestone}{iftag}{nickname1}将标签从{tag1}修改为{tag2}{endtag}{ifdoneratio}{nickname1}将完成度从{doneratio1}修改为{doneratio2}{enddoneratio}{ifbranch}{nickname1}将指定分支从{branch1}修改为{branch2}{endbranch}{ifstartdate}{nickname1}将开始日期从{startdate1}修改为{startdate2}{endstartdate}{ifduedate}{nickname1}将结束日期从{duedate1}修改为{duedate2}{endduedate}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') + self.create(type: 'MessageTemplate::IssueChanged', sys_notice: '在项目{nickname2}/{repository}的易修{title}中:{ifassigner}{nickname1}将负责人从{assigner1}修改为{assigner2}{endassigner}{ifstatus}{nickname1}将状态从{status1}修改为{status2}{endstatus}{iftracker}{nickname1}将类型从{tracker1}修改为{tracker2}{endtracker}{ifpriority}{nickname1}将优先级从{priority1}修改为{priority2}{endpriority}{ifmilestone}{nickname1}将里程碑从{milestone1}修改为{milestone2}{endmilestone}{iftag}{nickname1}将标记从{tag1}修改为{tag2}{endtag}{ifdoneratio}{nickname1}将完成度从{doneratio1}修改为{doneratio2}{enddoneratio}{ifbranch}{nickname1}将指定分支从{branch1}修改为{branch2}{endbranch}{ifstartdate}{nickname1}将开始日期从{startdate1}修改为{startdate2}{endstartdate}{ifduedate}{nickname1}将结束日期从{duedate1}修改为{duedate2}{endduedate}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') self.create(type: 'MessageTemplate::IssueCreatorExpire', sys_notice: '您发布的易修{title}已临近截止日期,请尽快处理', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') self.create(type: 'MessageTemplate::IssueDeleted', sys_notice: '{nickname}已将易修{title}删除', notification_url: '') self.create(type: 'MessageTemplate::IssueJournal', sys_notice: '{nickname}评论易修{title}:{notes}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') @@ -38,12 +38,12 @@ class MessageTemplate {nickname}点赞了你管理的仓库', notification_url: '{baseurl}/{login}') self.create(type: 'MessageTemplate::ProjectPullRequest', sys_notice: '{nickname1}在{nickname2}/{repository}提交了一个合并请求:{title}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') self.create(type: 'MessageTemplate::ProjectRole', sys_notice: '仓库{repository}已把你的角色改为{role}', notification_url: '{baseurl}/{owner}/{identifier}') - self.create(type: 'MessageTemplate::ProjectSettingChanged', sys_notice: '{nickname1}更改了{nickname2}/{repository}仓库设置:{ifname}更改项目名称为"{name}"{endname}{ifdescription}更改项目简介为"{description}"{enddescription}{ifcategory}更改项目类别为"{category}"{endcategory}{iflanguage}更改项目语言为"{language}"{endlanguage}{ifpermission}将仓库设为"{permission}"{endpermission}{ifnavbar}将项目导航更改为"{navbar}"{endnavbar}', notification_url: '{baseurl}/{owner}/{identifier}/settings') + self.create(type: 'MessageTemplate::ProjectSettingChanged', sys_notice: '{nickname1}更改了{nickname2}/{repository}仓库设置:{ifname}更改项目名称为"{name}"{endname}{ifdescription}更改项目简介为"{description}"{enddescription}{ifcategory}更改项目类别为"{category}"{endcategory}{iflanguage}更改项目语言为"{language}"{endlanguage}{ifpermission}将仓库设为"{permission}"{endpermission}{ifnavbar}将项目导航更改为"{navbar}"{endnavbar}', notification_url: '{baseurl}/{owner}/{identifier}/settings') self.create(type: 'MessageTemplate::ProjectTransfer', sys_notice: '你关注的仓库{nickname1}/{repository1}已被转移至{nickname2}/{repository2}', notification_url: '{baseurl}/{owner}/{identifier}') self.create(type: 'MessageTemplate::ProjectVersion', sys_notice: '{nickname1}在{nickname2}/{repository}创建了发行版:{title}', notification_url: '{baseurl}/{owner}/{identifier}/releases') self.create(type: 'MessageTemplate::PullRequestAssigned', sys_notice: '{nickname1}在{nickname2}/{repository}指派给你一个合并请求:{title}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') self.create(type: 'MessageTemplate::PullRequestAtme', sys_notice: '{nickname}在合并请求{title}中@我', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') - self.create(type: 'MessageTemplate::PullRequestChanged', sys_notice: '在项目{nickname2}/{repository}的合并请求{title}中:{ifassigner}{nickname1}将审查成员从{assigner1}修改为{assigner2}{endassigner}{ifmilestone}{nickname1}将里程碑从{milestone1}修改为{milestone2}{endmilestone}{iftag}{nickname1}将标签从{tag1}修改为{tag2}{endtag}{ifpriority}{nickname1}将优先级从{priority1}修改为{priority2}{endpriority}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') + self.create(type: 'MessageTemplate::PullRequestChanged', sys_notice: '在项目{nickname2}/{repository}的合并请求{title}中:{ifassigner}{nickname1}将审查成员从{assigner1}修改为{assigner2}{endassigner}{ifmilestone}{nickname1}将里程碑从{milestone1}修改为{milestone2}{endmilestone}{iftag}{nickname1}将标记从{tag1}修改为{tag2}{endtag}{ifpriority}{nickname1}将优先级从{priority1}修改为{priority2}{endpriority}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') self.create(type: 'MessageTemplate::PullRequestClosed', sys_notice: '你提交的合并请求:{title}被拒绝', notification_url: '') self.create(type: 'MessageTemplate::PullRequestJournal', sys_notice: '{nickname}评论合并请求{title}:{notes}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') self.create(type: 'MessageTemplate::PullRequestMerged', sys_notice: '你提交的合并请求:{title}被合并', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') From 41d04e9e9947bb650ddff051761031cc1304fafc Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 16 Sep 2021 18:39:19 +0800 Subject: [PATCH 036/135] =?UTF-8?q?fix:=20=E6=A0=87=E7=AD=BE=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E6=A0=87=E8=AE=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controllers/issues_controller.rb | 1 + app/controllers/pull_requests_controller.rb | 3 ++- config/locales/zh-CN.yml | 4 ++-- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/app/controllers/issues_controller.rb b/app/controllers/issues_controller.rb index 266d746d..bbde2ecb 100644 --- a/app/controllers/issues_controller.rb +++ b/app/controllers/issues_controller.rb @@ -158,6 +158,7 @@ class IssuesController < ApplicationController def update last_token = @issue.token last_status_id = @issue.status_id + @issue&.issue_tags_relates&.destroy_all if params[:issue_tag_ids].blank? if params[:issue_tag_ids].present? && !@issue&.issue_tags_relates.where(issue_tag_id: params[:issue_tag_ids]).exists? @issue&.issue_tags_relates&.destroy_all params[:issue_tag_ids].each do |tag| diff --git a/app/controllers/pull_requests_controller.rb b/app/controllers/pull_requests_controller.rb index 79221a66..7950d343 100644 --- a/app/controllers/pull_requests_controller.rb +++ b/app/controllers/pull_requests_controller.rb @@ -77,12 +77,13 @@ class PullRequestsController < ApplicationController if params[:title].nil? normal_status(-1, "名称不能为空") elsif params[:issue_tag_ids].nil? - normal_status(-1, "标签不能为空") + normal_status(-1, "标记不能为空") else ActiveRecord::Base.transaction do begin merge_params + @issue&.issue_tags_relates&.destroy_all if params[:issue_tag_ids].blank? if params[:issue_tag_ids].present? && !@issue&.issue_tags_relates.where(issue_tag_id: params[:issue_tag_ids]).exists? @issue&.issue_tags_relates&.destroy_all params[:issue_tag_ids].each do |tag| diff --git a/config/locales/zh-CN.yml b/config/locales/zh-CN.yml index db103016..f6f47862 100644 --- a/config/locales/zh-CN.yml +++ b/config/locales/zh-CN.yml @@ -31,7 +31,7 @@ zh-CN: branch_name: 分支 close_pr: 合并 merge: 合并 - issue_tags_value: 标签 + issue_tags_value: 标记 lock_issue: 锁定工单 unlock_issue: 解锁工单 destroy_issue_depend: 删除依赖 @@ -55,7 +55,7 @@ zh-CN: f: 否 true: 是 false: 否 - issue_tag_ids: 标签 + issue_tag_ids: 标记 issue_type: 分类 token: 悬赏金额 close_issue: 工单 From a5861ce1d69e9e1306c157463dd91ca9ff4e749a Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 17 Sep 2021 09:38:31 +0800 Subject: [PATCH 037/135] =?UTF-8?q?fix:=20=E9=A1=B9=E7=9B=AE=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E7=AE=80=E4=BB=8B=E3=80=81=E8=AF=AD=E8=A8=80=E3=80=81?= =?UTF-8?q?=E5=88=86=E7=B1=BB=E5=8F=AF=E4=BB=A5=E4=B8=BA=E7=A9=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/forms/base_form.rb | 4 ++-- app/forms/projects/update_form.rb | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/forms/base_form.rb b/app/forms/base_form.rb index c41a1299..c5776048 100644 --- a/app/forms/base_form.rb +++ b/app/forms/base_form.rb @@ -2,11 +2,11 @@ class BaseForm include ActiveModel::Model def check_project_category(project_category_id) - raise "project_category_id参数值无效." if project_category_id && !ProjectCategory.exists?(project_category_id) + raise "project_category_id参数值无效." unless project_category_id == '' && (project_category_id && !ProjectCategory.exists?(project_category_id)) end def check_project_language(project_language_id) - raise "project_language_id参数值无效." if project_language_id && !ProjectLanguage.exists?(project_language_id) + raise "project_language_id参数值无效." unless project_language_id == '' && (project_language_id && !ProjectLanguage.exists?(project_language_id)) end def check_repository_name(user_id, repository_name) diff --git a/app/forms/projects/update_form.rb b/app/forms/projects/update_form.rb index 65810a82..0cd2c945 100644 --- a/app/forms/projects/update_form.rb +++ b/app/forms/projects/update_form.rb @@ -1,6 +1,6 @@ class Projects::UpdateForm < BaseForm attr_accessor :name, :description, :project_category_id, :project_language_id, :private - validates :name, :description, :project_category_id, :project_language_id, presence: true + validates :name, presence: true validates :name, length: { maximum: 50 } validates :description, length: { maximum: 200 } validate do From 08de4819d73fda835dae5600b015529fd0d9069b Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 17 Sep 2021 09:44:17 +0800 Subject: [PATCH 038/135] fix: bold messsage some content --- app/models/message_template.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/models/message_template.rb b/app/models/message_template.rb index 593369c5..a69c839d 100644 --- a/app/models/message_template.rb +++ b/app/models/message_template.rb @@ -18,7 +18,7 @@ class MessageTemplate {nickname2}/{repository}指派给你一个易修:{title}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') self.create(type: 'MessageTemplate::IssueAssignerExpire', sys_notice: '您负责的易修{title}已临近截止日期,请尽快处理', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') self.create(type: 'MessageTemplate::IssueAtme', sys_notice: '{nickname}在易修{title}中@我', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') - self.create(type: 'MessageTemplate::IssueChanged', sys_notice: '在项目{nickname2}/{repository}的易修{title}中:{ifassigner}{nickname1}将负责人从{assigner1}修改为{assigner2}{endassigner}{ifstatus}{nickname1}将状态从{status1}修改为{status2}{endstatus}{iftracker}{nickname1}将类型从{tracker1}修改为{tracker2}{endtracker}{ifpriority}{nickname1}将优先级从{priority1}修改为{priority2}{endpriority}{ifmilestone}{nickname1}将里程碑从{milestone1}修改为{milestone2}{endmilestone}{iftag}{nickname1}将标记从{tag1}修改为{tag2}{endtag}{ifdoneratio}{nickname1}将完成度从{doneratio1}修改为{doneratio2}{enddoneratio}{ifbranch}{nickname1}将指定分支从{branch1}修改为{branch2}{endbranch}{ifstartdate}{nickname1}将开始日期从{startdate1}修改为{startdate2}{endstartdate}{ifduedate}{nickname1}将结束日期从{duedate1}修改为{duedate2}{endduedate}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') + self.create(type: 'MessageTemplate::IssueChanged', sys_notice: '在项目{nickname2}/{repository}的易修{title}中:{ifassigner}{nickname1}将负责人从{assigner1}修改为{assigner2}{endassigner}{ifstatus}{nickname1}将状态从{status1}修改为{status2}{endstatus}{iftracker}{nickname1}将类型从{tracker1}修改为{tracker2}{endtracker}{ifpriority}{nickname1}将优先级从{priority1}修改为{priority2}{endpriority}{ifmilestone}{nickname1}将里程碑从{milestone1}修改为{milestone2}{endmilestone}{iftag}{nickname1}将标记从{tag1}修改为{tag2}{endtag}{ifdoneratio}{nickname1}将完成度从{doneratio1}修改为{doneratio2}{enddoneratio}{ifbranch}{nickname1}将指定分支从{branch1}修改为{branch2}{endbranch}{ifstartdate}{nickname1}将开始日期从{startdate1}修改为{startdate2}{endstartdate}{ifduedate}{nickname1}将结束日期从{duedate1}修改为{duedate2}{endduedate}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') self.create(type: 'MessageTemplate::IssueCreatorExpire', sys_notice: '您发布的易修{title}已临近截止日期,请尽快处理', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') self.create(type: 'MessageTemplate::IssueDeleted', sys_notice: '{nickname}已将易修{title}删除', notification_url: '') self.create(type: 'MessageTemplate::IssueJournal', sys_notice: '{nickname}评论易修{title}:{notes}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') From 76268c4952a03a4c0424261703ad06ec2f2b1534 Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 17 Sep 2021 10:02:42 +0800 Subject: [PATCH 039/135] fix --- app/forms/base_form.rb | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/app/forms/base_form.rb b/app/forms/base_form.rb index c5776048..71eaee17 100644 --- a/app/forms/base_form.rb +++ b/app/forms/base_form.rb @@ -2,11 +2,15 @@ class BaseForm include ActiveModel::Model def check_project_category(project_category_id) - raise "project_category_id参数值无效." unless project_category_id == '' && (project_category_id && !ProjectCategory.exists?(project_category_id)) + unless project_category_id == '' + raise "project_category_id参数值无效." if project_category_id && !ProjectCategory.exists?(project_category_id) + end end def check_project_language(project_language_id) - raise "project_language_id参数值无效." unless project_language_id == '' && (project_language_id && !ProjectLanguage.exists?(project_language_id)) + unless project_language_id == '' + raise "project_language_id参数值无效." if project_language_id && !ProjectLanguage.exists?(project_language_id) + end end def check_repository_name(user_id, repository_name) From 228becfe079e70d43ea8dc63875058ed592b7d8e Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 17 Sep 2021 10:37:49 +0800 Subject: [PATCH 040/135] fix: some content for messages --- app/models/message_template.rb | 4 ++-- app/models/team.rb | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/models/message_template.rb b/app/models/message_template.rb index a69c839d..db412920 100644 --- a/app/models/message_template.rb +++ b/app/models/message_template.rb @@ -25,7 +25,7 @@ class MessageTemplate {organization}组织', notification_url: '{baseurl}/{login}') self.create(type: 'MessageTemplate::OrganizationLeft', sys_notice: '你已被移出{organization}组织', notification_url: '') - self.create(type: 'MessageTemplate::OrganizationRole', sys_notice: '组织{organization}已把你的角色改为{role}', notification_url: '{baseurl}/{login}') + self.create(type: 'MessageTemplate::OrganizationRole', sys_notice: '组织{organization}已把你的角色改为{role}', notification_url: '{baseurl}/{login}') self.create(type: 'MessageTemplate::ProjectDeleted', sys_notice: '你关注的仓库{nickname}/{repository}已被删除', notification_url: '') self.create(type: 'MessageTemplate::ProjectFollowed', sys_notice: '{nickname}关注了你管理的仓库', notification_url: '{baseurl}/{login}') self.create(type: 'MessageTemplate::ProjectForked', sys_notice: '{nickname1}复刻了你管理的仓库{nickname1}/{repository1}到{nickname2}/{repository2}', notification_url: '{baseurl}/{owner}/{identifier}') @@ -37,7 +37,7 @@ class MessageTemplate {nickname2}/{repository}创建了一个里程碑:{title}', notification_url: '{baseurl}/{owner}/{identifier}/milestones/{id}') self.create(type: 'MessageTemplate::ProjectPraised', sys_notice: '{nickname}点赞了你管理的仓库', notification_url: '{baseurl}/{login}') self.create(type: 'MessageTemplate::ProjectPullRequest', sys_notice: '{nickname1}在{nickname2}/{repository}提交了一个合并请求:{title}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') - self.create(type: 'MessageTemplate::ProjectRole', sys_notice: '仓库{repository}已把你的角色改为{role}', notification_url: '{baseurl}/{owner}/{identifier}') + self.create(type: 'MessageTemplate::ProjectRole', sys_notice: '仓库{repository}已把你的角色改为{role}', notification_url: '{baseurl}/{owner}/{identifier}') self.create(type: 'MessageTemplate::ProjectSettingChanged', sys_notice: '{nickname1}更改了{nickname2}/{repository}仓库设置:{ifname}更改项目名称为"{name}"{endname}{ifdescription}更改项目简介为"{description}"{enddescription}{ifcategory}更改项目类别为"{category}"{endcategory}{iflanguage}更改项目语言为"{language}"{endlanguage}{ifpermission}将仓库设为"{permission}"{endpermission}{ifnavbar}将项目导航更改为"{navbar}"{endnavbar}', notification_url: '{baseurl}/{owner}/{identifier}/settings') self.create(type: 'MessageTemplate::ProjectTransfer', sys_notice: '你关注的仓库{nickname1}/{repository1}已被转移至{nickname2}/{repository2}', notification_url: '{baseurl}/{owner}/{identifier}') self.create(type: 'MessageTemplate::ProjectVersion', sys_notice: '{nickname1}在{nickname2}/{repository}创建了发行版:{title}', notification_url: '{baseurl}/{owner}/{identifier}/releases') diff --git a/app/models/team.rb b/app/models/team.rb index 481e8c34..19d05c77 100644 --- a/app/models/team.rb +++ b/app/models/team.rb @@ -59,7 +59,7 @@ class Team < ApplicationRecord when 'read' then '报告者' when 'write' then '开发者' when 'admin' then '管理员' - when 'owner' then '管理员' + when 'owner' then '拥有者' else '' end From 18b0c760827cf4292c865c1cef0d97933239a9d9 Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 17 Sep 2021 14:15:38 +0800 Subject: [PATCH 041/135] fix --- app/controllers/pull_requests_controller.rb | 4 +- app/jobs/send_template_message_job.rb | 10 ++-- app/models/message_template.rb | 2 +- .../project_setting_changed.rb | 56 +++++++++++++------ 4 files changed, 49 insertions(+), 23 deletions(-) diff --git a/app/controllers/pull_requests_controller.rb b/app/controllers/pull_requests_controller.rb index fe1edab5..c48e12a8 100644 --- a/app/controllers/pull_requests_controller.rb +++ b/app/controllers/pull_requests_controller.rb @@ -93,8 +93,6 @@ class PullRequestsController < ApplicationController end if @issue.update_attributes(@issue_params) - SendTemplateMessageJob.perform_later('PullRequestChanged', current_user.id, @pull_request&.id, @issue.previous_changes.slice(:assigned_to_id, :priority_id, :fixed_version_id, :issue_tags_value)) - SendTemplateMessageJob.perform_later('PullRequestAssigned', current_user.id, @pull_request&.id ) if @issue.previous_changes[:assigned_to_id].present? if @pull_request.update_attributes(@local_params.compact) gitea_pull = Gitea::PullRequest::UpdateService.call(@owner.login, @repository.identifier, @pull_request.gitea_number, @requests_params, current_user.gitea_token) @@ -120,6 +118,8 @@ class PullRequestsController < ApplicationController normal_status(-1, e.message) raise ActiveRecord::Rollback end + SendTemplateMessageJob.perform_later('PullRequestChanged', current_user.id, @pull_request&.id, @issue.previous_changes.slice(:assigned_to_id, :priority_id, :fixed_version_id, :issue_tags_value)) + SendTemplateMessageJob.perform_later('PullRequestAssigned', current_user.id, @pull_request&.id ) if @issue.previous_changes[:assigned_to_id].present? end end diff --git a/app/jobs/send_template_message_job.rb b/app/jobs/send_template_message_job.rb index d3593806..ac5e956a 100644 --- a/app/jobs/send_template_message_job.rb +++ b/app/jobs/send_template_message_job.rb @@ -156,8 +156,9 @@ class SendTemplateMessageJob < ApplicationJob operator_id, pull_request_id = args[0], args[1] operator = User.find_by_id(operator_id) pull_request = PullRequest.find_by_id(pull_request_id) - return unless operator.present? && pull_request.present? - receivers = User.where(id: pull_request&.issue&.assigned_to_id).where.not(id: operator&.id) + issue = Issue.find_by_id(pull_request&.issue_id) + return unless operator.present? && pull_request.present? && issue.present? + receivers = User.where(id: issue&.assigned_to_id).where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::PullRequestAssigned.get_message_content(receivers, operator, pull_request) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, pull_request_id: pull_request.id}) when 'PullRequestAtme' @@ -172,8 +173,9 @@ class SendTemplateMessageJob < ApplicationJob operator_id, pull_request_id, change_params = args[0], args[1], args[2] operator = User.find_by_id(operator_id) pull_request = PullRequest.find_by_id(pull_request_id) - return unless operator.present? && pull_request.present? - receivers = User.where(id: [pull_request&.issue&.assigned_to_id, pull_request&.user_id]).where.not(id: operator&.id) + issue = Issue.find_by_id(pull_request&.issue_id) + return unless operator.present? && pull_request.present? && issue.present? + receivers = User.where(id: [issue&.assigned_to_id, pull_request&.user_id]).where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::PullRequestChanged.get_message_content(receivers, operator, pull_request, change_params.symbolize_keys) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, pull_request_id: pull_request.id, change_params: change_params}) when 'PullRequestClosed' diff --git a/app/models/message_template.rb b/app/models/message_template.rb index db412920..6a3aebf6 100644 --- a/app/models/message_template.rb +++ b/app/models/message_template.rb @@ -46,7 +46,7 @@ class MessageTemplate {title}中:{ifassigner}{nickname1}将审查成员从{assigner1}修改为{assigner2}{endassigner}{ifmilestone}{nickname1}将里程碑从{milestone1}修改为{milestone2}{endmilestone}{iftag}{nickname1}将标记从{tag1}修改为{tag2}{endtag}{ifpriority}{nickname1}将优先级从{priority1}修改为{priority2}{endpriority}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') self.create(type: 'MessageTemplate::PullRequestClosed', sys_notice: '你提交的合并请求:{title}被拒绝', notification_url: '') self.create(type: 'MessageTemplate::PullRequestJournal', sys_notice: '{nickname}评论合并请求{title}:{notes}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') - self.create(type: 'MessageTemplate::PullRequestMerged', sys_notice: '你提交的合并请求:{title}被合并', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') + self.create(type: 'MessageTemplate::PullRequestMerged', sys_notice: '你提交的合并请求:{title}已通过', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') end def self.sys_notice diff --git a/app/models/message_template/project_setting_changed.rb b/app/models/message_template/project_setting_changed.rb index f973f99d..9510fa58 100644 --- a/app/models/message_template/project_setting_changed.rb +++ b/app/models/message_template/project_setting_changed.rb @@ -35,39 +35,63 @@ class MessageTemplate::ProjectSettingChanged < MessageTemplate end # 项目简介更改 if change_params[:description].present? - if change_count > 1 - content.sub!('{ifdescription}', '
    ') + if change_params[:description][1].blank? + if change_count > 1 + content.gsub!(/({ifdescription})(.*)({enddescription})/, '
    删除了项目简介') + else + content.gsub!(/({ifdescription})(.*)({enddescription})/, '删除了项目简介') + end else - content.sub!('{ifdescription}', '') + if change_count > 1 + content.sub!('{ifdescription}', '
    ') + else + content.sub!('{ifdescription}', '') + end + content.sub!('{enddescription}', '') + content.gsub!('{description}', change_params[:description][1]) end - content.sub!('{enddescription}', '') - content.gsub!('{description}', change_params[:description][1]) else content.gsub!(/({ifdescription})(.*)({enddescription})/, '') end # 项目类别更改 if change_params[:project_category_id].present? category = ProjectCategory.find_by_id(change_params[:project_category_id][1]) - if change_count > 1 - content.sub!('{ifcategory}', '
    ') - else - content.sub!('{ifcategory}', '') + if category.present? + if change_count > 1 + content.sub!('{ifcategory}', '
    ') + else + content.sub!('{ifcategory}', '') + end + content.sub!('{endcategory}', '') + content.gsub!('{category}', category&.name) + else + if change_count > 1 + content.gsub!(/({ifcategory})(.*)({endcategory})/, '
    删除了项目类别') + else + content.gsub!(/({ifcategory})(.*)({endcategory})/, '删除了项目类别') + end end - content.sub!('{endcategory}', '') - content.gsub!('{category}', category&.name) else content.gsub!(/({ifcategory})(.*)({endcategory})/, '') end # 项目语言更改 if change_params[:project_language_id].present? language = ProjectLanguage.find_by_id(change_params[:project_language_id][1]) - if change_count > 1 - content.sub!('{iflanguage}', '
    ') + if language.present? + if change_count > 1 + content.sub!('{iflanguage}', '
    ') + else + content.sub!('{iflanguage}', '') + end + content.sub!('{endlanguage}', '') + content.gsub!('{language}', language&.name) else - content.sub!('{iflanguage}', '') + if change_count > 1 + content.gsub!(/({iflanguage})(.*)({endlanguage})/, '
    删除了项目语言') + else + content.gsub!(/({iflanguage})(.*)({endlanguage})/, '删除了项目语言') + end end - content.sub!('{endlanguage}', '') - content.gsub!('{language}', language&.name) else content.gsub!(/({iflanguage})(.*)({endlanguage})/, '') end From 9a7a5ca3a1cb12bded7af608cf1bcdec017bd578 Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 17 Sep 2021 14:48:00 +0800 Subject: [PATCH 042/135] fix: message content add space --- app/models/message_template.rb | 52 +++++++++---------- app/models/message_template/issue_changed.rb | 9 ++-- .../message_template/pull_request_changed.rb | 6 +-- 3 files changed, 34 insertions(+), 33 deletions(-) diff --git a/app/models/message_template.rb b/app/models/message_template.rb index 6a3aebf6..df4ed782 100644 --- a/app/models/message_template.rb +++ b/app/models/message_template.rb @@ -14,36 +14,36 @@ class MessageTemplate {nickname}关注了你', notification_url: '{baseurl}/{login}') - self.create(type: 'MessageTemplate::IssueAssigned', sys_notice: '{nickname1}在{nickname2}/{repository}指派给你一个易修:{title}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') - self.create(type: 'MessageTemplate::IssueAssignerExpire', sys_notice: '您负责的易修{title}已临近截止日期,请尽快处理', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') - self.create(type: 'MessageTemplate::IssueAtme', sys_notice: '{nickname}在易修{title}中@我', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') - self.create(type: 'MessageTemplate::IssueChanged', sys_notice: '在项目{nickname2}/{repository}的易修{title}中:{ifassigner}{nickname1}将负责人从{assigner1}修改为{assigner2}{endassigner}{ifstatus}{nickname1}将状态从{status1}修改为{status2}{endstatus}{iftracker}{nickname1}将类型从{tracker1}修改为{tracker2}{endtracker}{ifpriority}{nickname1}将优先级从{priority1}修改为{priority2}{endpriority}{ifmilestone}{nickname1}将里程碑从{milestone1}修改为{milestone2}{endmilestone}{iftag}{nickname1}将标记从{tag1}修改为{tag2}{endtag}{ifdoneratio}{nickname1}将完成度从{doneratio1}修改为{doneratio2}{enddoneratio}{ifbranch}{nickname1}将指定分支从{branch1}修改为{branch2}{endbranch}{ifstartdate}{nickname1}将开始日期从{startdate1}修改为{startdate2}{endstartdate}{ifduedate}{nickname1}将结束日期从{duedate1}修改为{duedate2}{endduedate}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') - self.create(type: 'MessageTemplate::IssueCreatorExpire', sys_notice: '您发布的易修{title}已临近截止日期,请尽快处理', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') - self.create(type: 'MessageTemplate::IssueDeleted', sys_notice: '{nickname}已将易修{title}删除', notification_url: '') + self.create(type: 'MessageTemplate::FollowedTip', sys_notice: '{nickname} 关注了你', notification_url: '{baseurl}/{login}') + self.create(type: 'MessageTemplate::IssueAssigned', sys_notice: '{nickname1}在 {nickname2}/{repository} 指派给你一个易修:{title}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') + self.create(type: 'MessageTemplate::IssueAssignerExpire', sys_notice: '您负责的易修 {title} 已临近截止日期,请尽快处理', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') + self.create(type: 'MessageTemplate::IssueAtme', sys_notice: '{nickname} 在易修 {title} 中@我', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') + self.create(type: 'MessageTemplate::IssueChanged', sys_notice: '在项目 {nickname2}/{repository} 的易修 {title} 中:{ifassigner}{nickname1}将负责人从 {assigner1} 修改为 {assigner2} {endassigner}{ifstatus}{nickname1}将状态从 {status1} 修改为 {status2} {endstatus}{iftracker}{nickname1}将类型从 {tracker1} 修改为 {tracker2} {endtracker}{ifpriority}{nickname1}将优先级从 {priority1} 修改为 {priority2} {endpriority}{ifmilestone}{nickname1}将里程碑从 {milestone1} 修改为 {milestone2} {endmilestone}{iftag}{nickname1}将标记从 {tag1} 修改为 {tag2} {endtag}{ifdoneratio}{nickname1}将完成度从 {doneratio1} 修改为 {doneratio2} {enddoneratio}{ifbranch}{nickname1}将指定分支从 {branch1} 修改为 {branch2} {endbranch}{ifstartdate}{nickname1}将开始日期从 {startdate1} 修改为 {startdate2} {endstartdate}{ifduedate}{nickname1}将结束日期从 {duedate1} 修改为 {duedate2} {endduedate}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') + self.create(type: 'MessageTemplate::IssueCreatorExpire', sys_notice: '您发布的易修 {title} 已临近截止日期,请尽快处理', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') + self.create(type: 'MessageTemplate::IssueDeleted', sys_notice: '{nickname}已将易修 {title} 删除', notification_url: '') self.create(type: 'MessageTemplate::IssueJournal', sys_notice: '{nickname}评论易修{title}:{notes}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') self.create(type: 'MessageTemplate::LoginIpTip', sys_notice: '您的账号{nickname}于{login_time)在非常用的IP地址{ip}登录,如非本人操作,请立即修改密码', notification_url: '') - self.create(type: 'MessageTemplate::OrganizationJoined', sys_notice: '你已加入{organization}组织', notification_url: '{baseurl}/{login}') - self.create(type: 'MessageTemplate::OrganizationLeft', sys_notice: '你已被移出{organization}组织', notification_url: '') - self.create(type: 'MessageTemplate::OrganizationRole', sys_notice: '组织{organization}已把你的角色改为{role}', notification_url: '{baseurl}/{login}') + self.create(type: 'MessageTemplate::OrganizationJoined', sys_notice: '你已加入 {organization} 组织', notification_url: '{baseurl}/{login}') + self.create(type: 'MessageTemplate::OrganizationLeft', sys_notice: '你已被移出 {organization} 组织', notification_url: '') + self.create(type: 'MessageTemplate::OrganizationRole', sys_notice: '组织 {organization} 已把你的角色改为 {role}', notification_url: '{baseurl}/{login}') self.create(type: 'MessageTemplate::ProjectDeleted', sys_notice: '你关注的仓库{nickname}/{repository}已被删除', notification_url: '') - self.create(type: 'MessageTemplate::ProjectFollowed', sys_notice: '{nickname}关注了你管理的仓库', notification_url: '{baseurl}/{login}') - self.create(type: 'MessageTemplate::ProjectForked', sys_notice: '{nickname1}复刻了你管理的仓库{nickname1}/{repository1}到{nickname2}/{repository2}', notification_url: '{baseurl}/{owner}/{identifier}') - self.create(type: 'MessageTemplate::ProjectIssue', sys_notice: '{nickname1}在{nickname2}/{repository}新建易修:{title}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') - self.create(type: 'MessageTemplate::ProjectJoined', sys_notice: '你已加入{repository}项目', notification_url: '{baseurl}/{owner}/{identifier}') - self.create(type: 'MessageTemplate::ProjectLeft', sys_notice: '你已被移出{repository}项目', notification_url: '') - self.create(type: 'MessageTemplate::ProjectMemberJoined', sys_notice: '{nickname1}已加入项目{nickname2}/{repository}', notification_url: '{baseurl}/{owner}/{identifier}') - self.create(type: 'MessageTemplate::ProjectMemberLeft', sys_notice: '{nickname1}已被移出项目{nickname2}/{repository}', notification_url: '{baseurl}/{owner}/{identifier}') - self.create(type: 'MessageTemplate::ProjectMilestone', sys_notice: '{nickname1}在{nickname2}/{repository}创建了一个里程碑:{title}', notification_url: '{baseurl}/{owner}/{identifier}/milestones/{id}') - self.create(type: 'MessageTemplate::ProjectPraised', sys_notice: '{nickname}点赞了你管理的仓库', notification_url: '{baseurl}/{login}') - self.create(type: 'MessageTemplate::ProjectPullRequest', sys_notice: '{nickname1}在{nickname2}/{repository}提交了一个合并请求:{title}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') - self.create(type: 'MessageTemplate::ProjectRole', sys_notice: '仓库{repository}已把你的角色改为{role}', notification_url: '{baseurl}/{owner}/{identifier}') - self.create(type: 'MessageTemplate::ProjectSettingChanged', sys_notice: '{nickname1}更改了{nickname2}/{repository}仓库设置:{ifname}更改项目名称为"{name}"{endname}{ifdescription}更改项目简介为"{description}"{enddescription}{ifcategory}更改项目类别为"{category}"{endcategory}{iflanguage}更改项目语言为"{language}"{endlanguage}{ifpermission}将仓库设为"{permission}"{endpermission}{ifnavbar}将项目导航更改为"{navbar}"{endnavbar}', notification_url: '{baseurl}/{owner}/{identifier}/settings') + self.create(type: 'MessageTemplate::ProjectFollowed', sys_notice: '{nickname} 关注了你管理的仓库', notification_url: '{baseurl}/{login}') + self.create(type: 'MessageTemplate::ProjectForked', sys_notice: '{nickname1} 复刻了你管理的仓库{nickname1}/{repository1}到{nickname2}/{repository2}', notification_url: '{baseurl}/{owner}/{identifier}') + self.create(type: 'MessageTemplate::ProjectIssue', sys_notice: '{nickname1}在 {nickname2}/{repository} 新建易修:{title}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') + self.create(type: 'MessageTemplate::ProjectJoined', sys_notice: '你已加入 {repository} 项目', notification_url: '{baseurl}/{owner}/{identifier}') + self.create(type: 'MessageTemplate::ProjectLeft', sys_notice: '你已被移出 {repository} 项目', notification_url: '') + self.create(type: 'MessageTemplate::ProjectMemberJoined', sys_notice: '{nickname1} 已加入项目 {nickname2}/{repository}', notification_url: '{baseurl}/{owner}/{identifier}') + self.create(type: 'MessageTemplate::ProjectMemberLeft', sys_notice: '{nickname1} 已被移出项目 {nickname2}/{repository}', notification_url: '{baseurl}/{owner}/{identifier}') + self.create(type: 'MessageTemplate::ProjectMilestone', sys_notice: '{nickname1}在 {nickname2}/{repository} 创建了一个里程碑:{title}', notification_url: '{baseurl}/{owner}/{identifier}/milestones/{id}') + self.create(type: 'MessageTemplate::ProjectPraised', sys_notice: '{nickname} 点赞了你管理的仓库', notification_url: '{baseurl}/{login}') + self.create(type: 'MessageTemplate::ProjectPullRequest', sys_notice: '{nickname1}在 {nickname2}/{repository} 提交了一个合并请求:{title}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') + self.create(type: 'MessageTemplate::ProjectRole', sys_notice: '仓库 {repository} 已把你的角色改为 {role}', notification_url: '{baseurl}/{owner}/{identifier}') + self.create(type: 'MessageTemplate::ProjectSettingChanged', sys_notice: '{nickname1}更改了 {nickname2}/{repository} 仓库设置:{ifname}更改项目名称为"{name}"{endname}{ifdescription}更改项目简介为"{description}"{enddescription}{ifcategory}更改项目类别为"{category}"{endcategory}{iflanguage}更改项目语言为"{language}"{endlanguage}{ifpermission}将仓库设为"{permission}"{endpermission}{ifnavbar}将项目导航更改为"{navbar}"{endnavbar}', notification_url: '{baseurl}/{owner}/{identifier}/settings') self.create(type: 'MessageTemplate::ProjectTransfer', sys_notice: '你关注的仓库{nickname1}/{repository1}已被转移至{nickname2}/{repository2}', notification_url: '{baseurl}/{owner}/{identifier}') - self.create(type: 'MessageTemplate::ProjectVersion', sys_notice: '{nickname1}在{nickname2}/{repository}创建了发行版:{title}', notification_url: '{baseurl}/{owner}/{identifier}/releases') - self.create(type: 'MessageTemplate::PullRequestAssigned', sys_notice: '{nickname1}在{nickname2}/{repository}指派给你一个合并请求:{title}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') - self.create(type: 'MessageTemplate::PullRequestAtme', sys_notice: '{nickname}在合并请求{title}中@我', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') - self.create(type: 'MessageTemplate::PullRequestChanged', sys_notice: '在项目{nickname2}/{repository}的合并请求{title}中:{ifassigner}{nickname1}将审查成员从{assigner1}修改为{assigner2}{endassigner}{ifmilestone}{nickname1}将里程碑从{milestone1}修改为{milestone2}{endmilestone}{iftag}{nickname1}将标记从{tag1}修改为{tag2}{endtag}{ifpriority}{nickname1}将优先级从{priority1}修改为{priority2}{endpriority}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') + self.create(type: 'MessageTemplate::ProjectVersion', sys_notice: '{nickname1}在 {nickname2}/{repository} 创建了发行版:{title}', notification_url: '{baseurl}/{owner}/{identifier}/releases') + self.create(type: 'MessageTemplate::PullRequestAssigned', sys_notice: '{nickname1}在 {nickname2}/{repository} 指派给你一个合并请求:{title}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') + self.create(type: 'MessageTemplate::PullRequestAtme', sys_notice: '{nickname} 在合并请求 {title} 中@我', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') + self.create(type: 'MessageTemplate::PullRequestChanged', sys_notice: '在项目{nickname2}/{repository}的合并请求 {title} 中:{ifassigner}{nickname1}将审查成员从 {assigner1} 修改为 {assigner2} {endassigner}{ifmilestone}{nickname1}将里程碑从 {milestone1} 修改为 {milestone2} {endmilestone}{iftag}{nickname1}将标记从 {tag1} 修改为 {tag2} {endtag}{ifpriority}{nickname1}将优先级从 {priority1} 修改为 {priority2} {endpriority}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') self.create(type: 'MessageTemplate::PullRequestClosed', sys_notice: '你提交的合并请求:{title}被拒绝', notification_url: '') self.create(type: 'MessageTemplate::PullRequestJournal', sys_notice: '{nickname}评论合并请求{title}:{notes}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') self.create(type: 'MessageTemplate::PullRequestMerged', sys_notice: '你提交的合并请求:{title}已通过', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') diff --git a/app/models/message_template/issue_changed.rb b/app/models/message_template/issue_changed.rb index f6f44367..e1fe764a 100644 --- a/app/models/message_template/issue_changed.rb +++ b/app/models/message_template/issue_changed.rb @@ -82,17 +82,18 @@ class MessageTemplate::IssueChanged < MessageTemplate else content.gsub!(/({ifmilestone})(.*)({endmilestone})/, '') end - # 易修标签修改 + # 易修标记修改 if change_params[:issue_tags_value].present? issue_tags1 = IssueTag.where(id: change_params[:issue_tags_value][0]).distinct issue_tags2 = IssueTag.where(id: change_params[:issue_tags_value][1]).distinct - tag1 = issue_tags1.pluck(:name).join(",").blank? ? '未选择标签' : issue_tags1.pluck(:name).join(",") - tag2 = issue_tags2.pluck(:name).join(",").blank? ? '未选择标签' : issue_tags2.pluck(:name).join(",") + tag1 = issue_tags1.pluck(:name).join(",").blank? ? '未选择标记' : issue_tags1.pluck(:name).join(",") + tag2 = issue_tags2.pluck(:name).join(",").blank? ? '未选择标记' : issue_tags2.pluck(:name).join(",") if change_count > 1 content.sub!('{iftag}', '
    ') else - content.sub!('{endtag}', '') + content.sub!('{iftag}', '') end + content.sub!('{endtag}', '') content.gsub!('{tag1}', tag1) content.gsub!('{tag2}', tag2) else diff --git a/app/models/message_template/pull_request_changed.rb b/app/models/message_template/pull_request_changed.rb index 1f34f2d0..e7ebc670 100644 --- a/app/models/message_template/pull_request_changed.rb +++ b/app/models/message_template/pull_request_changed.rb @@ -53,12 +53,12 @@ class MessageTemplate::PullRequestChanged < MessageTemplate else content.gsub!(/({ifmilestone})(.*)({endmilestone})/, '') end - # 合并请求标签修改 + # 合并请求标记修改 if change_params[:issue_tags_value].present? issue_tags1 = IssueTag.where(id: change_params[:issue_tags_value][0]).distinct issue_tags2 = IssueTag.where(id: change_params[:issue_tags_value][1]).distinct - tag1 = issue_tags1.pluck(:name).join(",").blank? ? '未选择标签' : issue_tags1.pluck(:name).join(",") - tag2 = issue_tags2.pluck(:name).join(",").blank? ? '未选择标签' : issue_tags2.pluck(:name).join(",") + tag1 = issue_tags1.pluck(:name).join(",").blank? ? '未选择标记' : issue_tags1.pluck(:name).join(",") + tag2 = issue_tags2.pluck(:name).join(",").blank? ? '未选择标记' : issue_tags2.pluck(:name).join(",") if change_count > 1 content.sub!('{iftag}', '
    ') else From 12681b0842578a23a92bb2267777e63d3b178c8e Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 17 Sep 2021 14:56:34 +0800 Subject: [PATCH 043/135] fix: issue visit permission --- app/controllers/issues_controller.rb | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/app/controllers/issues_controller.rb b/app/controllers/issues_controller.rb index bbde2ecb..43e90195 100644 --- a/app/controllers/issues_controller.rb +++ b/app/controllers/issues_controller.rb @@ -399,22 +399,22 @@ class IssuesController < ApplicationController def check_project_public unless @project.is_public || @project.member?(current_user) || current_user.admin? || (@project.user_id == current_user.id) - normal_status(-1, "您没有权限") + return render_forbidden end end def set_issue @issue = Issue.find_by_id(params[:id]) if @issue.blank? - normal_status(-1, "标签不存在") - elsif @issue.is_lock &&!(@project.member?(current_user) || current_user.admin?) - normal_status(-1, "您没有权限") + return render_not_found + elsif !(@project.is_public || (current_user.present? && (@project.member?(current_user) || current_user&.admin? || (@project.user_id == current_user&.id)))) + return render_forbidden end end def check_issue_permission unless @project.is_public || (current_user.present? && (@project.member?(current_user) || current_user&.admin? || (@project.user_id == current_user&.id))) - normal_status(-1, "您没有权限") + return render_forbidden end end From 74a4b499a946733d218ad687c686f983282fe6bd Mon Sep 17 00:00:00 2001 From: yystopf Date: Sat, 18 Sep 2021 10:16:37 +0800 Subject: [PATCH 044/135] fix --- app/models/message_template.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/models/message_template.rb b/app/models/message_template.rb index df4ed782..19458076 100644 --- a/app/models/message_template.rb +++ b/app/models/message_template.rb @@ -44,9 +44,9 @@ class MessageTemplate {nickname2}/{repository}
    指派给你一个合并请求:{title}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') self.create(type: 'MessageTemplate::PullRequestAtme', sys_notice: '{nickname} 在合并请求 {title} 中@我', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') self.create(type: 'MessageTemplate::PullRequestChanged', sys_notice: '在项目{nickname2}/{repository}的合并请求 {title} 中:{ifassigner}{nickname1}将审查成员从 {assigner1} 修改为 {assigner2} {endassigner}{ifmilestone}{nickname1}将里程碑从 {milestone1} 修改为 {milestone2} {endmilestone}{iftag}{nickname1}将标记从 {tag1} 修改为 {tag2} {endtag}{ifpriority}{nickname1}将优先级从 {priority1} 修改为 {priority2} {endpriority}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') - self.create(type: 'MessageTemplate::PullRequestClosed', sys_notice: '你提交的合并请求:{title}被拒绝', notification_url: '') + self.create(type: 'MessageTemplate::PullRequestClosed', sys_notice: '你提交的合并请求:{title} 被拒绝', notification_url: '') self.create(type: 'MessageTemplate::PullRequestJournal', sys_notice: '{nickname}评论合并请求{title}:{notes}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') - self.create(type: 'MessageTemplate::PullRequestMerged', sys_notice: '你提交的合并请求:{title}已通过', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') + self.create(type: 'MessageTemplate::PullRequestMerged', sys_notice: '你提交的合并请求:{title} 已通过', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount') end def self.sys_notice From a2ae8f1630397cfc48e0bafce8f376b26e8aaf53 Mon Sep 17 00:00:00 2001 From: yystopf Date: Sat, 18 Sep 2021 10:24:16 +0800 Subject: [PATCH 045/135] fix: profile completed --- app/models/user.rb | 10 +++++----- app/views/users/get_user_info.json.jbuilder | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/app/models/user.rb b/app/models/user.rb index 1a7cdeec..3c4a900a 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -186,7 +186,7 @@ class User < Owner :show_email, :show_location, :show_department, :technical_title, :province, :city, :custom_department, to: :user_extension, allow_nil: true - before_save :update_hashed_password, :set_lastname, :set_profile_completed + before_save :update_hashed_password, :set_lastname after_create do SyncTrustieJob.perform_later("user", 1) if allow_sync_to_trustie? end @@ -757,6 +757,10 @@ class User < Owner laboratory_id.present? && laboratory_id != 1 end + def profile_is_completed? + self.nickname.present? && self.gender.present? && self.mail.present? && self.custom_department.present? + end + protected def validate_password_length # 管理员的初始密码是5位 @@ -783,10 +787,6 @@ class User < Owner def set_lastname self.lastname = self.nickname if changes[:nickname].present? end - - def set_profile_completed - self.profile_completed = self.nickname.present? && self.gender.present? && self.mail.present? && self.custom_department.present? - end end diff --git a/app/views/users/get_user_info.json.jbuilder b/app/views/users/get_user_info.json.jbuilder index 067019ef..09de3d63 100644 --- a/app/views/users/get_user_info.json.jbuilder +++ b/app/views/users/get_user_info.json.jbuilder @@ -12,7 +12,7 @@ json.tidding_count 0 json.user_phone_binded @user.phone.present? # json.phone @user.phone # json.email @user.mail -json.profile_completed @user.profile_completed? +json.profile_completed @user.profile_is_completed? json.professional_certification @user.professional_certification json.devops_step @user.devops_step json.ci_certification @user.ci_certification? From a910b11860e623f47c68e3b2d7d813377993f146 Mon Sep 17 00:00:00 2001 From: yystopf Date: Sat, 18 Sep 2021 10:38:07 +0800 Subject: [PATCH 046/135] =?UTF-8?q?fix:=20=E9=A1=B9=E7=9B=AE=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E5=88=A0=E9=99=A4=E7=BB=84=E7=BB=87=E7=AD=9B=E9=80=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/queries/projects/list_query.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/queries/projects/list_query.rb b/app/queries/projects/list_query.rb index 771d4c92..4658408d 100644 --- a/app/queries/projects/list_query.rb +++ b/app/queries/projects/list_query.rb @@ -11,7 +11,7 @@ class Projects::ListQuery < ApplicationQuery end def call - q = Project.all_visible(current_user_id).by_name_or_identifier(params[:search]) + q = Project.visible.by_name_or_identifier(params[:search]) scope = q .with_project_type(params[:project_type]) From d957e0544ff92dd8749becf81dd29a8d726638fb Mon Sep 17 00:00:00 2001 From: yystopf Date: Sat, 18 Sep 2021 18:41:03 +0800 Subject: [PATCH 047/135] add: message template management --- .../admins/message_templates_controller.rb | 34 ++++++++++++ .../project_setting_changed.rb | 8 ++- .../admins/message_templates/_form.html.erb | 53 +++++++++++++++++++ .../admins/message_templates/_list.html.erb | 39 ++++++++++++++ .../admins/message_templates/edit.js.erb | 1 + .../admins/message_templates/index.html.erb | 9 ++++ .../admins/message_templates/index.js.erb | 1 + app/views/admins/shared/_sidebar.html.erb | 1 + config/routes.rb | 1 + 9 files changed, 145 insertions(+), 2 deletions(-) create mode 100644 app/controllers/admins/message_templates_controller.rb create mode 100644 app/views/admins/message_templates/_form.html.erb create mode 100644 app/views/admins/message_templates/_list.html.erb create mode 100644 app/views/admins/message_templates/edit.js.erb create mode 100644 app/views/admins/message_templates/index.html.erb create mode 100644 app/views/admins/message_templates/index.js.erb diff --git a/app/controllers/admins/message_templates_controller.rb b/app/controllers/admins/message_templates_controller.rb new file mode 100644 index 00000000..7724dde5 --- /dev/null +++ b/app/controllers/admins/message_templates_controller.rb @@ -0,0 +1,34 @@ +class Admins::MessageTemplatesController < Admins::BaseController + before_action :get_template, only: [:edit,:update, :destroy] + + def index + message_templates = MessageTemplate.group(:type).count.keys + @message_templates = kaminari_array_paginate(message_templates) + end + + def edit + end + + def update + if @message_template.update_attributes(message_template_params) + redirect_to admins_message_templates_path + flash[:success] = '消息模版更新成功' + else + redirect_to admins_message_templates_path + flash[:danger] = @message_template.errors.full_messages.join(",") + end + end + + private + def message_template_params + params.require(:message_template).permit! + end + + def get_template + @message_template = MessageTemplate.find_by(id: params[:id]) + unless @message_template.present? + redirect_to admins_message_templates_path + flash[:danger] = "消息模版不存在" + end + end +end \ No newline at end of file diff --git a/app/models/message_template/project_setting_changed.rb b/app/models/message_template/project_setting_changed.rb index 9510fa58..8d4947db 100644 --- a/app/models/message_template/project_setting_changed.rb +++ b/app/models/message_template/project_setting_changed.rb @@ -110,8 +110,12 @@ class MessageTemplate::ProjectSettingChanged < MessageTemplate end # 项目导航更改 if change_params[:navbar].present? - navbar = project.project_units.order(unit_type: :asc).pluck(:unit_type).join(',') - navbar.gsub!('code,', '') + unit_types = project.project_units.order(unit_type: :asc).pluck(:unit_type) + unit_types.delete('code') + unit_types.unshift('代码库') + unit_types.unshift('主页') + unit_types.append('动态') + navbar = unit_types.join(',') navbar.gsub!('issues', '易修') navbar.gsub!('pulls', '合并请求') navbar.gsub!('wiki', 'Wiki') diff --git a/app/views/admins/message_templates/_form.html.erb b/app/views/admins/message_templates/_form.html.erb new file mode 100644 index 00000000..d8b7158c --- /dev/null +++ b/app/views/admins/message_templates/_form.html.erb @@ -0,0 +1,53 @@ +
    +
    <%= type == "create" ? "新建" : "编辑" %>消息模版
    + <%= link_to "返回", admins_message_templates_path, class: "btn btn-default pull-right" %> +
    + +
    + <%= form_for @message_template, url: {controller: "message_templates", action: "#{type}"} do |f| %> + +
    + +
    + <%= f.text_area :sys_notice, class:"form-control", rows: "10", cols: "20",placeholer: "站内信模版" %> +
    + + + +
    +
    + +
    + <%= f.text_area :email, class:"form-control", rows: "10", cols: "20",placeholer: "邮件模版" %> +
    + + + +
    +
    + +
    + <%= f.text_field :notification_url, class: "form-control input-lg", maxlength: "60", placeholder: "跳转地址" %> +
    + +
    +
    + <%= f.submit "确认", class: "btn btn-primary submit-btn" %> +
    + <% end %> +
    \ No newline at end of file diff --git a/app/views/admins/message_templates/_list.html.erb b/app/views/admins/message_templates/_list.html.erb new file mode 100644 index 00000000..0f495eff --- /dev/null +++ b/app/views/admins/message_templates/_list.html.erb @@ -0,0 +1,39 @@ + + + + + + + + + + + + + <% if message_templates.present? %> + <% message_templates.each_with_index do |message_template_type, index| %> + <% message_template = message_template_type.constantize.last%> + + + + + + + + + <% end %> + <% else %> + <%= render 'admins/shared/no_data_for_table' %> + <% end %> + +
    序号类型系统消息模版邮件模版通知地址操作
    <%= list_index_no((params[:page] || 1).to_i, index) %><%= message_template.type.split("::")[1] %> + <%= message_template.sys_notice.to_s.truncate(200) %> + + <%= message_template.email.to_s.truncate(200) %> + + <%= message_template.notification_url.to_s.truncate(200) %> + + <%= link_to "编辑", edit_admins_message_template_path(message_template),remote: true, class: "action" %> +
    + +<%= render partial: 'admins/shared/paginate', locals: { objects: message_templates } %> \ No newline at end of file diff --git a/app/views/admins/message_templates/edit.js.erb b/app/views/admins/message_templates/edit.js.erb new file mode 100644 index 00000000..789dd286 --- /dev/null +++ b/app/views/admins/message_templates/edit.js.erb @@ -0,0 +1 @@ +$("#admins-message-templates-content").html("<%= j render partial: 'admins/message_templates/form', locals:{type: 'update'} %>") \ No newline at end of file diff --git a/app/views/admins/message_templates/index.html.erb b/app/views/admins/message_templates/index.html.erb new file mode 100644 index 00000000..ab2af2f9 --- /dev/null +++ b/app/views/admins/message_templates/index.html.erb @@ -0,0 +1,9 @@ +<% define_admin_breadcrumbs do %> + <% add_admin_breadcrumb('消息模版') %> +<% end %> +
    +
    + <%= render partial: 'admins/message_templates/list', locals: { message_templates: @message_templates } %> +
    +
    + diff --git a/app/views/admins/message_templates/index.js.erb b/app/views/admins/message_templates/index.js.erb new file mode 100644 index 00000000..d8e0fdd2 --- /dev/null +++ b/app/views/admins/message_templates/index.js.erb @@ -0,0 +1 @@ +$('.message-templates-list-container').html("<%= j( render partial: 'admins/message_templates/list', locals: { message_templates: @message_templates } ) %>"); \ 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 e58337c1..402449b3 100644 --- a/app/views/admins/shared/_sidebar.html.erb +++ b/app/views/admins/shared/_sidebar.html.erb @@ -30,6 +30,7 @@
  • <%= sidebar_item(admins_reversed_keywords_path, '系统保留关键词', icon: 'key', controller: 'admins-reversed_keywords') %>
  • +
  • <%= sidebar_item(admins_message_templates_path, '消息模版', icon: 'folder', controller: 'admins-message_templates') %>
  • <%= sidebar_item(admins_laboratories_path, '云上实验室', icon: 'cloud', controller: 'admins-laboratories') %>
  • diff --git a/config/routes.rb b/config/routes.rb index 06b634fc..e0ea4207 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -668,6 +668,7 @@ Rails.application.routes.draw do resources :project_licenses resources :project_ignores resources :reversed_keywords + resources :message_templates, only: [:index, :edit, :update] resources :major_informations, only: [:index] resources :ec_templates, only: [:index, :destroy] do collection do From 0581c59a84ab1e723391b95cf6323e4f59ade197 Mon Sep 17 00:00:00 2001 From: yystopf Date: Sat, 18 Sep 2021 18:50:45 +0800 Subject: [PATCH 048/135] fix: message template simple type --- app/models/message_template.rb | 4 ++++ app/views/admins/message_templates/_form.html.erb | 2 +- app/views/admins/message_templates/_list.html.erb | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/app/models/message_template.rb b/app/models/message_template.rb index 19458076..88be2f51 100644 --- a/app/models/message_template.rb +++ b/app/models/message_template.rb @@ -64,4 +64,8 @@ class MessageTemplate -
    <%= type == "create" ? "新建" : "编辑" %>消息模版
    +
    <%= type == "create" ? "新建" : "编辑" %><%= @message_template.simple_type %>消息模版
    <%= link_to "返回", admins_message_templates_path, class: "btn btn-default pull-right" %> diff --git a/app/views/admins/message_templates/_list.html.erb b/app/views/admins/message_templates/_list.html.erb index 0f495eff..a5a1a726 100644 --- a/app/views/admins/message_templates/_list.html.erb +++ b/app/views/admins/message_templates/_list.html.erb @@ -15,7 +15,7 @@ <% message_template = message_template_type.constantize.last%> <%= list_index_no((params[:page] || 1).to_i, index) %> - <%= message_template.type.split("::")[1] %> + <%= message_template.simple_type %> <%= message_template.sys_notice.to_s.truncate(200) %> From 53212975f1bbb08b71ae03ac4f8cf767457942aa Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 22 Sep 2021 09:53:43 +0800 Subject: [PATCH 049/135] add: init data button --- app/controllers/admins/message_templates_controller.rb | 10 ++++++++++ app/views/admins/message_templates/index.html.erb | 3 +++ config/routes.rb | 6 +++++- 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/app/controllers/admins/message_templates_controller.rb b/app/controllers/admins/message_templates_controller.rb index 7724dde5..b474c428 100644 --- a/app/controllers/admins/message_templates_controller.rb +++ b/app/controllers/admins/message_templates_controller.rb @@ -19,6 +19,16 @@ class Admins::MessageTemplatesController < Admins::BaseController end end + def init_data + if MessageTemplate.build_init_data + redirect_to admins_message_templates_path + flash[:success] = '消息模版初始化成功' + else + redirect_to admins_message_templates_path + flash[:danger] = '消息模版初始化失败' + end + end + private def message_template_params params.require(:message_template).permit! diff --git a/app/views/admins/message_templates/index.html.erb b/app/views/admins/message_templates/index.html.erb index ab2af2f9..54d27333 100644 --- a/app/views/admins/message_templates/index.html.erb +++ b/app/views/admins/message_templates/index.html.erb @@ -2,6 +2,9 @@ <% add_admin_breadcrumb('消息模版') %> <% end %>
    +
    + <%= link_to "初始化数据", init_data_admins_message_templates_path, class: "btn btn-primary pull-right", "data-disabled-with":"...初始化数据" %> +
    <%= render partial: 'admins/message_templates/list', locals: { message_templates: @message_templates } %>
    diff --git a/config/routes.rb b/config/routes.rb index e0ea4207..9c6dda1b 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -668,7 +668,11 @@ Rails.application.routes.draw do resources :project_licenses resources :project_ignores resources :reversed_keywords - resources :message_templates, only: [:index, :edit, :update] + resources :message_templates, only: [:index, :edit, :update] do + collection do + get :init_data + end + end resources :major_informations, only: [:index] resources :ec_templates, only: [:index, :destroy] do collection do From e5199425ee90e1ba7f3a2dd5cd58bbf859197c77 Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 22 Sep 2021 14:25:56 +0800 Subject: [PATCH 050/135] add: template email message --- .../admins/message_templates_controller.rb | 6 +- app/jobs/send_template_message_job.rb | 26 ++++ app/models/message_template.rb | 10 +- app/models/message_template/issue_assigned.rb | 11 ++ .../message_template/organization_joined.rb | 9 ++ .../message_template/organization_left.rb | 10 ++ .../message_template/organization_role.rb | 9 ++ app/models/message_template/project_issue.rb | 13 ++ app/models/message_template/project_joined.rb | 8 ++ app/models/message_template/project_left.rb | 10 ++ .../message_template/project_member_joined.rb | 9 ++ .../message_template/project_member_left.rb | 9 ++ .../message_template/project_pull_request.rb | 13 ++ app/models/message_template/project_role.rb | 9 ++ .../project_setting_changed.rb | 124 ++++++++++++++++++ .../message_template/pull_request_assigned.rb | 11 ++ app/services/notice/read/client_service.rb | 12 +- app/services/notice/read/count_service.rb | 2 +- app/services/notice/read/list_service.rb | 2 +- .../notice/write/change_status_service.rb | 6 +- app/services/notice/write/client_service.rb | 12 +- app/services/notice/write/create_service.rb | 6 +- app/services/notice/write/delete_service.rb | 6 +- .../notice/write/email_create_service.rb | 36 +++++ 24 files changed, 348 insertions(+), 21 deletions(-) create mode 100644 app/services/notice/write/email_create_service.rb diff --git a/app/controllers/admins/message_templates_controller.rb b/app/controllers/admins/message_templates_controller.rb index b474c428..23c94e78 100644 --- a/app/controllers/admins/message_templates_controller.rb +++ b/app/controllers/admins/message_templates_controller.rb @@ -1,5 +1,5 @@ class Admins::MessageTemplatesController < Admins::BaseController - before_action :get_template, only: [:edit,:update, :destroy] + before_action :get_template, only: [:edit, :update, :destroy] def index message_templates = MessageTemplate.group(:type).count.keys @@ -30,8 +30,8 @@ class Admins::MessageTemplatesController < Admins::BaseController end private - def message_template_params - params.require(:message_template).permit! + def message_template_params + params.require(@message_template.type.split("::").join("_").underscore.to_sym).permit! end def get_template diff --git a/app/jobs/send_template_message_job.rb b/app/jobs/send_template_message_job.rb index ac5e956a..3dc946e7 100644 --- a/app/jobs/send_template_message_job.rb +++ b/app/jobs/send_template_message_job.rb @@ -20,6 +20,8 @@ class SendTemplateMessageJob < ApplicationJob receivers = User.where(id: issue&.assigned_to_id).where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::IssueAssigned.get_message_content(receivers, operator, issue) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_id: issue.id}) + receivers_email_string, email_content, notification_url = MessageTemplate::IssueAssigned.get_email_message_content(receivers, operator, issue) + Notice::Write::EmailCreateService.call(receivers_email_string, email_content, source) when 'IssueAssignerExpire' issue_id = args[0] issue = Issue.find_by_id(issue_id) @@ -65,6 +67,8 @@ class SendTemplateMessageJob < ApplicationJob receivers = User.where(id: user.id) receivers_string, content, notification_url = MessageTemplate::OrganizationJoined.get_message_content(receivers, organization) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {user_id: user.id, organization_id: organization.id}) + receivers_email_string, email_content, notification_url = MessageTemplate::OrganizationJoined.get_email_message_content(receivers, organization) + Notice::Write::EmailCreateService.call(receivers_email_string, email_content, source) when 'OrganizationLeft' user_id, organization_id = args[0], args[1] user = User.find_by_id(user_id) @@ -73,6 +77,8 @@ class SendTemplateMessageJob < ApplicationJob receivers = User.where(id: user.id) receivers_string, content, notification_url = MessageTemplate::OrganizationLeft.get_message_content(receivers, organization) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {user_id: user.id, organization_id: organization.id}) + receivers_email_string, email_content, notification_url = MessageTemplate::OrganizationLeft.get_email_message_content(receivers, organization) + Notice::Write::EmailCreateService.call(receivers_email_string, email_content, source) when 'OrganizationRole' user_id, organization_id, role = args[0], args[1], args[2] user = User.find_by_id(user_id) @@ -81,6 +87,8 @@ class SendTemplateMessageJob < ApplicationJob receivers = User.where(id: user.id) receivers_string, content, notification_url = MessageTemplate::OrganizationRole.get_message_content(receivers, organization, role) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {user_id: user.id, organization_id: organization.id, role: role}) + receivers_email_string, email_content, notification_url = MessageTemplate::OrganizationRole.get_email_message_content(receivers, organization, role) + Notice::Write::EmailCreateService.call(receivers_email_string, email_content, source) when 'ProjectIssue' operator_id, issue_id = args[0], args[1] operator = User.find_by_id(operator_id) @@ -90,6 +98,8 @@ class SendTemplateMessageJob < ApplicationJob followers = [] # TODO receivers_string, content, notification_url = MessageTemplate::ProjectIssue.get_message_content(managers, followers, operator, issue) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_id: issue.id}) + receivers_email_string, email_content, notification_url = MessageTemplate::ProjectIssue.get_email_message_content(managers, followers, operator, issue) + Notice::Write::EmailCreateService.call(receivers_email_string, email_content, source) when 'ProjectJoined' operator_id, user_id, project_id = args[0], args[1], args[2] operator = User.find_by_id(operator_id) @@ -99,6 +109,8 @@ class SendTemplateMessageJob < ApplicationJob receivers = User.where(id: user.id).where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::ProjectJoined.get_message_content(receivers, project) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, user_id: user.id, project_id: project.id}) + receivers_emal_string, email_content, notification_url = MessageTemplate::ProjectJoined.get_email_message_content(receivers, project) + Notice::Write::EmailCreateService.call(receivers_email_string, email_content, source) when 'ProjectLeft' operator_id, user_id, project_id = args[0], args[1], args[2] operator = User.find_by_id(operator_id) @@ -108,6 +120,8 @@ class SendTemplateMessageJob < ApplicationJob receivers = User.where(id: user.id).where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::ProjectLeft.get_message_content(receivers, project) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, user_id: user.id, project_id: project.id}) + receivers_email_string, email_content, notification_url = MessageTemplate::ProjectLeft.get_email_message_content(receivers, project) + Notice::Write::EmailCreateService.call(receivers_email_string, email_content, source) when 'ProjectMemberJoined' operator_id, user_id, project_id = args[0], args[1], args[2] operator = User.find_by_id(operator_id) @@ -117,6 +131,8 @@ class SendTemplateMessageJob < ApplicationJob receivers = project&.all_managers.where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::ProjectMemberJoined.get_message_content(receivers, user, project) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, user_id: user.id, project_id: project.id}) + receivers_email_string, email_content, notification_url = MessageTemplate::ProjectMemberJoined.get_email_message_content(receivers, user, project) + Notice::Write::EmailCreateService.call(receivers_email_string, email_content, source) when 'ProjectMemberLeft' operator_id, user_id, project_id = args[0], args[1], args[2] operator = User.find_by_id(operator_id) @@ -126,6 +142,8 @@ class SendTemplateMessageJob < ApplicationJob receivers = project&.all_managers.where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::ProjectMemberLeft.get_message_content(receivers, user, project) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, user_id: user.id, project_id: project.id}) + receivers_email_string, email_content, notification_url = MessageTemplate::ProjectMemberLeft.get_email_message_content(receivers, user, project) + Notice::Write::EmailCreateService.call(receivers_email_string, email_content, source) when 'ProjectPullRequest' operator_id, pull_request_id = args[0], args[1] operator = User.find_by_id(operator_id) @@ -135,6 +153,8 @@ class SendTemplateMessageJob < ApplicationJob followers = [] # TODO receivers_string, content, notification_url = MessageTemplate::ProjectPullRequest.get_message_content(managers, followers, operator, pull_request) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, pull_request_id: pull_request.id}) + receivers_email_string, email_content, notification_url = MessageTemplate::ProjectPullRequest.get_email_message_content(managers, followers, operator, pull_request) + Notice::Write::EmailCreateService.call(receivers_email_string, email_content, source) when 'ProjectRole' operator_id, user_id, project_id, role = args[0], args[1], args[2], args[3] operator = User.find_by_id(operator_id) @@ -144,6 +164,8 @@ class SendTemplateMessageJob < ApplicationJob receivers = User.where(id: user.id).where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::ProjectRole.get_message_content(receivers, project, role) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, user_id: user.id, project_id: project.id, role: role}) + receivers_email_string, email_content, notification_url = MessageTemplate::ProjectRole.get_email_message_content(receivers, project, role) + Notice::Write::EmailCreateService.call(receivers_email_string, email_content, source) when 'ProjectSettingChanged' operator_id, project_id, change_params = args[0], args[1], args[2] operator = User.find_by_id(operator_id) @@ -152,6 +174,8 @@ class SendTemplateMessageJob < ApplicationJob receivers = project.all_managers.where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::ProjectSettingChanged.get_message_content(receivers, operator, project, change_params.symbolize_keys) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, project_id: project.id, change_params: change_params}) + receivers_email_string, email_content, notification_url = MessageTemplate::ProjectSettingChanged.get_email_message_content(receivers, operator, project, change_params.symbolize_keys) + Notice::Write::EmailCreateService.call(receivers_email_string, email_content, source) when 'PullRequestAssigned' operator_id, pull_request_id = args[0], args[1] operator = User.find_by_id(operator_id) @@ -161,6 +185,8 @@ class SendTemplateMessageJob < ApplicationJob receivers = User.where(id: issue&.assigned_to_id).where.not(id: operator&.id) receivers_string, content, notification_url = MessageTemplate::PullRequestAssigned.get_message_content(receivers, operator, pull_request) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, pull_request_id: pull_request.id}) + receivers_email_string, email_content, notification_url = MessageTemplate::PullRequestAssigned.get_email_message_content(receivers, operator, pull_request) + Notice::Write::EmailCreateService.call(receivers_email_string, email_content, source) when 'PullRequestAtme' receivers, operator_id, pull_request_id = args[0], args[1], args[2] operator = User.find_by_id(operator_id) diff --git a/app/models/message_template.rb b/app/models/message_template.rb index 88be2f51..daca0283 100644 --- a/app/models/message_template.rb +++ b/app/models/message_template.rb @@ -11,7 +11,7 @@ # notification_url :string(255) # -class MessageTemplate {nickname}
    关注了你', notification_url: '{baseurl}/{login}') @@ -53,6 +53,10 @@ class MessageTemplate e + Rails.logger.info("MessageTemplate::IssueAssigned.get_email_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/organization_joined.rb b/app/models/message_template/organization_joined.rb index 81ae2a67..91837483 100644 --- a/app/models/message_template/organization_joined.rb +++ b/app/models/message_template/organization_joined.rb @@ -23,4 +23,13 @@ class MessageTemplate::OrganizationJoined < MessageTemplate Rails.logger.info("MessageTemplate::OrganizationJoined.get_message_content [ERROR] #{e}") return '', '', '' end + + def self.get_email_message_content(receivers, organization) + content = email.gsub('{organization}', organization&.real_name) + url = notification_url.gsub('{login}', organization&.login) + return receivers_email_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::OrganizationJoined.get_email_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/organization_left.rb b/app/models/message_template/organization_left.rb index 16652d30..2f63cfca 100644 --- a/app/models/message_template/organization_left.rb +++ b/app/models/message_template/organization_left.rb @@ -23,4 +23,14 @@ class MessageTemplate::OrganizationLeft < MessageTemplate Rails.logger.info("MessageTemplate::OrganizationLeft.get_message_content [ERROR] #{e}") return '', '', '' end + + def self.get_email_message_content(receivers, organization) + content = email.gsub('{organization}', organization&.real_name) + url = notification_url.gsub('{login}', organization&.login) + + return receivers_email_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::OrganizationLeft.get_email_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/organization_role.rb b/app/models/message_template/organization_role.rb index 33c32651..f494d5bd 100644 --- a/app/models/message_template/organization_role.rb +++ b/app/models/message_template/organization_role.rb @@ -23,4 +23,13 @@ class MessageTemplate::OrganizationRole < MessageTemplate Rails.logger.info("MessageTemplate::OrganizationRole.get_message_content [ERROR] #{e}") return '', '', '' end + + def self.get_email_message_content(receivers, organization, role) + content = email.gsub('{organization}', organization&.real_name).gsub('{role}', role) + url = notification_url.gsub('{login}', organization&.login) + return receivers_email_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::OrganizationRole.get_email_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_issue.rb b/app/models/message_template/project_issue.rb index 700932ad..e7126237 100644 --- a/app/models/message_template/project_issue.rb +++ b/app/models/message_template/project_issue.rb @@ -27,4 +27,17 @@ class MessageTemplate::ProjectIssue < MessageTemplate Rails.logger.info("MessageTemplate::ProjectIssue.get_message_content [ERROR] #{e}") return '', '', '' end + + def self.get_email_message_content(managers, followers, operator, issue) + project = issue&.project + owner = project&.owner + receivers = managers + followers + content = email.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub('{title}', issue&.subject) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s) + + return receivers_email_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectIssue.get_email_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_joined.rb b/app/models/message_template/project_joined.rb index 91d4b3c1..91836a59 100644 --- a/app/models/message_template/project_joined.rb +++ b/app/models/message_template/project_joined.rb @@ -23,4 +23,12 @@ class MessageTemplate::ProjectJoined < MessageTemplate Rails.logger.info("MessageTemplate::ProjectJoined.get_message_content [ERROR] #{e}") return '', '', '' end + + def self.get_email_message_content(receivers, project) + content = email.gsub('{repository}', project&.name) + url = notification_url.gsub('{owner}', project&.owner&.login).gsub('{identifier}', project&.identifier) + rescue => e + Rails.logger.info("MessageTemplate::ProjectJoined.get_email_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_left.rb b/app/models/message_template/project_left.rb index e83b027a..dabb31d1 100644 --- a/app/models/message_template/project_left.rb +++ b/app/models/message_template/project_left.rb @@ -23,4 +23,14 @@ class MessageTemplate::ProjectLeft < MessageTemplate Rails.logger.info("MessageTemplate::ProjectLeft.get_message_content [ERROR] #{e}") return '', '', '' end + + def self.get_email_message_content(receivers, project) + content = email.gsub('{repository}', project&.name) + url = notification_url.gsub('{owner}', project&.owner&.login).gsub('{identifier}', project&.identifier) + + return receivers_email_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectLeft.get_email_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_member_joined.rb b/app/models/message_template/project_member_joined.rb index a510265b..f08a99ff 100644 --- a/app/models/message_template/project_member_joined.rb +++ b/app/models/message_template/project_member_joined.rb @@ -23,4 +23,13 @@ class MessageTemplate::ProjectMemberJoined < MessageTemplate Rails.logger.info("MessageTemplate::ProjectMemberJoined.get_message_content [ERROR] #{e}") return '', '', '' end + + def self.get_email_message_content(receivers, user, project) + content = email.gsub('{nickname}', user&.real_name).gsub('{nickname2}', project&.owner&.real_name).gsub('{repository}', project&.name) + url = notification_url.gsub('{owner}', project&.owner&.login).gsub('{identifier}', project&.identifier) + return receivers_email_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectMemberJoined.get_email_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_member_left.rb b/app/models/message_template/project_member_left.rb index 9d26e102..846a496e 100644 --- a/app/models/message_template/project_member_left.rb +++ b/app/models/message_template/project_member_left.rb @@ -23,4 +23,13 @@ class MessageTemplate::ProjectMemberLeft < MessageTemplate Rails.logger.info("MessageTemplate::ProjectMemberLeft.get_message_content [ERROR] #{e}") return '', '', '' end + + def self.get_email_message_content(receivers, user, project) + content = email.gsub('{nickname1}', user&.real_name).gsub('{nickname2}', project&.owner&.real_name).gsub("{repository}", project&.name) + url = notification_url.gsub('{owner}', project&.owner&.login).gsub('{identifier}', project&.identifier) + return receivers_email_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectMemberLeft.get_email_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_pull_request.rb b/app/models/message_template/project_pull_request.rb index 2db1021a..70c0ab54 100644 --- a/app/models/message_template/project_pull_request.rb +++ b/app/models/message_template/project_pull_request.rb @@ -27,4 +27,17 @@ class MessageTemplate::ProjectPullRequest < MessageTemplate Rails.logger.info("MessageTemplate::ProjectPullRequest.get_message_content [ERROR] #{e}") return '', '', '' end + + def self.get_email_message_content(managers, followers, operator, pull_request) + project = pull_request&.project + owner = project&.owner + receivers = managers + followers + content = email.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub('{title}', pull_request&.title) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', pull_request&.id.to_s) + + return receivers_email_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectPullRequest.get_email_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_role.rb b/app/models/message_template/project_role.rb index cb229007..459b6fd1 100644 --- a/app/models/message_template/project_role.rb +++ b/app/models/message_template/project_role.rb @@ -23,4 +23,13 @@ class MessageTemplate::ProjectRole < MessageTemplate Rails.logger.info("MessageTemplate::ProjectRole.get_message_content [ERROR] #{e}") return '', '', '' end + + def self.get_email_message_content(receivers, project, role) + content = email.gsub('{repository}', project&.name).gsub('{role}', role) + url = notification_url.gsub('{owner}', project&.owner&.login).gsub('{identifier}', project&.identifier) + return receivers_email_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectRole.get_email_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/project_setting_changed.rb b/app/models/message_template/project_setting_changed.rb index 8d4947db..9bd11986 100644 --- a/app/models/message_template/project_setting_changed.rb +++ b/app/models/message_template/project_setting_changed.rb @@ -138,4 +138,128 @@ class MessageTemplate::ProjectSettingChanged < MessageTemplate Rails.logger.info("MessageTemplate::ProjectSettingChanged.get_message_content [ERROR] #{e}") return '', '', '' end + + def self.get_email_message_content(receivers, operator, project, change_params) + return '', '', '' if change_params.blank? + owner = project&.owner + content = email.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier) + change_count = change_params.keys.size + # 项目名称更改 + if change_params[:name].present? + if change_count > 1 + content.sub!('{ifname}', '
    ') + else + content.sub!('{ifname}', '') + end + content.sub!('{endname}', '') + content.gsub!('{name}', change_params[:name][1]) + else + content.gsub!(/({ifname})(.*)({endname})/, '') + end + # 项目简介更改 + if change_params[:description].present? + if change_params[:description][1].blank? + if change_count > 1 + content.gsub!(/({ifdescription})(.*)({enddescription})/, '
    删除了项目简介') + else + content.gsub!(/({ifdescription})(.*)({enddescription})/, '删除了项目简介') + end + else + if change_count > 1 + content.sub!('{ifdescription}', '
    ') + else + content.sub!('{ifdescription}', '') + end + content.sub!('{enddescription}', '') + content.gsub!('{description}', change_params[:description][1]) + end + else + content.gsub!(/({ifdescription})(.*)({enddescription})/, '') + end + # 项目类别更改 + if change_params[:project_category_id].present? + category = ProjectCategory.find_by_id(change_params[:project_category_id][1]) + if category.present? + if change_count > 1 + content.sub!('{ifcategory}', '
    ') + else + content.sub!('{ifcategory}', '') + end + content.sub!('{endcategory}', '') + content.gsub!('{category}', category&.name) + else + if change_count > 1 + content.gsub!(/({ifcategory})(.*)({endcategory})/, '
    删除了项目类别') + else + content.gsub!(/({ifcategory})(.*)({endcategory})/, '删除了项目类别') + end + end + else + content.gsub!(/({ifcategory})(.*)({endcategory})/, '') + end + # 项目语言更改 + if change_params[:project_language_id].present? + language = ProjectLanguage.find_by_id(change_params[:project_language_id][1]) + if language.present? + if change_count > 1 + content.sub!('{iflanguage}', '
    ') + else + content.sub!('{iflanguage}', '') + end + content.sub!('{endlanguage}', '') + content.gsub!('{language}', language&.name) + else + if change_count > 1 + content.gsub!(/({iflanguage})(.*)({endlanguage})/, '
    删除了项目语言') + else + content.gsub!(/({iflanguage})(.*)({endlanguage})/, '删除了项目语言') + end + end + else + content.gsub!(/({iflanguage})(.*)({endlanguage})/, '') + end + # 项目公私有更改 + if change_params[:is_public].present? + permission = change_params[:is_public][1] ? '公有' : '私有' + if change_count > 1 + content.sub!('{ifpermission}', '
    ') + else + content.sub!('{ifpermission}', '') + end + content.sub!('{endpermission}', '') + content.gsub!('{permission}', permission) + else + content.gsub!(/({ifpermission})(.*)({endpermission})/, '') + end + # 项目导航更改 + if change_params[:navbar].present? + unit_types = project.project_units.order(unit_type: :asc).pluck(:unit_type) + unit_types.delete('code') + unit_types.unshift('代码库') + unit_types.unshift('主页') + unit_types.append('动态') + navbar = unit_types.join(',') + navbar.gsub!('issues', '易修') + navbar.gsub!('pulls', '合并请求') + navbar.gsub!('wiki', 'Wiki') + navbar.gsub!('devops', '工作流') + navbar.gsub!('versions', '里程碑') + navbar.gsub!('resources', '资源库') + if change_count > 1 + content.sub!('{ifnavbar}', '
    ') + else + content.sub!('{ifnavbar}', '') + end + content.sub!('{endnavbar}', '') + content.gsub!('{navbar}', navbar) + else + content.gsub!(/({ifnavbar})(.*)({endnavbar})/, '') + end + + return receivers_email_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::ProjectSettingChanged.get_email_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/pull_request_assigned.rb b/app/models/message_template/pull_request_assigned.rb index 5b3e6538..1cd90164 100644 --- a/app/models/message_template/pull_request_assigned.rb +++ b/app/models/message_template/pull_request_assigned.rb @@ -25,4 +25,15 @@ class MessageTemplate::PullRequestAssigned < MessageTemplate Rails.logger.info("MessageTemplate::PullRequestAssigned.get_message_content [ERROR] #{e}") return '', '', '' end + + def self.get_email_message_content(receivers, operator, pull_request) + project = pull_request&.project + owner = project&.owner + content = email.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub('{title}', pull_request&.title) + url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', pull_request&.id.to_s) + return receivers_email_string(receivers), content, url + rescue => e + Rails.logger.info("MessageTemplate::PullRequestAssigned.get_email_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/services/notice/read/client_service.rb b/app/services/notice/read/client_service.rb index 39ba816c..95ab8159 100644 --- a/app/services/notice/read/client_service.rb +++ b/app/services/notice/read/client_service.rb @@ -48,7 +48,11 @@ class Notice::Read::ClientService < ApplicationService end end - #private + def platform + Notice.notice_config[:platform] + end + + private def conn @client ||= begin Faraday.new(url: domain) do |req| @@ -69,12 +73,8 @@ class Notice::Read::ClientService < ApplicationService Notice.notice_config[:read_domain] end - def platform - Notice.notice_config[:platform] - end - def api_url - [domain, base_url, "/#{platform}"].join('') + [domain, base_url].join('') end def full_url(api_rest, action='post') diff --git a/app/services/notice/read/count_service.rb b/app/services/notice/read/count_service.rb index 502d57a6..fade1227 100644 --- a/app/services/notice/read/count_service.rb +++ b/app/services/notice/read/count_service.rb @@ -20,6 +20,6 @@ class Notice::Read::CountService < Notice::Read::ClientService end def url - "/count".freeze + "/notification/#{platform}/count".freeze end end \ No newline at end of file diff --git a/app/services/notice/read/list_service.rb b/app/services/notice/read/list_service.rb index e4b1fda4..3f6645d7 100644 --- a/app/services/notice/read/list_service.rb +++ b/app/services/notice/read/list_service.rb @@ -27,6 +27,6 @@ class Notice::Read::ListService < Notice::Read::ClientService end def url - "/list".freeze + "/notification/#{platform}/list".freeze end end \ No newline at end of file diff --git a/app/services/notice/write/change_status_service.rb b/app/services/notice/write/change_status_service.rb index 9091d211..de2c8981 100644 --- a/app/services/notice/write/change_status_service.rb +++ b/app/services/notice/write/change_status_service.rb @@ -9,7 +9,7 @@ class Notice::Write::ChangeStatusService < Notice::Write::ClientService end def call - result = put("", request_params) + result = put(url, request_params) response = render_response(result) end @@ -28,4 +28,8 @@ class Notice::Write::ChangeStatusService < Notice::Write::ClientService }.stringify_keys) end + def url + "/notification/#{platform}".freeze + end + end \ No newline at end of file diff --git a/app/services/notice/write/client_service.rb b/app/services/notice/write/client_service.rb index 51ba5656..c76691cf 100644 --- a/app/services/notice/write/client_service.rb +++ b/app/services/notice/write/client_service.rb @@ -48,7 +48,11 @@ class Notice::Write::ClientService < ApplicationService end end - #private + def platform + Notice.notice_config[:platform] + end + + private def conn @client ||= begin Faraday.new(url: domain) do |req| @@ -69,12 +73,8 @@ class Notice::Write::ClientService < ApplicationService Notice.notice_config[:write_domain] end - def platform - Notice.notice_config[:platform] - end - def api_url - [domain, base_url, "/#{platform}"].join('') + [domain, base_url].join('') end def full_url(api_rest, action='post') diff --git a/app/services/notice/write/create_service.rb b/app/services/notice/write/create_service.rb index 9c1b8492..8dfc8848 100644 --- a/app/services/notice/write/create_service.rb +++ b/app/services/notice/write/create_service.rb @@ -13,7 +13,7 @@ class Notice::Write::CreateService < Notice::Write::ClientService def call return nil if request_receivers.blank? - result = post("", request_params) + result = post(url, request_params) response = render_response(result) end @@ -35,4 +35,8 @@ class Notice::Write::CreateService < Notice::Write::ClientService }.stringify_keys) end + def url + "/notification/#{platform}".freeze + end + end \ No newline at end of file diff --git a/app/services/notice/write/delete_service.rb b/app/services/notice/write/delete_service.rb index 82ab904a..f6358481 100644 --- a/app/services/notice/write/delete_service.rb +++ b/app/services/notice/write/delete_service.rb @@ -8,7 +8,7 @@ class Notice::Write::DeleteService < Notice::Write::ClientService end def call - result = delete("", request_params) + result = delete(url, request_params) response = render_response(result) end @@ -26,4 +26,8 @@ class Notice::Write::DeleteService < Notice::Write::ClientService }.stringify_keys) end + def url + "/notification/#{platform}".freeze + end + end \ No newline at end of file diff --git a/app/services/notice/write/email_create_service.rb b/app/services/notice/write/email_create_service.rb new file mode 100644 index 00000000..0e95e86a --- /dev/null +++ b/app/services/notice/write/email_create_service.rb @@ -0,0 +1,36 @@ +class Notice::Write::EmailCreateService < Notice::Write::ClientService + attr_accessor :receivers, :sender, :content, :subject + + def initialize(receivers, content, subject, sender=-1) + @receivers = receivers + @sender = sender + @content = content + @subject = subject + end + + def call + return nil if request_receivers.blank? + result = post(url, request_params) + response = render_response(result) + end + + private + + def request_receivers + receivers.is_a?(Array) ? receivers.join(",") : receivers + end + + def request_params + Hash.new.merge(data: { + emails: request_receivers, + sender: sender, + content: content, + subject: subject + }.stringify_keys) + end + + def url + "/email/#{platform}".freeze + end + +end \ No newline at end of file From 1c27e9ccd87c28fbc0ad78a333faa3e8adbc8288 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 23 Sep 2021 17:08:53 +0800 Subject: [PATCH 051/135] fix: textarea md editor --- app/views/admins/message_templates/_form.html.erb | 7 +++---- app/views/admins/message_templates/edit.js.erb | 3 ++- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/app/views/admins/message_templates/_form.html.erb b/app/views/admins/message_templates/_form.html.erb index ec640d1d..823c4408 100644 --- a/app/views/admins/message_templates/_form.html.erb +++ b/app/views/admins/message_templates/_form.html.erb @@ -28,11 +28,10 @@
    - <%= f.text_area :email, class:"form-control", rows: "10", cols: "20",placeholer: "邮件模版" %> +
    + <%= f.text_area :email, class:"form-control", style: 'display: none;', rows: "10", cols: "20", placeholer: "请输入邮件模版" %> +
    - - -
    -
    +
    + +
    + <%= f.text_field :notification_url, class: "form-control input-lg", maxlength: "60", placeholder: "请输入站内信跳转地址" %> +
    + +
    +
    -
    - -
    - <%= f.text_field :notification_url, class: "form-control input-lg", maxlength: "60", placeholder: "请输入站内信跳转地址" %> -
    -
    <%= f.submit "确认", class: "btn btn-primary submit-btn" %>
    diff --git a/app/views/admins/message_templates/edit.js.erb b/app/views/admins/message_templates/edit.js.erb index 8d22ddc0..5d797af2 100644 --- a/app/views/admins/message_templates/edit.js.erb +++ b/app/views/admins/message_templates/edit.js.erb @@ -1,2 +1,2 @@ $("#admins-message-templates-content").html("<%= j render partial: 'admins/message_templates/form', locals:{type: 'update'} %>") -createMDEditor('message-template-email-editor', { height: 200, placeholder: '请输入邮件模版' }); +createMDEditor('message-template-email-editor', { height: 500, placeholder: '请输入邮件模版' }); From 3a22ece8717673ee1479e668584ea8c008ba90d9 Mon Sep 17 00:00:00 2001 From: yystopf Date: Sun, 26 Sep 2021 15:00:17 +0800 Subject: [PATCH 054/135] fix: orgainization left receiver email --- app/models/message_template/organization_left.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/models/message_template/organization_left.rb b/app/models/message_template/organization_left.rb index fc6ab230..edf8b32e 100644 --- a/app/models/message_template/organization_left.rb +++ b/app/models/message_template/organization_left.rb @@ -34,7 +34,7 @@ class MessageTemplate::OrganizationLeft < MessageTemplate content.gsub!('{login}', organization&.login) content.gsub!('{organization}', organization&.real_name) - return receiver, title, content + return receiver&.mail, title, content rescue => e Rails.logger.info("MessageTemplate::OrganizationLeft.get_email_message_content [ERROR] #{e}") return '', '', '' From c9a902d41614e84ac2954e12e14da45fd7c3b10c Mon Sep 17 00:00:00 2001 From: chenjing Date: Mon, 27 Sep 2021 10:03:27 +0800 Subject: [PATCH 055/135] fix database.yml.example gitea adapter --- config/database.yml.example | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/database.yml.example b/config/database.yml.example index b0f1f2be..52f6538e 100644 --- a/config/database.yml.example +++ b/config/database.yml.example @@ -18,7 +18,7 @@ default: &default password: 123456 # socket: /var/run/mysqld/mysqld.sock gitea_server: - aadapter: mysql2 + adapter: mysql2 database: gitea_development host: 127.0.0.1 username: root From be5b3864cd6bad91dbf7056805e65c7c7072fcd9 Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 27 Sep 2021 11:25:12 +0800 Subject: [PATCH 056/135] fix: remove repeat message --- app/jobs/send_template_message_job.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/jobs/send_template_message_job.rb b/app/jobs/send_template_message_job.rb index bc080c68..2c463d70 100644 --- a/app/jobs/send_template_message_job.rb +++ b/app/jobs/send_template_message_job.rb @@ -146,7 +146,7 @@ class SendTemplateMessageJob < ApplicationJob user = User.find_by_id(user_id) project = Project.find_by_id(project_id) return unless operator.present? && user.present? && project.present? - receivers = project&.all_managers.where.not(id: operator&.id) + receivers = project&.all_managers.where.not(id: [operator&.id, user&.id]) receivers_string, content, notification_url = MessageTemplate::ProjectMemberJoined.get_message_content(receivers, user, project) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, user_id: user.id, project_id: project.id}) receivers.find_each do |receiver| @@ -159,7 +159,7 @@ class SendTemplateMessageJob < ApplicationJob user = User.find_by_id(user_id) project = Project.find_by_id(project_id) return unless operator.present? && user.present? && project.present? - receivers = project&.all_managers.where.not(id: operator&.id) + receivers = project&.all_managers.where.not(id: [operator&.id, user&.id]) receivers_string, content, notification_url = MessageTemplate::ProjectMemberLeft.get_message_content(receivers, user, project) Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, user_id: user.id, project_id: project.id}) receivers.find_each do |receiver| From a825271a3653bea23bfceaea8f8de44bb9909346 Mon Sep 17 00:00:00 2001 From: jasder Date: Tue, 28 Sep 2021 15:59:36 +0800 Subject: [PATCH 057/135] FIX code bug --- app/models/pull_request.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/app/models/pull_request.rb b/app/models/pull_request.rb index 5c9004a0..ce0cb04a 100644 --- a/app/models/pull_request.rb +++ b/app/models/pull_request.rb @@ -54,8 +54,10 @@ class PullRequest < ApplicationRecord Project.find_by(id: self.fork_project_id) end - def bind_gitea_pull_request!(gitea_pull_number) - update_column(:gitea_number, gitea_pull_number) + def bind_gitea_pull_request!(gitea_pull_number, gitea_pull_id) + update_columns( + gitea_number: gitea_pull_number, + gitea_id: gitea_pull_id) end def merge! From 60720c309ffeef51e2ee92318636a5c4b2f3c448 Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 29 Sep 2021 10:39:50 +0800 Subject: [PATCH 058/135] fix: profile completed --- app/controllers/application_controller.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 11ea87dd..8362dfa7 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -280,7 +280,7 @@ class ApplicationController < ActionController::Base # 资料是否完善 def check_account - if !current_user.profile_completed? + if !current_user. profile_is_completed? #info_url = '/account/profile' tip_exception(402, nil) end From 484194341914d7220ceb30a346cb2a261d862890 Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 29 Sep 2021 10:49:39 +0800 Subject: [PATCH 059/135] fix --- app/controllers/application_controller.rb | 4 ++-- app/services/admins/delete_unit_apply_service.rb | 2 +- app/services/admins/import_user_service.rb | 2 +- app/services/projects/apply_transfer_service.rb | 2 +- app/services/users/apply_authentication_service.rb | 2 +- app/services/users/apply_professional_auth_service.rb | 2 +- app/services/users/update_account_service.rb | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 8362dfa7..3f0fbcc7 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -247,11 +247,11 @@ class ApplicationController < ActionController::Base end def require_profile_completed - tip_exception(411, "请完善资料后再操作") unless User.current.profile_completed + tip_exception(411, "请完善资料后再操作") unless User.current.profile_is_completed? end def require_user_profile_completed(user) - tip_exception(412, "请用户完善资料后再操作") unless user.profile_completed + tip_exception(412, "请用户完善资料后再操作") unless user.profile_is_completed? end # 异常提醒 diff --git a/app/services/admins/delete_unit_apply_service.rb b/app/services/admins/delete_unit_apply_service.rb index a64c8d64..af2e9668 100644 --- a/app/services/admins/delete_unit_apply_service.rb +++ b/app/services/admins/delete_unit_apply_service.rb @@ -18,7 +18,7 @@ class Admins::DeleteUnitApplyService < ApplicationService use_extensions = UserExtension&.where(school_id: @unit_apply.school_id) user_ids = UserExtension&.where(school_id: @unit_apply.school_id)&.pluck(:user_id) - User.where(id: user_ids).update_all(profile_completed: false) + User.where(id: user_ids) use_extensions.update_all(school_id: nil,department_id: nil) @unit_apply&.user&.user_extension&.update_attribute("department_id", nil) diff --git a/app/services/admins/import_user_service.rb b/app/services/admins/import_user_service.rb index 5d4c2e10..2fac412e 100644 --- a/app/services/admins/import_user_service.rb +++ b/app/services/admins/import_user_service.rb @@ -57,7 +57,7 @@ class Admins::ImportUserService < ApplicationService password: '12345678', phone: data.phone, mail: "#{prefix}#{data.student_id}@qq.com", - profile_completed: true + # profile_completed: true } ActiveRecord::Base.transaction do user = User.create!(attr) diff --git a/app/services/projects/apply_transfer_service.rb b/app/services/projects/apply_transfer_service.rb index 2953cd3d..98847a91 100644 --- a/app/services/projects/apply_transfer_service.rb +++ b/app/services/projects/apply_transfer_service.rb @@ -24,7 +24,7 @@ class Projects::ApplyTransferService < ApplicationService raise Error, '仓库标识不正确' if @project.identifier != params[:identifier] raise Error, '该仓库正在迁移' if @project.is_transfering raise Error, '新拥有者不存在' unless @owner.present? - raise Error, '新拥有者资料不完善' if @owner.is_a?(User) && !@owner.profile_completed + raise Error, '新拥有者资料不完善' if @owner.is_a?(User) && !@owner.profile_is_completed? raise Error, '新拥有者已经存在同名仓库!' if Project.where(user_id: @owner.id, identifier: params[:identifier]).present? raise Error, '未拥有转移权限' unless is_permit_owner end diff --git a/app/services/users/apply_authentication_service.rb b/app/services/users/apply_authentication_service.rb index a6b02f43..5e256210 100644 --- a/app/services/users/apply_authentication_service.rb +++ b/app/services/users/apply_authentication_service.rb @@ -7,7 +7,7 @@ class Users::ApplyAuthenticationService < ApplicationService end def call - raise Error, '请先完善基本信息' unless user.profile_completed? + raise Error, '请先完善基本信息' unless user.profile_is_completed? Users::ApplyAuthenticationForm.new(params).validate! # raise Error, '您已经申请过实名认证了' if ApplyUserAuthentication.real_name_auth.processing.exists?(user_id: user.id) diff --git a/app/services/users/apply_professional_auth_service.rb b/app/services/users/apply_professional_auth_service.rb index c9448189..9f3057dd 100644 --- a/app/services/users/apply_professional_auth_service.rb +++ b/app/services/users/apply_professional_auth_service.rb @@ -9,7 +9,7 @@ class Users::ApplyProfessionalAuthService < ApplicationService end def call - raise Error, '请先完善基本信息' unless user.profile_completed? + raise Error, '请先完善基本信息' unless user.profile_is_completed? Users::ApplyProfessionalAuthForm.new(params).validate! # raise Error, '您已经申请过职业认证了' if ApplyUserAuthentication.professional_auth.processing.exists?(user_id: user.id) diff --git a/app/services/users/update_account_service.rb b/app/services/users/update_account_service.rb index 16824a90..8a0b1885 100644 --- a/app/services/users/update_account_service.rb +++ b/app/services/users/update_account_service.rb @@ -43,7 +43,7 @@ class Users::UpdateAccountService < ApplicationService end # 表示资料完整 - user.profile_completed = true + # user.profile_completed = true extension.save! user.save! From 91feb8cf89fb9d127a5e0365a52f76bf11a4dd87 Mon Sep 17 00:00:00 2001 From: yystopf Date: Tue, 7 Sep 2021 18:39:11 +0800 Subject: [PATCH 060/135] add: project branch_slice --- app/controllers/projects_controller.rb | 7 ++++++ .../repository/branches/list_slice_service.rb | 22 +++++++++++++++++++ app/services/repositories/detail_service.rb | 9 +++++++- .../projects/branches_slice.json.jbuilder | 20 +++++++++++++++++ app/views/repositories/detail.json.jbuilder | 9 ++++++++ config/routes.rb | 1 + 6 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 app/services/gitea/repository/branches/list_slice_service.rb create mode 100644 app/views/projects/branches_slice.json.jbuilder diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index 78056bee..b19d2b63 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -86,6 +86,13 @@ class ProjectsController < ApplicationController @branches = result.is_a?(Hash) && result.key?(:status) ? [] : result end + def branches_slice + return @branches = [] unless @project.forge? + + slice_result = Gitea::Repository::Branches::ListSliceService.call(@owner, @project.identifier) + @branches_slice = slice_result.is_a?(Hash) && slice_result.key?(:status) ? [] : slice_result + end + def group_type_list project_statics = ProjectStatistic.first diff --git a/app/services/gitea/repository/branches/list_slice_service.rb b/app/services/gitea/repository/branches/list_slice_service.rb new file mode 100644 index 00000000..6b643831 --- /dev/null +++ b/app/services/gitea/repository/branches/list_slice_service.rb @@ -0,0 +1,22 @@ +class Gitea::Repository::Branches::ListSliceService < Gitea::ClientService + attr_reader :user, :repo + + def initialize(user, repo) + @user = user + @repo = repo + end + + def call + response = get(url, params) + render_200_response(response) + end + + private + def params + Hash.new.merge(token: user.gitea_token) + end + + def url + "/repos/#{user.login}/#{repo}/branches/branches_slice".freeze + end +end diff --git a/app/services/repositories/detail_service.rb b/app/services/repositories/detail_service.rb index d8853cf4..7488ce24 100644 --- a/app/services/repositories/detail_service.rb +++ b/app/services/repositories/detail_service.rb @@ -13,6 +13,7 @@ class Repositories::DetailService < ApplicationService repo: {}, release: [], branch: [], + branch_type: [], tag: [], contributor: [], language: {}, @@ -23,6 +24,7 @@ class Repositories::DetailService < ApplicationService repo: repo_suitable, release: release_suitable, branch: branch_suitable, + branch_slice: branch_slice_suitable, tag: tag_suitable, contributor: contributor_suitable, language: language_suitable, @@ -43,7 +45,12 @@ class Repositories::DetailService < ApplicationService def branch_suitable branches = Gitea::Repository::Branches::ListService.call(@owner, @repo.identifier) - branches.is_a?(Hash) && branches[:status] == :error ? [] : branches + branches.is_a?(Hash) && branches.key?(:status) ? [] : branches + end + + def branch_slice_suitable + branches = Gitea::Repository::Branches::ListSliceService.call(@owner, @repo.identifier) + branches.is_a?(Hash) && branches.key?(:status) == :error ? [] : branches end def tag_suitable diff --git a/app/views/projects/branches_slice.json.jbuilder b/app/views/projects/branches_slice.json.jbuilder new file mode 100644 index 00000000..2731b151 --- /dev/null +++ b/app/views/projects/branches_slice.json.jbuilder @@ -0,0 +1,20 @@ +json.array! @branches_slice do |branch_slice| + json.branch_type branch_slice['branch_name'] + json.list branch_slice['branches'].each do |branch| + json.name branch['name'] + json.user_can_push branch['user_can_push'] + json.user_can_merge branch['user_can_merge'] + json.protected branch['protected'] + json.http_url render_http_url(@project) + json.zip_url render_zip_url(@owner, @repository, branch['name']) + json.tar_url render_tar_url(@owner, @repository, branch['name']) + json.last_commit do + json.sha branch['commit']['id'] + json.message branch['commit']['message'] + json.timestamp render_unix_time(branch['commit']['timestamp']) + json.time_from_now time_from_now(branch['commit']['timestamp']) + json.author branch['commit']['author'] + json.committer branch['commit']['committer'] + end + end +end \ No newline at end of file diff --git a/app/views/repositories/detail.json.jbuilder b/app/views/repositories/detail.json.jbuilder index c00ae346..18b5dd88 100644 --- a/app/views/repositories/detail.json.jbuilder +++ b/app/views/repositories/detail.json.jbuilder @@ -72,6 +72,15 @@ json.branches do end json.total_count @result[:branch].size end +json.branches_slice do + json.list @result[:branch_slice].each do |branch_slice| + json.branch_type branch_slice["branch_name"] + json.list branch_slice["branches"].each do |branch| + json.name branch["name"] + end + end + json.total_count @result[:branch_slice].size +end json.tags do json.list @result[:tag].each do |tag| json.name tag["name"] diff --git a/config/routes.rb b/config/routes.rb index 9c6dda1b..1f029db3 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -416,6 +416,7 @@ Rails.application.routes.draw do member do get :menu_list get :branches + get :branches_slice get :simple get :watchers, to: 'projects#watch_users' get :stargazers, to: 'projects#praise_users' From af7488505db2c5ccc2be7f1a7b730238b11e16a8 Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 8 Sep 2021 09:45:15 +0800 Subject: [PATCH 061/135] add: project commit_slice --- app/controllers/repositories_controller.rb | 5 +++ .../repository/commits/list_slice_service.rb | 42 +++++++++++++++++++ .../repositories/commits_slice.json.jbuilder | 38 +++++++++++++++++ config/routes.rb | 1 + 4 files changed, 86 insertions(+) create mode 100644 app/services/gitea/repository/commits/list_slice_service.rb create mode 100644 app/views/repositories/commits_slice.json.jbuilder diff --git a/app/controllers/repositories_controller.rb b/app/controllers/repositories_controller.rb index 9ef44090..db7be5c7 100644 --- a/app/controllers/repositories_controller.rb +++ b/app/controllers/repositories_controller.rb @@ -107,6 +107,11 @@ class RepositoriesController < ApplicationController sha: params[:sha], page: params[:page], limit: params[:limit], token: current_user&.gitea_token).call 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] @commit = Gitea::Repository::Commits::GetService.call(@owner.login, @repository.identifier, @sha, current_user&.gitea_token) diff --git a/app/services/gitea/repository/commits/list_slice_service.rb b/app/services/gitea/repository/commits/list_slice_service.rb new file mode 100644 index 00000000..04f45f55 --- /dev/null +++ b/app/services/gitea/repository/commits/list_slice_service.rb @@ -0,0 +1,42 @@ +# Get a list of all commits from a repository +class Gitea::Repository::Commits::ListSliceService < Gitea::ClientService + attr_reader :owner, :repo_name, :args + + # sha: SHA or branch to start listing commits from (usually 'master') + # ex: + # Gitea::Repository::Commits::ListService.new(@project.owner.login, @project.identifier, + # sha: params[:sha], page: params[:page], limit: params[:limit], token: current_user&.gitea_token).call + def initialize(owner, repo_name, **args) + @owner = owner + @repo_name = repo_name + @args = args + end + + def call + response = get(url, params) + render_result(response) + end + + private + def params + { sha: args[:sha] || 'master', page: args[:page] || PAGINATE_DEFAULT_PAGE, limit: args[:limit] || PAGINATE_DEFAULT_LIMIT, token: args[:token] || "" } + end + + def url + "/repos/#{owner}/#{repo_name}/commits_slice".freeze + end + + def render_result(response) + case response.status + when 200 + result = {} + headers = response.headers.to_hash + body = JSON.parse(response.body) + total_count = headers["x-total"] + result.merge(total_count: total_count.to_i, body: body) + else + nil + # {status: -1, message: "#{body['message']}"} + end + end +end diff --git a/app/views/repositories/commits_slice.json.jbuilder b/app/views/repositories/commits_slice.json.jbuilder new file mode 100644 index 00000000..e252cda6 --- /dev/null +++ b/app/views/repositories/commits_slice.json.jbuilder @@ -0,0 +1,38 @@ +if @hash_commit.blank? #如果有状态值,则表示报错了 + json.total_count 0 + json.commits [] +else + json.total_count @hash_commit[:total_count] + json.commit_dates do + json.array! @hash_commit[:body] do |commit_date| + json.commit_date commit_date["commit_date"] + json.commits do + json.array! commit_date["Commits"] do |commit| + commiter = commit['committer'] + + forge_user = + if commiter.present? + User.simple_select.find_by(gitea_uid: commiter['id']) + end + + json.sha commit['sha'] + json.message commit['commit']['message'] + json.timestamp render_unix_time(commit['commit']['author']['date']) + json.time_from_now time_from_now(commit['commit']['author']['date']) + if forge_user + json.partial! 'author', user: forge_user + else + json.author do + json.id nil + json.login commit['commit']['author']['name'] + json.type nil + json.name commit['commit']['author']['name'] + json.image_url User::Avatar.get_letter_avatar_url(commit['commit']['author']['name']) + end + end + end + end + end + end + +end diff --git a/config/routes.rb b/config/routes.rb index 1f029db3..2a935b89 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -432,6 +432,7 @@ Rails.application.routes.draw do get :entries match :sub_entries, :via => [:get, :put] get :commits + get :commits_slice get :tags get :contributors post :create_file From 333d6a8ea475eaeb3265c7ced60293602e445ea6 Mon Sep 17 00:00:00 2001 From: yystopf Date: Tue, 14 Sep 2021 10:59:01 +0800 Subject: [PATCH 062/135] add: branch commiter user info --- app/helpers/repositories_helper.rb | 10 +++++++--- app/views/projects/branches.json.jbuilder | 8 ++++++-- app/views/projects/branches_slice.json.jbuilder | 8 ++++++-- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/app/helpers/repositories_helper.rb b/app/helpers/repositories_helper.rb index 7057ac58..d9679cb8 100644 --- a/app/helpers/repositories_helper.rb +++ b/app/helpers/repositories_helper.rb @@ -26,9 +26,13 @@ module RepositoriesHelper end def render_commit_author(author_json) - return nil if author_json.blank? || author_json["id"].blank? - # find_user_by_login author_json['name'] - find_user_by_gitea_uid author_json['id'] + 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? + return find_user_by_login author_json['name'] + end end def readme_render_decode64_content(str, path) diff --git a/app/views/projects/branches.json.jbuilder b/app/views/projects/branches.json.jbuilder index dd722c9d..ad4f4328 100644 --- a/app/views/projects/branches.json.jbuilder +++ b/app/views/projects/branches.json.jbuilder @@ -11,7 +11,11 @@ json.array! @branches do |branch| json.message branch['commit']['message'] json.timestamp render_unix_time(branch['commit']['timestamp']) json.time_from_now time_from_now(branch['commit']['timestamp']) - json.author branch['commit']['author'] - json.committer branch['commit']['committer'] + json.author do + json.partial! 'repositories/commit_author', user: render_commit_author(branch['commit']['author']), name: branch['commit']['author']['name'] + end + json.committer do + json.partial! 'repositories/commit_author', user: render_commit_author(branch['commit']['committer']), name: branch['commit']['committer']['name'] + end end end diff --git a/app/views/projects/branches_slice.json.jbuilder b/app/views/projects/branches_slice.json.jbuilder index 2731b151..31c662a1 100644 --- a/app/views/projects/branches_slice.json.jbuilder +++ b/app/views/projects/branches_slice.json.jbuilder @@ -13,8 +13,12 @@ json.array! @branches_slice do |branch_slice| json.message branch['commit']['message'] json.timestamp render_unix_time(branch['commit']['timestamp']) json.time_from_now time_from_now(branch['commit']['timestamp']) - json.author branch['commit']['author'] - json.committer branch['commit']['committer'] + json.author do + json.partial! 'repositories/commit_author', user: render_commit_author(branch['commit']['author']), name: branch['commit']['author']['name'] + end + json.committer do + json.partial! 'repositories/commit_author', user: render_commit_author(branch['commit']['committer']), name: branch['commit']['committer']['name'] + end end end end \ No newline at end of file From 6466ef523b785bd9741d24779a1ac5107ea232b7 Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 15 Sep 2021 11:47:16 +0800 Subject: [PATCH 063/135] fix --- app/services/repositories/detail_service.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/services/repositories/detail_service.rb b/app/services/repositories/detail_service.rb index 7488ce24..984f10d5 100644 --- a/app/services/repositories/detail_service.rb +++ b/app/services/repositories/detail_service.rb @@ -50,7 +50,7 @@ class Repositories::DetailService < ApplicationService def branch_slice_suitable branches = Gitea::Repository::Branches::ListSliceService.call(@owner, @repo.identifier) - branches.is_a?(Hash) && branches.key?(:status) == :error ? [] : branches + branches.is_a?(Hash) && branches.key?(:status) ? [] : branches end def tag_suitable From ec221240042a9bb775fe19ae6f05d822e5744ca6 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 23 Sep 2021 18:07:46 +0800 Subject: [PATCH 064/135] add: readme by filepath --- app/controllers/repositories_controller.rb | 18 +- .../slate/source/includes/_repositories.md | 57 ++ .../gitea/repository/readme/dir_service.rb | 34 + .../repositories/contributors.json.jbuilder | 2 +- public/docs/api.html | 692 ++++++++++-------- 5 files changed, 510 insertions(+), 293 deletions(-) create mode 100644 app/services/gitea/repository/readme/dir_service.rb diff --git a/app/controllers/repositories_controller.rb b/app/controllers/repositories_controller.rb index db7be5c7..a7e909eb 100644 --- a/app/controllers/repositories_controller.rb +++ b/app/controllers/repositories_controller.rb @@ -125,7 +125,11 @@ class RepositoriesController < ApplicationController end def contributors - @contributors = Gitea::Repository::Contributors::GetService.call(@owner, @repository.identifier) + if params[:filepath].present? + @contributors = [] + else + @contributors = Gitea::Repository::Contributors::GetService.call(@owner, @repository.identifier) + end end def edit @@ -188,10 +192,16 @@ class RepositoriesController < ApplicationController end def readme - result = Gitea::Repository::Readme::GetService.call(@owner.login, @repository.identifier, params[:ref], current_user&.gitea_token) - + 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 @readme = result[:status] === :success ? result[:body] : nil - render json: @readme + + render json: @readme.slice("type", "encoding", "size", "name", "path", "content", "sha") + rescue + render json: nil end def languages diff --git a/app/docs/slate/source/includes/_repositories.md b/app/docs/slate/source/includes/_repositories.md index 1552655e..c27243da 100644 --- a/app/docs/slate/source/includes/_repositories.md +++ b/app/docs/slate/source/includes/_repositories.md @@ -868,6 +868,63 @@ await octokit.request('GET /api/jasder/jasder_test/sub_entries.json') Success Data. +## 获取仓库README文件 +获取仓库README文件 + +> 示例: + +```shell +curl -X GET \ +-d "ref=master" \ +-d "filepath=lib" \ +http://localhost:3000/api/yystopf/csfjkkj/readme.json +``` + +```javascript +await octokit.request('GET /api/yystopf/csfjkkj/readme.json') +``` + +### HTTP 请求 +`GET /api/:owner/:repo/readme.json` + +### 请求参数: +参数 | 必选 | 默认 | 类型 | 字段说明 +--------- | ------- | ------- | -------- | ---------- +|owner |是| |string |用户登录名 | +|repo |是| |string |项目标识identifier | +|ref |否| | string |分支名称、tag名称或是提交记录id,默认为默认分支 | +|filepath |否| | string |子目录名称,默认为空 | + +### 返回字段说明: +参数 | 类型 | 字段说明 +--------- | ----------- | ----------- +|type |string|文件类型, file:文件,dir:文件目录 +|encoding |string |编码 | +|size |int|文件夹或文件大小 单位B +|name |string|文件夹或文件名称| +|path |string|文件夹或文件相对路径| +|content |string|文件内容 +|sha |string|文件commitid + + +> 返回的JSON示例: + +```json +{ + "type": "file", + "encoding": "base64", + "size": 24, + "name": "README.md", + "path": "lib/README.md", + "content": "ZGZhc2RhZGpmIGRrZnNsCgpzZGZkZnMK", + "sha": "860962cd21c60b1a9e07d723080c87c32c18d44a" +} +``` + + + ## 获取仓库webhooks列表 获取仓库webhooks列表 diff --git a/app/services/gitea/repository/readme/dir_service.rb b/app/services/gitea/repository/readme/dir_service.rb new file mode 100644 index 00000000..587fb5d5 --- /dev/null +++ b/app/services/gitea/repository/readme/dir_service.rb @@ -0,0 +1,34 @@ +class Gitea::Repository::Readme::DirService < Gitea::ClientService + attr_reader :owner, :repo, :ref, :dir, :token + + def initialize(owner, repo, dir, ref='', token=nil) + @owner = owner + @repo = repo + @dir = dir + @ref = ref + @token = token + end + + def call + response = get(url, params) + status, message, body = render_response(response) + json_format(status, message, body) + end + + private + def params + Hash.new.merge(token: token, ref: ref) + end + + def url + "/repos/#{owner}/#{repo}/readme/#{dir}".freeze + end + + def json_format(status, message, body) + case status + when 200 then success(body) + when 404 then error(message, 404) + else error(message, status) + end + end +end \ No newline at end of file diff --git a/app/views/repositories/contributors.json.jbuilder b/app/views/repositories/contributors.json.jbuilder index a5edb37e..9165cf94 100644 --- a/app/views/repositories/contributors.json.jbuilder +++ b/app/views/repositories/contributors.json.jbuilder @@ -6,7 +6,7 @@ json.contributors @contributors.each do |contributor| next end json.contributions contributor["contributions"] - json.gid contributor["id"] + # json.gid contributor["id"] json.login user.login json.type user&.type json.name user.real_name diff --git a/public/docs/api.html b/public/docs/api.html index c77c0898..5e3baed1 100644 --- a/public/docs/api.html +++ b/public/docs/api.html @@ -499,6 +499,9 @@
  • 获取仓库代码子目录或者文件
  • +
  • + 获取仓库README文件 +
  • 获取仓库webhooks列表
  • @@ -7247,17 +7250,19 @@ http://localhost:3000//api/jasder/jasder_test/sub_entries.json -

    获取仓库webhooks列表

    -

    获取仓库webhooks列表

    +

    获取仓库README文件

    +

    获取仓库README文件

    示例:

    curl -X GET \
    -http://localhost:3000/api/yystopf/ceshi/webhooks.json
    -
    await octokit.request('GET /api/yystopf/ceshi/webhooks.json')
    +-d "ref=master" \
    +-d "filepath=lib" \
    +http://localhost:3000/api/yystopf/csfjkkj/readme.json
    +
    await octokit.request('GET /api/yystopf/csfjkkj/readme.json')
     

    HTTP 请求

    -

    GET /api/:owner/:repo/webhooks.json

    +

    GET /api/:owner/:repo/readme.json

    请求参数:

    @@ -7282,6 +7287,20 @@ http://localhost:3000/api/yystopf/ceshi/webhooks.json + + + + + + + + + + + + + +
    string 项目标识identifier
    refstring分支名称、tag名称或是提交记录id,默认为默认分支
    filepathstring子目录名称,默认为空

    返回字段说明:

    @@ -7292,6 +7311,103 @@ http://localhost:3000/api/yystopf/ceshi/webhooks.json + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    typestring文件类型, file:文件,dir:文件目录
    encodingstring编码
    sizeint文件夹或文件大小 单位B
    namestring文件夹或文件名称
    pathstring文件夹或文件相对路径
    contentstring文件内容
    shastring文件commitid
    + +
    +

    返回的JSON示例:

    +
    +
    {
    +    "type": "file",
    +    "encoding": "base64",
    +    "size": 24,
    +    "name": "README.md",
    +    "path": "lib/README.md",
    +    "content": "ZGZhc2RhZGpmIGRrZnNsCgpzZGZkZnMK",
    +    "sha": "860962cd21c60b1a9e07d723080c87c32c18d44a"
    +}
    +
    + +

    获取仓库webhooks列表

    +

    获取仓库webhooks列表

    + +
    +

    示例:

    +
    +
    curl -X GET \
    +http://localhost:3000/api/yystopf/ceshi/webhooks.json
    +
    await octokit.request('GET /api/yystopf/ceshi/webhooks.json')
    +

    HTTP 请求

    +

    GET /api/:owner/:repo/webhooks.json

    +

    请求参数:

    + + + + + + + + + + + + + + + + + + + + + + + +
    参数必选默认类型字段说明
    ownerstring用户登录名
    repostring项目标识identifier
    +

    返回字段说明:

    + + + + + + + + @@ -7385,9 +7501,9 @@ http://localhost:3000/api/yystopf/ceshi/webhooks.json
    curl -X GET \
     http://localhost:3000/api/yystopf/ceshi/webhooks/3/edit.json
     
    await octokit.request('GET /api/yystopf/ceshi/webhooks/3/edit.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/:owner/:repo/webhooks/:id/edit.json

    -

    请求参数:

    +

    请求参数:

    参数类型字段说明
    id int id
    @@ -7419,7 +7535,7 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/3/edit.json
    参数webhook ID
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -7620,266 +7736,8 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/3/edit.json
    curl -X POST \
     http://localhost:3000/api/yystopf/ceshi/webhooks.json
     
    await octokit.request('POST /api/yystopf/ceshi/webhooks.json')
    -

    HTTP 请求

    -

    POST /api/:owner/:repo/webhooks.json

    -

    请求参数:

    -
    参数
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    参数必选默认类型字段说明
    ownerstring用户登录名
    repostring项目标识identifier
    webhook.urlstring目标url
    webhook.typestring类型
    webhook.http_methodstringhttp方法, POST和GET
    webhook.content_typestringPOST Content Type
    webhook.secretstring密钥文本
    webhook.activebool是否激活
    webhook.branch_filterstring分支过滤
    webhook.eventsarray触发事件
    - -

    触发事件字段说明

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    参数含义
    create创建分支或标签
    delete分支或标签删除
    fork仓库被fork
    pushgit仓库推送
    issue易修已打开、已关闭、已重新打开或编辑
    issue_assign易修被指派
    issue_label易修标签被更新或删除
    issue_milestone易修被收入里程碑
    issue_comment易修评论
    pull_request合并请求
    pull_request_assign合并请求被指派
    pull_request_label合并请求被贴上标签
    pull_request_milestone合并请求被记录于里程碑中
    pull_request_comment合并请求被评论
    pull_request_review_approved合并请求被批准
    pull_request_review_rejected合并请求被拒绝
    pull_request_review_comment合并请求被提出审查意见
    pull_request_sync合并请求被同步
    repository创建或删除仓库
    release版本发布
    - -
    -

    请求的JSON示例:

    -
    -
    {
    -    "active": true, 
    -    "content_type": "json",
    -    "http_method": "GET",
    -    "secret": "123456",
    -    "url": "http://localhost:10000",
    -    "branch_filter": "*",
    -    "events": ["push"]
    -}
    -

    返回字段说明:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    参数类型字段说明
    idintid
    urlstring地址
    content_typestringPOST Content Type
    is_activebool是否激活
    typestring类型
    eventsarray触发事件
    create_timestring创建时间
    - -
    -

    返回的JSON示例:

    -
    -
    {
    -    "id": 18,
    -    "type": "gitea",
    -    "content_type": "json",
    -    "url": "http://localhost:10000",
    -    "events": [
    -        "push"
    -    ],
    -    "active": true,
    -    "create_time": "2021-07-26 18:53:43"
    -}
    -
    - -

    更新仓库webhook

    -

    更新仓库webhook

    - -
    -

    示例:

    -
    -
    curl -X PATCH \
    -http://localhost:3000/api/yystopf/ceshi/webhooks/7.json
    -
    await octokit.request('PATCH /api/yystopf/ceshi/webhooks/7.json')
     

    HTTP 请求

    -

    PATCH /api/:owner/:repo/webhooks/:id.json

    +

    POST /api/:owner/:repo/webhooks.json

    请求参数:

    @@ -7905,13 +7763,6 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/7.json - - - - - - - @@ -8072,28 +7923,79 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/7.json "events": ["push"] }

    返回字段说明:

    +
    项目标识identifier
    idstringwebhook id
    webhook.url
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数类型字段说明
    idintid
    urlstring地址
    content_typestringPOST Content Type
    is_activebool是否激活
    typestring类型
    eventsarray触发事件
    create_timestring创建时间
    +

    返回的JSON示例:

    {
    -    "status": 0,
    -    "message": "success"
    +    "id": 18,
    +    "type": "gitea",
    +    "content_type": "json",
    +    "url": "http://localhost:10000",
    +    "events": [
    +        "push"
    +    ],
    +    "active": true,
    +    "create_time": "2021-07-26 18:53:43"
     }
     
    -

    删除仓库webhook

    -

    删除仓库webhook

    +

    更新仓库webhook

    +

    更新仓库webhook

    示例:

    -
    curl -X DELETE \
    +
    curl -X PATCH \
     http://localhost:3000/api/yystopf/ceshi/webhooks/7.json
    -
    await octokit.request('DELETE /api/yystopf/ceshi/webhooks/7.json')
    +
    await octokit.request('PATCH /api/yystopf/ceshi/webhooks/7.json')
     

    HTTP 请求

    -

    DELETE /api/:owner/:repo/webhooks/:id.json

    +

    PATCH /api/:owner/:repo/webhooks/:id.json

    请求参数:

    @@ -8125,8 +8027,222 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/7.json + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    string webhook id
    webhook.urlstring目标url
    webhook.typestring类型
    webhook.http_methodstringhttp方法, POST和GET
    webhook.content_typestringPOST Content Type
    webhook.secretstring密钥文本
    webhook.activebool是否激活
    webhook.branch_filterstring分支过滤
    webhook.eventsarray触发事件
    -

    返回字段说明:

    + +

    触发事件字段说明

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数含义
    create创建分支或标签
    delete分支或标签删除
    fork仓库被fork
    pushgit仓库推送
    issue易修已打开、已关闭、已重新打开或编辑
    issue_assign易修被指派
    issue_label易修标签被更新或删除
    issue_milestone易修被收入里程碑
    issue_comment易修评论
    pull_request合并请求
    pull_request_assign合并请求被指派
    pull_request_label合并请求被贴上标签
    pull_request_milestone合并请求被记录于里程碑中
    pull_request_comment合并请求被评论
    pull_request_review_approved合并请求被批准
    pull_request_review_rejected合并请求被拒绝
    pull_request_review_comment合并请求被提出审查意见
    pull_request_sync合并请求被同步
    repository创建或删除仓库
    release版本发布
    + +
    +

    请求的JSON示例:

    +
    +
    {
    +    "active": true, 
    +    "content_type": "json",
    +    "http_method": "GET",
    +    "secret": "123456",
    +    "url": "http://localhost:10000",
    +    "branch_filter": "*",
    +    "events": ["push"]
    +}
    +

    返回字段说明:

    +
    +

    返回的JSON示例:

    +
    +
    {
    +    "status": 0,
    +    "message": "success"
    +}
    +
    + +

    删除仓库webhook

    +

    删除仓库webhook

    + +
    +

    示例:

    +
    +
    curl -X DELETE \
    +http://localhost:3000/api/yystopf/ceshi/webhooks/7.json
    +
    await octokit.request('DELETE /api/yystopf/ceshi/webhooks/7.json')
    +

    HTTP 请求

    +

    DELETE /api/:owner/:repo/webhooks/:id.json

    +

    请求参数:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数必选默认类型字段说明
    ownerstring用户登录名
    repostring项目标识identifier
    idstringwebhook id
    +

    返回字段说明:

    返回的JSON示例:

    @@ -8147,9 +8263,9 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/7.json
    curl -X GET \
     http://localhost:3000/api/yystopf/ceshi/webhooks/3/tasks.json
     
    await octokit.request('GET /api/yystopf/ceshi/webhooks/3/tasks.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/:owner/:repo/webhooks/:id/tasks.json

    -

    请求参数:

    +

    请求参数:

    @@ -8181,7 +8297,7 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/3/tasks.json
    参数webhook ID
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -8418,9 +8534,9 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/3/tasks.json
    curl -X POST \
     http://localhost:3000/api/yystopf/ceshi/webhooks/3/test.json
     
    await octokit.request('POST /api/yystopf/ceshi/webhooks/3/test.json')
    -

    HTTP 请求

    +

    HTTP 请求

    POST /api/:owner/:repo/webhooks/:id/test.json

    -

    请求参数:

    +

    请求参数:

    参数
    @@ -8452,7 +8568,7 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/3/test.json
    参数webhook ID
    -

    返回字段说明:

    +

    返回字段说明:

    返回的JSON示例:

    From 206bba1c4939d728ddce3e6d8d9083ba880f79bb Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 23 Sep 2021 18:17:52 +0800 Subject: [PATCH 065/135] add: contributors by filepath --- .../slate/source/includes/_repositories.md | 65 ++ public/docs/api.html | 697 ++++++++++-------- 2 files changed, 474 insertions(+), 288 deletions(-) diff --git a/app/docs/slate/source/includes/_repositories.md b/app/docs/slate/source/includes/_repositories.md index c27243da..eaae1074 100644 --- a/app/docs/slate/source/includes/_repositories.md +++ b/app/docs/slate/source/includes/_repositories.md @@ -924,6 +924,71 @@ await octokit.request('GET /api/yystopf/csfjkkj/readme.json') Success Data. +## 获取仓库贡献者 +获取仓库贡献者 + +> 示例: + +```shell +curl -X GET \ +-d "ref=master" \ +-d "filepath=lib" \ +http://localhost:3000/api/yystopf/csfjkkj/contributors.json +``` + +```javascript +await octokit.request('GET /api/yystopf/csfjkkj/contributors.json') +``` + +### HTTP 请求 +`GET /api/:owner/:repo/contributors.json` + +### 请求参数: +参数 | 必选 | 默认 | 类型 | 字段说明 +--------- | ------- | ------- | -------- | ---------- +|owner |是| |string |用户登录名 | +|repo |是| |string |项目标识identifier | +|ref |否| | string |分支名称、tag名称或是提交记录id,默认为整个仓库 | +|filepath |否| | string |子目录名称,默认为空 | + +### 返回字段说明: +参数 | 类型 | 字段说明 +--------- | ----------- | ----------- +|total_count |integer|贡献者数量| +|contributions |integer|贡献数量| +|login |string |用户登录名 | +|type |string|用户类型 | +|name |string|用户昵称| +|image_url |string|用户头像| + + +> 返回的JSON示例: + +```json +{ + "contributors": [ + { + "contributions": 5, + "login": "testforge2", + "type": "User", + "name": "testforge2", + "image_url": "system/lets/letter_avatars/2/T/236_177_85/120.png" + }, + { + "contributions": 79, + "login": "yystopf", + "type": "User", + "name": "yystopf", + "image_url": "system/lets/letter_avatars/2/Y/241_125_89/120.png" + } + ], + "total_count": 2 +} +``` + + ## 获取仓库webhooks列表 获取仓库webhooks列表 diff --git a/public/docs/api.html b/public/docs/api.html index 5e3baed1..4ec491b4 100644 --- a/public/docs/api.html +++ b/public/docs/api.html @@ -502,6 +502,9 @@
  • 获取仓库README文件
  • +
  • + 获取仓库贡献者 +
  • 获取仓库webhooks列表
  • @@ -7363,17 +7366,19 @@ http://localhost:3000/api/yystopf/csfjkkj/readme.json -

    获取仓库webhooks列表

    -

    获取仓库webhooks列表

    +

    获取仓库贡献者

    +

    获取仓库贡献者

    示例:

    curl -X GET \
    -http://localhost:3000/api/yystopf/ceshi/webhooks.json
    -
    await octokit.request('GET /api/yystopf/ceshi/webhooks.json')
    +-d "ref=master" \
    +-d "filepath=lib" \
    +http://localhost:3000/api/yystopf/csfjkkj/contributors.json
    +
    await octokit.request('GET /api/yystopf/csfjkkj/contributors.json')
     

    HTTP 请求

    -

    GET /api/:owner/:repo/webhooks.json

    +

    GET /api/:owner/:repo/contributors.json

    请求参数:

    @@ -7398,6 +7403,20 @@ http://localhost:3000/api/yystopf/ceshi/webhooks.json + + + + + + + + + + + + + +
    string 项目标识identifier
    refstring分支名称、tag名称或是提交记录id,默认为整个仓库
    filepathstring子目录名称,默认为空

    返回字段说明:

    @@ -7408,6 +7427,108 @@ http://localhost:3000/api/yystopf/ceshi/webhooks.json + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    total_countinteger贡献者数量
    contributionsinteger贡献数量
    loginstring用户登录名
    typestring用户类型
    namestring用户昵称
    image_urlstring用户头像
    + +
    +

    返回的JSON示例:

    +
    +
    {
    +    "contributors": [
    +        {
    +            "contributions": 5,
    +            "login": "testforge2",
    +            "type": "User",
    +            "name": "testforge2",
    +            "image_url": "system/lets/letter_avatars/2/T/236_177_85/120.png"
    +        },
    +        {
    +            "contributions": 79,
    +            "login": "yystopf",
    +            "type": "User",
    +            "name": "yystopf",
    +            "image_url": "system/lets/letter_avatars/2/Y/241_125_89/120.png"
    +        }
    +    ],
    +    "total_count": 2
    +}
    +
    + +

    获取仓库webhooks列表

    +

    获取仓库webhooks列表

    + +
    +

    示例:

    +
    +
    curl -X GET \
    +http://localhost:3000/api/yystopf/ceshi/webhooks.json
    +
    await octokit.request('GET /api/yystopf/ceshi/webhooks.json')
    +

    HTTP 请求

    +

    GET /api/:owner/:repo/webhooks.json

    +

    请求参数:

    + + + + + + + + + + + + + + + + + + + + + + + +
    参数必选默认类型字段说明
    ownerstring用户登录名
    repostring项目标识identifier
    +

    返回字段说明:

    + + + + + + + + @@ -7501,9 +7622,9 @@ http://localhost:3000/api/yystopf/ceshi/webhooks.json
    curl -X GET \
     http://localhost:3000/api/yystopf/ceshi/webhooks/3/edit.json
     
    await octokit.request('GET /api/yystopf/ceshi/webhooks/3/edit.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/:owner/:repo/webhooks/:id/edit.json

    -

    请求参数:

    +

    请求参数:

    参数类型字段说明
    id int id
    @@ -7535,7 +7656,7 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/3/edit.json
    参数webhook ID
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -7736,266 +7857,8 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/3/edit.json
    curl -X POST \
     http://localhost:3000/api/yystopf/ceshi/webhooks.json
     
    await octokit.request('POST /api/yystopf/ceshi/webhooks.json')
    -

    HTTP 请求

    -

    POST /api/:owner/:repo/webhooks.json

    -

    请求参数:

    -
    参数
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    参数必选默认类型字段说明
    ownerstring用户登录名
    repostring项目标识identifier
    webhook.urlstring目标url
    webhook.typestring类型
    webhook.http_methodstringhttp方法, POST和GET
    webhook.content_typestringPOST Content Type
    webhook.secretstring密钥文本
    webhook.activebool是否激活
    webhook.branch_filterstring分支过滤
    webhook.eventsarray触发事件
    - -

    触发事件字段说明

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    参数含义
    create创建分支或标签
    delete分支或标签删除
    fork仓库被fork
    pushgit仓库推送
    issue易修已打开、已关闭、已重新打开或编辑
    issue_assign易修被指派
    issue_label易修标签被更新或删除
    issue_milestone易修被收入里程碑
    issue_comment易修评论
    pull_request合并请求
    pull_request_assign合并请求被指派
    pull_request_label合并请求被贴上标签
    pull_request_milestone合并请求被记录于里程碑中
    pull_request_comment合并请求被评论
    pull_request_review_approved合并请求被批准
    pull_request_review_rejected合并请求被拒绝
    pull_request_review_comment合并请求被提出审查意见
    pull_request_sync合并请求被同步
    repository创建或删除仓库
    release版本发布
    - -
    -

    请求的JSON示例:

    -
    -
    {
    -    "active": true, 
    -    "content_type": "json",
    -    "http_method": "GET",
    -    "secret": "123456",
    -    "url": "http://localhost:10000",
    -    "branch_filter": "*",
    -    "events": ["push"]
    -}
    -

    返回字段说明:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    参数类型字段说明
    idintid
    urlstring地址
    content_typestringPOST Content Type
    is_activebool是否激活
    typestring类型
    eventsarray触发事件
    create_timestring创建时间
    - -
    -

    返回的JSON示例:

    -
    -
    {
    -    "id": 18,
    -    "type": "gitea",
    -    "content_type": "json",
    -    "url": "http://localhost:10000",
    -    "events": [
    -        "push"
    -    ],
    -    "active": true,
    -    "create_time": "2021-07-26 18:53:43"
    -}
    -
    - -

    更新仓库webhook

    -

    更新仓库webhook

    - -
    -

    示例:

    -
    -
    curl -X PATCH \
    -http://localhost:3000/api/yystopf/ceshi/webhooks/7.json
    -
    await octokit.request('PATCH /api/yystopf/ceshi/webhooks/7.json')
     

    HTTP 请求

    -

    PATCH /api/:owner/:repo/webhooks/:id.json

    +

    POST /api/:owner/:repo/webhooks.json

    请求参数:

    @@ -8021,13 +7884,6 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/7.json - - - - - - - @@ -8188,28 +8044,79 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/7.json "events": ["push"] }

    返回字段说明:

    +
    项目标识identifier
    idstringwebhook id
    webhook.url
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数类型字段说明
    idintid
    urlstring地址
    content_typestringPOST Content Type
    is_activebool是否激活
    typestring类型
    eventsarray触发事件
    create_timestring创建时间
    +

    返回的JSON示例:

    {
    -    "status": 0,
    -    "message": "success"
    +    "id": 18,
    +    "type": "gitea",
    +    "content_type": "json",
    +    "url": "http://localhost:10000",
    +    "events": [
    +        "push"
    +    ],
    +    "active": true,
    +    "create_time": "2021-07-26 18:53:43"
     }
     
    -

    删除仓库webhook

    -

    删除仓库webhook

    +

    更新仓库webhook

    +

    更新仓库webhook

    示例:

    -
    curl -X DELETE \
    +
    curl -X PATCH \
     http://localhost:3000/api/yystopf/ceshi/webhooks/7.json
    -
    await octokit.request('DELETE /api/yystopf/ceshi/webhooks/7.json')
    +
    await octokit.request('PATCH /api/yystopf/ceshi/webhooks/7.json')
     

    HTTP 请求

    -

    DELETE /api/:owner/:repo/webhooks/:id.json

    +

    PATCH /api/:owner/:repo/webhooks/:id.json

    请求参数:

    @@ -8241,8 +8148,222 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/7.json + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    string webhook id
    webhook.urlstring目标url
    webhook.typestring类型
    webhook.http_methodstringhttp方法, POST和GET
    webhook.content_typestringPOST Content Type
    webhook.secretstring密钥文本
    webhook.activebool是否激活
    webhook.branch_filterstring分支过滤
    webhook.eventsarray触发事件
    -

    返回字段说明:

    + +

    触发事件字段说明

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数含义
    create创建分支或标签
    delete分支或标签删除
    fork仓库被fork
    pushgit仓库推送
    issue易修已打开、已关闭、已重新打开或编辑
    issue_assign易修被指派
    issue_label易修标签被更新或删除
    issue_milestone易修被收入里程碑
    issue_comment易修评论
    pull_request合并请求
    pull_request_assign合并请求被指派
    pull_request_label合并请求被贴上标签
    pull_request_milestone合并请求被记录于里程碑中
    pull_request_comment合并请求被评论
    pull_request_review_approved合并请求被批准
    pull_request_review_rejected合并请求被拒绝
    pull_request_review_comment合并请求被提出审查意见
    pull_request_sync合并请求被同步
    repository创建或删除仓库
    release版本发布
    + +
    +

    请求的JSON示例:

    +
    +
    {
    +    "active": true, 
    +    "content_type": "json",
    +    "http_method": "GET",
    +    "secret": "123456",
    +    "url": "http://localhost:10000",
    +    "branch_filter": "*",
    +    "events": ["push"]
    +}
    +

    返回字段说明:

    +
    +

    返回的JSON示例:

    +
    +
    {
    +    "status": 0,
    +    "message": "success"
    +}
    +
    + +

    删除仓库webhook

    +

    删除仓库webhook

    + +
    +

    示例:

    +
    +
    curl -X DELETE \
    +http://localhost:3000/api/yystopf/ceshi/webhooks/7.json
    +
    await octokit.request('DELETE /api/yystopf/ceshi/webhooks/7.json')
    +

    HTTP 请求

    +

    DELETE /api/:owner/:repo/webhooks/:id.json

    +

    请求参数:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数必选默认类型字段说明
    ownerstring用户登录名
    repostring项目标识identifier
    idstringwebhook id
    +

    返回字段说明:

    返回的JSON示例:

    @@ -8263,9 +8384,9 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/7.json
    curl -X GET \
     http://localhost:3000/api/yystopf/ceshi/webhooks/3/tasks.json
     
    await octokit.request('GET /api/yystopf/ceshi/webhooks/3/tasks.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/:owner/:repo/webhooks/:id/tasks.json

    -

    请求参数:

    +

    请求参数:

    @@ -8297,7 +8418,7 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/3/tasks.json
    参数webhook ID
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -8534,9 +8655,9 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/3/tasks.json
    curl -X POST \
     http://localhost:3000/api/yystopf/ceshi/webhooks/3/test.json
     
    await octokit.request('POST /api/yystopf/ceshi/webhooks/3/test.json')
    -

    HTTP 请求

    +

    HTTP 请求

    POST /api/:owner/:repo/webhooks/:id/test.json

    -

    请求参数:

    +

    请求参数:

    参数
    @@ -8568,7 +8689,7 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/3/test.json
    参数webhook ID
    -

    返回字段说明:

    +

    返回字段说明:

    返回的JSON示例:

    From bbcca413c6a379e778107c9319dd886f35ddf7cf Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 23 Sep 2021 18:57:16 +0800 Subject: [PATCH 066/135] add: tags commiter message --- .../slate/source/includes/_repositories.md | 78 ++ app/helpers/application_helper.rb | 4 + app/helpers/repositories_helper.rb | 4 +- app/views/repositories/tags.json.jbuilder | 5 + public/docs/api.html | 920 ++++++++++-------- 5 files changed, 615 insertions(+), 396 deletions(-) diff --git a/app/docs/slate/source/includes/_repositories.md b/app/docs/slate/source/includes/_repositories.md index eaae1074..81dbe144 100644 --- a/app/docs/slate/source/includes/_repositories.md +++ b/app/docs/slate/source/includes/_repositories.md @@ -274,6 +274,84 @@ await octokit.request('GET /api/yystopf/ceshi/detail.json') } ``` +## 仓库标签列表 +仓库标签列表 + +> 示例: + +```shell +curl -X GET http://localhost:3000/api/yystopf/csfjkkj/tags.json +``` + +```javascript +await octokit.request('GET /api/yystopf/csfjkkj/tags.json') +``` + +### HTTP 请求 +`GET /api/:owner/:repo/tags.json` + +### 请求参数: +参数 | 必选 | 默认 | 类型 | 字段说明 +--------- | ------- | ------- | -------- | ---------- +|owner |是| |string |用户登录名 | +|repo |是| |string |项目标识identifier | + + +### 返回字段说明: +参数 | 类型 | 字段说明 +--------- | ----------- | ----------- +|id |int |标签id | +|name |string|标签名称| +|zipball_url |string|标签zip包下载地址| +|tarball_url |string|标签tar包下载地址| +|commit |object|标签最后一个commit| +|commit.sha |string|commit的id| +|commit.message |string|commit的提交信息| +|commit.time_ago|string|commit的提交时间| +|commit.commiter|object|commit的提交者| + + +> 返回的JSON示例: + +```json +[ + { + "name": "v2.0.0", + "id": "c7d0873ee41796d1a0e193063095ccf539a9bf31", + "zipball_url": "http://localhost:3000/api/yystopf/csfjkkj/archive/v2.0.0.zip", + "tarball_url": "http://localhost:3000/api/yystopf/csfjkkj/archive/v2.0.0.tar.gz", + "commit": { + "sha": "08fe383f1e5ebe2e2a384a8ea3ee890a758c7cd7", + "message": "add\n", + "time_ago": "4小时前", + "committer": { + "id": 4, + "login": "testforge1", + "name": "testforge1", + "image_url": "system/lets/letter_avatars/2/T/19_237_174/120.png" + } + } + }, + { + "name": "v1.0.0", + "id": "12168ad39c3ef201a445a2db181a3e43d50e40dd", + "zipball_url": "http://localhost:3000/api/yystopf/csfjkkj/archive/v1.0.0.zip", + "tarball_url": "http://localhost:3000/api/yystopf/csfjkkj/archive/v1.0.0.tar.gz", + "commit": { + "sha": "5291b5e45a377c1f7710cc6647259887ed7aaccf", + "message": "ADD file via upload\n", + "time_ago": "9天前", + "committer": { + "id": 2, + "login": "yystopf", + "name": "heh", + "image_url": "system/lets/letter_avatars/2/H/188_239_142/120.png" + } + } + } +] +``` + ## 编辑仓库信息 编辑仓库信息 diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 72f3f341..c37fd59d 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -434,6 +434,10 @@ module ApplicationHelper User.find_by_login login end + def find_user_by_login_and_mail(login, mail) + User.find_by(login: login, mail: mail) + end + def find_user_by_gitea_uid(gitea_uid) User.find_by(gitea_uid: gitea_uid) end diff --git a/app/helpers/repositories_helper.rb b/app/helpers/repositories_helper.rb index d9679cb8..ee60b64a 100644 --- a/app/helpers/repositories_helper.rb +++ b/app/helpers/repositories_helper.rb @@ -30,8 +30,8 @@ module RepositoriesHelper if author_json["id"].present? return find_user_by_gitea_uid author_json['id'] end - if author_json["id"].nil? && author_json["name"].present? - return find_user_by_login author_json['name'] + 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 diff --git a/app/views/repositories/tags.json.jbuilder b/app/views/repositories/tags.json.jbuilder index 9db3ff93..011fad46 100644 --- a/app/views/repositories/tags.json.jbuilder +++ b/app/views/repositories/tags.json.jbuilder @@ -6,6 +6,11 @@ json.array! @tags do |tag| json.tarball_url render_tar_url(@owner, @repository, tag['name']) json.commit do json.sha tag['commit']['sha'] + json.message tag['commit_message'] + json.time_ago time_from_now(tag['commit_time'].to_time) + json.committer do + json.partial! 'commit_author', user: render_commit_author(tag['commiter']), name: tag['commiter']['name'] + end end end end diff --git a/public/docs/api.html b/public/docs/api.html index 4ec491b4..763134f4 100644 --- a/public/docs/api.html +++ b/public/docs/api.html @@ -469,6 +469,9 @@
  • 仓库详情(新版)
  • +
  • + 仓库标签列表 +
  • 编辑仓库信息
  • @@ -6185,16 +6188,16 @@ http://localhost:3000/api/ceshi1/ceshi_repo1/applied_transfer_projects/organizat "Shell": "0.1%" } } -

    编辑仓库信息

    -

    编辑仓库信息

    +

    仓库标签列表

    +

    仓库标签列表

    示例:

    -
    curl -X GET http://localhost:3000/api/jasder/jasder_test/edit.json
    -
    await octokit.request('GET /api/jasder/jasder_test/edit.json')
    +
    curl -X GET http://localhost:3000/api/yystopf/csfjkkj/tags.json
    +
    await octokit.request('GET /api/yystopf/csfjkkj/tags.json')
     

    HTTP 请求

    -

    GET /api/:owner/:repo/edit.json

    +

    GET /api/:owner/:repo/tags.json

    请求参数:

    @@ -6229,6 +6232,135 @@ http://localhost:3000/api/ceshi1/ceshi_repo1/applied_transfer_projects/organizat + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    idint标签id
    namestring标签名称
    zipball_urlstring标签zip包下载地址
    tarball_urlstring标签tar包下载地址
    commitobject标签最后一个commit
    commit.shastringcommit的id
    commit.messagestringcommit的提交信息
    commit.time_agostringcommit的提交时间
    commit.commiterobjectcommit的提交者
    + +
    +

    返回的JSON示例:

    +
    +
    [
    +    {
    +        "name": "v2.0.0",
    +        "id": "c7d0873ee41796d1a0e193063095ccf539a9bf31",
    +        "zipball_url": "http://localhost:3000/api/yystopf/csfjkkj/archive/v2.0.0.zip",
    +        "tarball_url": "http://localhost:3000/api/yystopf/csfjkkj/archive/v2.0.0.tar.gz",
    +        "commit": {
    +            "sha": "08fe383f1e5ebe2e2a384a8ea3ee890a758c7cd7",
    +            "message": "add\n",
    +            "time_ago": "4小时前",
    +            "committer": {
    +                "id": 4,
    +                "login": "testforge1",
    +                "name": "testforge1",
    +                "image_url": "system/lets/letter_avatars/2/T/19_237_174/120.png"
    +            }
    +        }
    +    },
    +    {
    +        "name": "v1.0.0",
    +        "id": "12168ad39c3ef201a445a2db181a3e43d50e40dd",
    +        "zipball_url": "http://localhost:3000/api/yystopf/csfjkkj/archive/v1.0.0.zip",
    +        "tarball_url": "http://localhost:3000/api/yystopf/csfjkkj/archive/v1.0.0.tar.gz",
    +        "commit": {
    +            "sha": "5291b5e45a377c1f7710cc6647259887ed7aaccf",
    +            "message": "ADD file via upload\n",
    +            "time_ago": "9天前",
    +            "committer": {
    +                "id": 2,
    +                "login": "yystopf",
    +                "name": "heh",
    +                "image_url": "system/lets/letter_avatars/2/H/188_239_142/120.png"
    +            }
    +        }
    +    }
    +]
    +

    编辑仓库信息

    +

    编辑仓库信息

    + +
    +

    示例:

    +
    +
    curl -X GET http://localhost:3000/api/jasder/jasder_test/edit.json
    +
    await octokit.request('GET /api/jasder/jasder_test/edit.json')
    +

    HTTP 请求

    +

    GET /api/:owner/:repo/edit.json

    +

    请求参数:

    + + + + + + + + + + + + + + + + + + + + + + + +
    参数必选默认类型字段说明
    ownerstring用户登录名
    repostring项目标识identifier
    +

    返回字段说明:

    + + + + + + + + @@ -6297,9 +6429,9 @@ http://localhost:3000/api/ceshi1/ceshi_repo1/applied_transfer_projects/organizat -d"private=true"\ http://localhost:3000/api/jasder/jasder_test.json
    await octokit.request('PATCH /api/jasder/jasder_test.json')
    -

    HTTP 请求

    +

    HTTP 请求

    PATCH /api/:owner/:repo

    -

    请求参数:

    +

    请求参数:

    参数类型字段说明
    identifier string 仓库标识
    @@ -6359,7 +6491,7 @@ http://localhost:3000/api/jasder/jasder_test.json
    参数项目是否私有, true:为私有,false: 公开,默认为公开
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -6424,9 +6556,9 @@ http://localhost:3000/api/jasder/jasder_test.json
    curl -X DELETE http://localhost:3000/api/jasder/jasder_test.json
     
    await octokit.request('DELETE /api/jasder/jasder_test.json')
    -

    HTTP 请求

    +

    HTTP 请求

    PATCH /api/:owner/:repo

    -

    请求参数:

    +

    请求参数:

    参数
    @@ -6451,7 +6583,7 @@ http://localhost:3000/api/jasder/jasder_test.json
    参数项目标识identifier
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -6492,83 +6624,8 @@ http://localhost:3000/api/jasder/jasder_test.json -d"user_id=12"\ http://localhost:3000/api/jasder/jasder_test/collaborators.json
    await octokit.request('POST /api/jasder/jasder_test/collaborators.json')
    -

    HTTP 请求

    -

    POST /api/:owner/:repo/collaborators.json

    -

    请求参数:

    -
    参数
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    参数必选默认类型字段说明
    ownerstring用户登录名
    repostring项目标识identifier
    user_idint用户id
    -

    返回字段说明:

    - - - - - - - - - - - - - - - - - -
    参数类型字段说明
    statusint返回状态, 0: 表示操作成功
    messagestring返回信息说明
    - -
    -

    返回的JSON示例:

    -
    -
    {
    -  "status": 0,
    -  "message": "success"
    -}
    -
    - -

    删除仓库成员

    -

    仓库中删除成员操作

    - -
    -

    示例:

    -
    -
    curl -X DELETE \
    --d "user_id=12" \
    -http://localhost:3000/api/jasder/jasder_test/collaborators.json
    -
    await octokit.request('DELETE /api/jasder/jasder_test/collaborators.json')
     

    HTTP 请求

    -

    DELETE /api/:owner/:repo/collaborators.json

    +

    POST /api/:owner/:repo/collaborators.json

    请求参数:

    @@ -6621,6 +6678,81 @@ http://localhost:3000/api/jasder/jasder_test/collaborators.json
    +
    +

    返回的JSON示例:

    +
    +
    {
    +  "status": 0,
    +  "message": "success"
    +}
    +
    + +

    删除仓库成员

    +

    仓库中删除成员操作

    + +
    +

    示例:

    +
    +
    curl -X DELETE \
    +-d "user_id=12" \
    +http://localhost:3000/api/jasder/jasder_test/collaborators.json
    +
    await octokit.request('DELETE /api/jasder/jasder_test/collaborators.json')
    +

    HTTP 请求

    +

    DELETE /api/:owner/:repo/collaborators.json

    +

    请求参数:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数必选默认类型字段说明
    ownerstring用户登录名
    repostring项目标识identifier
    user_idint用户id
    +

    返回字段说明:

    + + + + + + + + + + + + + + + + + +
    参数类型字段说明
    statusint返回状态, 0: 表示操作成功
    messagestring返回信息说明
    +

    返回的JSON示例:

    @@ -6643,9 +6775,9 @@ http://localhost:3000/api/jasder/jasder_test/collaborators.json -d "role=Developer" \ http://localhost:3000/api/jasder/jasder_test/change_role.json
    await octokit.request('PUT /api/jasder/jasder_test/change_role.json')
    -

    HTTP 请求

    +

    HTTP 请求

    PUT /api/:owner/:repo/change_role.json

    -

    请求参数:

    +

    请求参数:

    @@ -6684,7 +6816,7 @@ http://localhost:3000/api/jasder/jasder_test/change_role.json
    参数取值范围:"Manager", "Developer", "Reporter";分别为项目管理人员(拥有所有操作权限)、项目开发人员(只拥有读写权限)、项目报告人员(只拥有读权限)
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -6726,9 +6858,9 @@ http://localhost:3000/api/jasder/jasder_test/change_role.json -d"limit=5"\ http://localhost:3000/api/jasder/jasder_test/collaborators.json
    await octokit.request('GET /api/jasder/jasder_test/collaborators.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/:owner/:repo/collaborators.json

    -

    请求参数:

    +

    请求参数:

    参数
    @@ -6767,7 +6899,7 @@ http://localhost:3000/api/jasder/jasder_test/collaborators.json
    参数每页多少条数据,默认15条
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -6855,9 +6987,9 @@ http://localhost:3000/api/jasder/jasder_test/collaborators.json -d"ref=develop"\ http://localhost:3000/api/yystopf/ceshi/files.json
    await octokit.request('GET /api/yystopf/ceshi/files.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/:owner/:repo/files

    -

    请求参数:

    +

    请求参数:

    参数
    @@ -6896,7 +7028,7 @@ http://localhost:3000/api/yystopf/ceshi/files.json
    参数分支名,默认为仓库默认分支
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -6978,9 +7110,9 @@ http://localhost:3000/api/yystopf/ceshi/files.json -d"ref=develop"\ http://localhost:3000//api/jasder/jasder_test/entries.json
    await octokit.request('GET /api/jasder/jasder_test/entries.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/:owner/:repo/entries.json

    -

    请求参数:

    +

    请求参数:

    参数
    @@ -7012,7 +7144,7 @@ http://localhost:3000//api/jasder/jasder_test/entries.json
    参数分支名称、tag名称或是提交记录id,默认为master分支
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -7126,9 +7258,9 @@ http://localhost:3000//api/jasder/jasder_test/entries.json -d"filepath=file"\ http://localhost:3000//api/jasder/jasder_test/sub_entries.json
    await octokit.request('GET /api/jasder/jasder_test/sub_entries.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/:owner/:repo/sub_entries.json

    -

    请求参数:

    +

    请求参数:

    参数
    @@ -7167,7 +7299,7 @@ http://localhost:3000//api/jasder/jasder_test/sub_entries.json
    参数分支名称、tag名称或是提交记录id,默认为master分支
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -7264,9 +7396,9 @@ http://localhost:3000//api/jasder/jasder_test/sub_entries.json -d"filepath=lib"\ http://localhost:3000/api/yystopf/csfjkkj/readme.json
    await octokit.request('GET /api/yystopf/csfjkkj/readme.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/:owner/:repo/readme.json

    -

    请求参数:

    +

    请求参数:

    参数
    @@ -7305,7 +7437,7 @@ http://localhost:3000/api/yystopf/csfjkkj/readme.json
    参数子目录名称,默认为空
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -7377,9 +7509,9 @@ http://localhost:3000/api/yystopf/csfjkkj/readme.json -d"filepath=lib"\ http://localhost:3000/api/yystopf/csfjkkj/contributors.json
    await octokit.request('GET /api/yystopf/csfjkkj/contributors.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/:owner/:repo/contributors.json

    -

    请求参数:

    +

    请求参数:

    参数
    @@ -7418,7 +7550,7 @@ http://localhost:3000/api/yystopf/csfjkkj/contributors.json
    参数子目录名称,默认为空
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -7493,9 +7625,9 @@ http://localhost:3000/api/yystopf/csfjkkj/contributors.json
    curl -X GET \
     http://localhost:3000/api/yystopf/ceshi/webhooks.json
     
    await octokit.request('GET /api/yystopf/ceshi/webhooks.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/:owner/:repo/webhooks.json

    -

    请求参数:

    +

    请求参数:

    参数
    @@ -7520,7 +7652,7 @@ http://localhost:3000/api/yystopf/ceshi/webhooks.json
    参数项目标识identifier
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -7622,9 +7754,9 @@ http://localhost:3000/api/yystopf/ceshi/webhooks.json
    curl -X GET \
     http://localhost:3000/api/yystopf/ceshi/webhooks/3/edit.json
     
    await octokit.request('GET /api/yystopf/ceshi/webhooks/3/edit.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/:owner/:repo/webhooks/:id/edit.json

    -

    请求参数:

    +

    请求参数:

    参数
    @@ -7656,7 +7788,7 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/3/edit.json
    参数webhook ID
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -7857,266 +7989,8 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/3/edit.json
    curl -X POST \
     http://localhost:3000/api/yystopf/ceshi/webhooks.json
     
    await octokit.request('POST /api/yystopf/ceshi/webhooks.json')
    -

    HTTP 请求

    -

    POST /api/:owner/:repo/webhooks.json

    -

    请求参数:

    -
    参数
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    参数必选默认类型字段说明
    ownerstring用户登录名
    repostring项目标识identifier
    webhook.urlstring目标url
    webhook.typestring类型
    webhook.http_methodstringhttp方法, POST和GET
    webhook.content_typestringPOST Content Type
    webhook.secretstring密钥文本
    webhook.activebool是否激活
    webhook.branch_filterstring分支过滤
    webhook.eventsarray触发事件
    - -

    触发事件字段说明

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    参数含义
    create创建分支或标签
    delete分支或标签删除
    fork仓库被fork
    pushgit仓库推送
    issue易修已打开、已关闭、已重新打开或编辑
    issue_assign易修被指派
    issue_label易修标签被更新或删除
    issue_milestone易修被收入里程碑
    issue_comment易修评论
    pull_request合并请求
    pull_request_assign合并请求被指派
    pull_request_label合并请求被贴上标签
    pull_request_milestone合并请求被记录于里程碑中
    pull_request_comment合并请求被评论
    pull_request_review_approved合并请求被批准
    pull_request_review_rejected合并请求被拒绝
    pull_request_review_comment合并请求被提出审查意见
    pull_request_sync合并请求被同步
    repository创建或删除仓库
    release版本发布
    - -
    -

    请求的JSON示例:

    -
    -
    {
    -    "active": true, 
    -    "content_type": "json",
    -    "http_method": "GET",
    -    "secret": "123456",
    -    "url": "http://localhost:10000",
    -    "branch_filter": "*",
    -    "events": ["push"]
    -}
    -

    返回字段说明:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    参数类型字段说明
    idintid
    urlstring地址
    content_typestringPOST Content Type
    is_activebool是否激活
    typestring类型
    eventsarray触发事件
    create_timestring创建时间
    - -
    -

    返回的JSON示例:

    -
    -
    {
    -    "id": 18,
    -    "type": "gitea",
    -    "content_type": "json",
    -    "url": "http://localhost:10000",
    -    "events": [
    -        "push"
    -    ],
    -    "active": true,
    -    "create_time": "2021-07-26 18:53:43"
    -}
    -
    - -

    更新仓库webhook

    -

    更新仓库webhook

    - -
    -

    示例:

    -
    -
    curl -X PATCH \
    -http://localhost:3000/api/yystopf/ceshi/webhooks/7.json
    -
    await octokit.request('PATCH /api/yystopf/ceshi/webhooks/7.json')
     

    HTTP 请求

    -

    PATCH /api/:owner/:repo/webhooks/:id.json

    +

    POST /api/:owner/:repo/webhooks.json

    请求参数:

    @@ -8142,13 +8016,6 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/7.json - - - - - - - @@ -8309,28 +8176,79 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/7.json "events": ["push"] }

    返回字段说明:

    +
    项目标识identifier
    idstringwebhook id
    webhook.url
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数类型字段说明
    idintid
    urlstring地址
    content_typestringPOST Content Type
    is_activebool是否激活
    typestring类型
    eventsarray触发事件
    create_timestring创建时间
    +

    返回的JSON示例:

    {
    -    "status": 0,
    -    "message": "success"
    +    "id": 18,
    +    "type": "gitea",
    +    "content_type": "json",
    +    "url": "http://localhost:10000",
    +    "events": [
    +        "push"
    +    ],
    +    "active": true,
    +    "create_time": "2021-07-26 18:53:43"
     }
     
    -

    删除仓库webhook

    -

    删除仓库webhook

    +

    更新仓库webhook

    +

    更新仓库webhook

    示例:

    -
    curl -X DELETE \
    +
    curl -X PATCH \
     http://localhost:3000/api/yystopf/ceshi/webhooks/7.json
    -
    await octokit.request('DELETE /api/yystopf/ceshi/webhooks/7.json')
    +
    await octokit.request('PATCH /api/yystopf/ceshi/webhooks/7.json')
     

    HTTP 请求

    -

    DELETE /api/:owner/:repo/webhooks/:id.json

    +

    PATCH /api/:owner/:repo/webhooks/:id.json

    请求参数:

    @@ -8362,8 +8280,222 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/7.json + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    string webhook id
    webhook.urlstring目标url
    webhook.typestring类型
    webhook.http_methodstringhttp方法, POST和GET
    webhook.content_typestringPOST Content Type
    webhook.secretstring密钥文本
    webhook.activebool是否激活
    webhook.branch_filterstring分支过滤
    webhook.eventsarray触发事件
    -

    返回字段说明:

    + +

    触发事件字段说明

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数含义
    create创建分支或标签
    delete分支或标签删除
    fork仓库被fork
    pushgit仓库推送
    issue易修已打开、已关闭、已重新打开或编辑
    issue_assign易修被指派
    issue_label易修标签被更新或删除
    issue_milestone易修被收入里程碑
    issue_comment易修评论
    pull_request合并请求
    pull_request_assign合并请求被指派
    pull_request_label合并请求被贴上标签
    pull_request_milestone合并请求被记录于里程碑中
    pull_request_comment合并请求被评论
    pull_request_review_approved合并请求被批准
    pull_request_review_rejected合并请求被拒绝
    pull_request_review_comment合并请求被提出审查意见
    pull_request_sync合并请求被同步
    repository创建或删除仓库
    release版本发布
    + +
    +

    请求的JSON示例:

    +
    +
    {
    +    "active": true, 
    +    "content_type": "json",
    +    "http_method": "GET",
    +    "secret": "123456",
    +    "url": "http://localhost:10000",
    +    "branch_filter": "*",
    +    "events": ["push"]
    +}
    +

    返回字段说明:

    +
    +

    返回的JSON示例:

    +
    +
    {
    +    "status": 0,
    +    "message": "success"
    +}
    +
    + +

    删除仓库webhook

    +

    删除仓库webhook

    + +
    +

    示例:

    +
    +
    curl -X DELETE \
    +http://localhost:3000/api/yystopf/ceshi/webhooks/7.json
    +
    await octokit.request('DELETE /api/yystopf/ceshi/webhooks/7.json')
    +

    HTTP 请求

    +

    DELETE /api/:owner/:repo/webhooks/:id.json

    +

    请求参数:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数必选默认类型字段说明
    ownerstring用户登录名
    repostring项目标识identifier
    idstringwebhook id
    +

    返回字段说明:

    返回的JSON示例:

    @@ -8384,9 +8516,9 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/7.json
    curl -X GET \
     http://localhost:3000/api/yystopf/ceshi/webhooks/3/tasks.json
     
    await octokit.request('GET /api/yystopf/ceshi/webhooks/3/tasks.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/:owner/:repo/webhooks/:id/tasks.json

    -

    请求参数:

    +

    请求参数:

    @@ -8418,7 +8550,7 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/3/tasks.json
    参数webhook ID
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -8655,9 +8787,9 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/3/tasks.json
    curl -X POST \
     http://localhost:3000/api/yystopf/ceshi/webhooks/3/test.json
     
    await octokit.request('POST /api/yystopf/ceshi/webhooks/3/test.json')
    -

    HTTP 请求

    +

    HTTP 请求

    POST /api/:owner/:repo/webhooks/:id/test.json

    -

    请求参数:

    +

    请求参数:

    参数
    @@ -8689,7 +8821,7 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/3/test.json
    参数webhook ID
    -

    返回字段说明:

    +

    返回字段说明:

    返回的JSON示例:

    From 33473eecc27b34a3df0a70b0eef1712b4c00f7f8 Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 24 Sep 2021 18:06:29 +0800 Subject: [PATCH 067/135] fix: tag addition message --- app/controllers/projects_controller.rb | 2 +- .../slate/source/includes/_repositories.md | 41 ++++++++++-- app/views/repositories/tags.json.jbuilder | 13 +++- public/docs/api.html | 65 +++++++++++++++++-- 4 files changed, 107 insertions(+), 14 deletions(-) diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index b19d2b63..bea2b429 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -4,7 +4,7 @@ class ProjectsController < ApplicationController include ProjectsHelper include Acceleratorable - before_action :require_login, except: %i[index branches group_type_list simple show fork_users praise_users watch_users recommend about menu_list] + before_action :require_login, except: %i[index branches branches_slice group_type_list simple show fork_users praise_users watch_users recommend about menu_list] before_action :require_profile_completed, only: [:create, :migrate] before_action :load_repository, except: %i[index group_type_list migrate create recommend] before_action :authorizate_user_can_edit_project!, only: %i[update] diff --git a/app/docs/slate/source/includes/_repositories.md b/app/docs/slate/source/includes/_repositories.md index 81dbe144..1ebb4536 100644 --- a/app/docs/slate/source/includes/_repositories.md +++ b/app/docs/slate/source/includes/_repositories.md @@ -295,6 +295,8 @@ await octokit.request('GET /api/yystopf/csfjkkj/tags.json') --------- | ------- | ------- | -------- | ---------- |owner |是| |string |用户登录名 | |repo |是| |string |项目标识identifier | +|page |否| 1 | integer | 页码 | +|limit |否| 20| integer | 每页个数 | ### 返回字段说明: @@ -304,11 +306,14 @@ await octokit.request('GET /api/yystopf/csfjkkj/tags.json') |name |string|标签名称| |zipball_url |string|标签zip包下载地址| |tarball_url |string|标签tar包下载地址| +|tagger |object|打标签的人| +|message |string|标签信息| |commit |object|标签最后一个commit| |commit.sha |string|commit的id| |commit.message |string|commit的提交信息| |commit.time_ago|string|commit的提交时间| |commit.commiter|object|commit的提交者| +|commit.author|object|commit的作者| > 返回的JSON示例: @@ -320,15 +325,28 @@ await octokit.request('GET /api/yystopf/csfjkkj/tags.json') "id": "c7d0873ee41796d1a0e193063095ccf539a9bf31", "zipball_url": "http://localhost:3000/api/yystopf/csfjkkj/archive/v2.0.0.zip", "tarball_url": "http://localhost:3000/api/yystopf/csfjkkj/archive/v2.0.0.tar.gz", + "tagger": { + "id": 4, + "login": "testforge1", + "name": "testforge1", + "image_url": "system/lets/letter_avatars/2/T/19_237_174/120.png" + }, + "message": "jdfkls", "commit": { "sha": "08fe383f1e5ebe2e2a384a8ea3ee890a758c7cd7", "message": "add\n", - "time_ago": "4小时前", + "time_ago": "1天前", "committer": { "id": 4, "login": "testforge1", "name": "testforge1", "image_url": "system/lets/letter_avatars/2/T/19_237_174/120.png" + }, + "author": { + "id": 4, + "login": "testforge1", + "name": "testforge1", + "image_url": "system/lets/letter_avatars/2/T/19_237_174/120.png" } } }, @@ -337,15 +355,28 @@ await octokit.request('GET /api/yystopf/csfjkkj/tags.json') "id": "12168ad39c3ef201a445a2db181a3e43d50e40dd", "zipball_url": "http://localhost:3000/api/yystopf/csfjkkj/archive/v1.0.0.zip", "tarball_url": "http://localhost:3000/api/yystopf/csfjkkj/archive/v1.0.0.tar.gz", + "tagger": { + "id": null, + "login": "viletyy", + "name": "viletyy", + "image_url": "system/lets/letter_avatars/2/V/39_141_222/120.png" + }, + "message": "dfks", "commit": { "sha": "5291b5e45a377c1f7710cc6647259887ed7aaccf", "message": "ADD file via upload\n", - "time_ago": "9天前", + "time_ago": "21天前", "committer": { - "id": 2, + "id": null, "login": "yystopf", - "name": "heh", - "image_url": "system/lets/letter_avatars/2/H/188_239_142/120.png" + "name": "yystopf", + "image_url": "system/lets/letter_avatars/2/Y/241_125_89/120.png" + }, + "author": { + "id": null, + "login": "yystopf", + "name": "yystopf", + "image_url": "system/lets/letter_avatars/2/Y/241_125_89/120.png" } } } diff --git a/app/views/repositories/tags.json.jbuilder b/app/views/repositories/tags.json.jbuilder index 011fad46..8ae5f94c 100644 --- a/app/views/repositories/tags.json.jbuilder +++ b/app/views/repositories/tags.json.jbuilder @@ -4,12 +4,19 @@ json.array! @tags do |tag| json.id tag['id'] json.zipball_url render_zip_url(@owner, @repository, tag['name']) json.tarball_url render_tar_url(@owner, @repository, tag['name']) + json.tagger do + json.partial! 'commit_author', user: render_commit_author(tag['tagger']), name: tag['tagger']['name'] + end + json.message tag['message'] json.commit do json.sha tag['commit']['sha'] - json.message tag['commit_message'] - json.time_ago time_from_now(tag['commit_time'].to_time) + json.message tag['commit']['message'] + json.time_ago time_from_now(tag['commit']['commiter']['date'].to_time) json.committer do - json.partial! 'commit_author', user: render_commit_author(tag['commiter']), name: tag['commiter']['name'] + json.partial! 'commit_author', user: render_commit_author(tag['commit']['commiter']), name: tag['commit']['commiter']['name'] + end + json.author do + json.partial! 'commit_author', user: render_commit_author(tag['commit']['author']), name: tag['commit']['author']['name'] end end end diff --git a/public/docs/api.html b/public/docs/api.html index 763134f4..6bd5c592 100644 --- a/public/docs/api.html +++ b/public/docs/api.html @@ -6222,6 +6222,20 @@ http://localhost:3000/api/ceshi1/ceshi_repo1/applied_transfer_projects/organizat string 项目标识identifier + +page +否 +1 +integer +页码 + + +limit +否 +20 +integer +每页个数 +

    返回字段说明:

    @@ -6252,6 +6266,16 @@ http://localhost:3000/api/ceshi1/ceshi_repo1/applied_transfer_projects/organizat + + + + + + + + + + @@ -6276,6 +6300,11 @@ http://localhost:3000/api/ceshi1/ceshi_repo1/applied_transfer_projects/organizat + + + + +
    标签tar包下载地址
    taggerobject打标签的人
    messagestring标签信息
    commit object 标签最后一个commitobject commit的提交者
    commit.authorobjectcommit的作者
    @@ -6287,15 +6316,28 @@ http://localhost:3000/api/ceshi1/ceshi_repo1/applied_transfer_projects/organizat "id": "c7d0873ee41796d1a0e193063095ccf539a9bf31", "zipball_url": "http://localhost:3000/api/yystopf/csfjkkj/archive/v2.0.0.zip", "tarball_url": "http://localhost:3000/api/yystopf/csfjkkj/archive/v2.0.0.tar.gz", + "tagger": { + "id": 4, + "login": "testforge1", + "name": "testforge1", + "image_url": "system/lets/letter_avatars/2/T/19_237_174/120.png" + }, + "message": "jdfkls", "commit": { "sha": "08fe383f1e5ebe2e2a384a8ea3ee890a758c7cd7", "message": "add\n", - "time_ago": "4小时前", + "time_ago": "1天前", "committer": { "id": 4, "login": "testforge1", "name": "testforge1", "image_url": "system/lets/letter_avatars/2/T/19_237_174/120.png" + }, + "author": { + "id": 4, + "login": "testforge1", + "name": "testforge1", + "image_url": "system/lets/letter_avatars/2/T/19_237_174/120.png" } } }, @@ -6304,15 +6346,28 @@ http://localhost:3000/api/ceshi1/ceshi_repo1/applied_transfer_projects/organizat "id": "12168ad39c3ef201a445a2db181a3e43d50e40dd", "zipball_url": "http://localhost:3000/api/yystopf/csfjkkj/archive/v1.0.0.zip", "tarball_url": "http://localhost:3000/api/yystopf/csfjkkj/archive/v1.0.0.tar.gz", + "tagger": { + "id": null, + "login": "viletyy", + "name": "viletyy", + "image_url": "system/lets/letter_avatars/2/V/39_141_222/120.png" + }, + "message": "dfks", "commit": { "sha": "5291b5e45a377c1f7710cc6647259887ed7aaccf", "message": "ADD file via upload\n", - "time_ago": "9天前", + "time_ago": "21天前", "committer": { - "id": 2, + "id": null, "login": "yystopf", - "name": "heh", - "image_url": "system/lets/letter_avatars/2/H/188_239_142/120.png" + "name": "yystopf", + "image_url": "system/lets/letter_avatars/2/Y/241_125_89/120.png" + }, + "author": { + "id": null, + "login": "yystopf", + "name": "yystopf", + "image_url": "system/lets/letter_avatars/2/Y/241_125_89/120.png" } } } From ab6b597d7b1209efc8681e915b9422cb2ef1787a Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 24 Sep 2021 18:28:01 +0800 Subject: [PATCH 068/135] fix --- app/docs/slate/source/includes/_repositories.md | 3 +++ app/views/repositories/tags.json.jbuilder | 1 + public/docs/api.html | 7 +++++++ 3 files changed, 11 insertions(+) diff --git a/app/docs/slate/source/includes/_repositories.md b/app/docs/slate/source/includes/_repositories.md index 1ebb4536..9669d456 100644 --- a/app/docs/slate/source/includes/_repositories.md +++ b/app/docs/slate/source/includes/_repositories.md @@ -307,6 +307,7 @@ await octokit.request('GET /api/yystopf/csfjkkj/tags.json') |zipball_url |string|标签zip包下载地址| |tarball_url |string|标签tar包下载地址| |tagger |object|打标签的人| +|time_ago |string|打标签的时间| |message |string|标签信息| |commit |object|标签最后一个commit| |commit.sha |string|commit的id| @@ -331,6 +332,7 @@ await octokit.request('GET /api/yystopf/csfjkkj/tags.json') "name": "testforge1", "image_url": "system/lets/letter_avatars/2/T/19_237_174/120.png" }, + "time_ago": "1天前", "message": "jdfkls", "commit": { "sha": "08fe383f1e5ebe2e2a384a8ea3ee890a758c7cd7", @@ -361,6 +363,7 @@ await octokit.request('GET /api/yystopf/csfjkkj/tags.json') "name": "viletyy", "image_url": "system/lets/letter_avatars/2/V/39_141_222/120.png" }, + "time_ago": "10天前", "message": "dfks", "commit": { "sha": "5291b5e45a377c1f7710cc6647259887ed7aaccf", diff --git a/app/views/repositories/tags.json.jbuilder b/app/views/repositories/tags.json.jbuilder index 8ae5f94c..2feab91e 100644 --- a/app/views/repositories/tags.json.jbuilder +++ b/app/views/repositories/tags.json.jbuilder @@ -7,6 +7,7 @@ json.array! @tags do |tag| json.tagger do json.partial! 'commit_author', user: render_commit_author(tag['tagger']), name: tag['tagger']['name'] end + json.time_ago time_from_now(tag['tagger']['date'].to_time) json.message tag['message'] json.commit do json.sha tag['commit']['sha'] diff --git a/public/docs/api.html b/public/docs/api.html index 6bd5c592..33f9e72b 100644 --- a/public/docs/api.html +++ b/public/docs/api.html @@ -6271,6 +6271,11 @@ http://localhost:3000/api/ceshi1/ceshi_repo1/applied_transfer_projects/organizat 打标签的人 +time_ago +string +打标签的时间 + + message string 标签信息 @@ -6322,6 +6327,7 @@ http://localhost:3000/api/ceshi1/ceshi_repo1/applied_transfer_projects/organizat "name": "testforge1", "image_url": "system/lets/letter_avatars/2/T/19_237_174/120.png" }, + "time_ago": "1天前", "message": "jdfkls", "commit": { "sha": "08fe383f1e5ebe2e2a384a8ea3ee890a758c7cd7", @@ -6352,6 +6358,7 @@ http://localhost:3000/api/ceshi1/ceshi_repo1/applied_transfer_projects/organizat "name": "viletyy", "image_url": "system/lets/letter_avatars/2/V/39_141_222/120.png" }, + "time_ago": "10天前", "message": "dfks", "commit": { "sha": "5291b5e45a377c1f7710cc6647259887ed7aaccf", From 133713ae7f575214bc883ac4b162412e73ebf3e7 Mon Sep 17 00:00:00 2001 From: yystopf Date: Sun, 26 Sep 2021 11:36:34 +0800 Subject: [PATCH 069/135] add: tag created at unix --- app/docs/slate/source/includes/_repositories.md | 6 ++++++ app/views/repositories/tags.json.jbuilder | 2 ++ public/docs/api.html | 14 ++++++++++++++ 3 files changed, 22 insertions(+) diff --git a/app/docs/slate/source/includes/_repositories.md b/app/docs/slate/source/includes/_repositories.md index 9669d456..642a4cc3 100644 --- a/app/docs/slate/source/includes/_repositories.md +++ b/app/docs/slate/source/includes/_repositories.md @@ -308,11 +308,13 @@ await octokit.request('GET /api/yystopf/csfjkkj/tags.json') |tarball_url |string|标签tar包下载地址| |tagger |object|打标签的人| |time_ago |string|打标签的时间| +|created_at_unix|string|打标签的时间戳| |message |string|标签信息| |commit |object|标签最后一个commit| |commit.sha |string|commit的id| |commit.message |string|commit的提交信息| |commit.time_ago|string|commit的提交时间| +|commit.created_at_unix|string|commit的提交时间戳| |commit.commiter|object|commit的提交者| |commit.author|object|commit的作者| @@ -333,11 +335,13 @@ await octokit.request('GET /api/yystopf/csfjkkj/tags.json') "image_url": "system/lets/letter_avatars/2/T/19_237_174/120.png" }, "time_ago": "1天前", + "created_at_unix": 1632376903, "message": "jdfkls", "commit": { "sha": "08fe383f1e5ebe2e2a384a8ea3ee890a758c7cd7", "message": "add\n", "time_ago": "1天前", + "created_at_unix": 1632376186, "committer": { "id": 4, "login": "testforge1", @@ -364,11 +368,13 @@ await octokit.request('GET /api/yystopf/csfjkkj/tags.json') "image_url": "system/lets/letter_avatars/2/V/39_141_222/120.png" }, "time_ago": "10天前", + "created_at_unix": 1631588042, "message": "dfks", "commit": { "sha": "5291b5e45a377c1f7710cc6647259887ed7aaccf", "message": "ADD file via upload\n", "time_ago": "21天前", + "created_at_unix": 1630648417, "committer": { "id": null, "login": "yystopf", diff --git a/app/views/repositories/tags.json.jbuilder b/app/views/repositories/tags.json.jbuilder index 2feab91e..d1ee3671 100644 --- a/app/views/repositories/tags.json.jbuilder +++ b/app/views/repositories/tags.json.jbuilder @@ -8,11 +8,13 @@ json.array! @tags do |tag| json.partial! 'commit_author', user: render_commit_author(tag['tagger']), name: tag['tagger']['name'] end json.time_ago time_from_now(tag['tagger']['date'].to_time) + json.created_at_unix tag['tagger']['date'].to_time.to_i json.message tag['message'] json.commit do json.sha tag['commit']['sha'] json.message tag['commit']['message'] json.time_ago time_from_now(tag['commit']['commiter']['date'].to_time) + json.created_at_unix tag['commit']['commiter']['date'].to_time.to_i json.committer do json.partial! 'commit_author', user: render_commit_author(tag['commit']['commiter']), name: tag['commit']['commiter']['name'] end diff --git a/public/docs/api.html b/public/docs/api.html index 33f9e72b..fc942703 100644 --- a/public/docs/api.html +++ b/public/docs/api.html @@ -6276,6 +6276,11 @@ http://localhost:3000/api/ceshi1/ceshi_repo1/applied_transfer_projects/organizat 打标签的时间 +created_at_unix +string +打标签的时间戳 + + message string 标签信息 @@ -6301,6 +6306,11 @@ http://localhost:3000/api/ceshi1/ceshi_repo1/applied_transfer_projects/organizat commit的提交时间 +commit.created_at_unix +string +commit的提交时间戳 + + commit.commiter object commit的提交者 @@ -6328,11 +6338,13 @@ http://localhost:3000/api/ceshi1/ceshi_repo1/applied_transfer_projects/organizat "image_url": "system/lets/letter_avatars/2/T/19_237_174/120.png" }, "time_ago": "1天前", + "created_at_unix": 1632376903, "message": "jdfkls", "commit": { "sha": "08fe383f1e5ebe2e2a384a8ea3ee890a758c7cd7", "message": "add\n", "time_ago": "1天前", + "created_at_unix": 1632376186, "committer": { "id": 4, "login": "testforge1", @@ -6359,11 +6371,13 @@ http://localhost:3000/api/ceshi1/ceshi_repo1/applied_transfer_projects/organizat "image_url": "system/lets/letter_avatars/2/V/39_141_222/120.png" }, "time_ago": "10天前", + "created_at_unix": 1631588042, "message": "dfks", "commit": { "sha": "5291b5e45a377c1f7710cc6647259887ed7aaccf", "message": "ADD file via upload\n", "time_ago": "21天前", + "created_at_unix": 1630648417, "committer": { "id": null, "login": "yystopf", From 46a083239b20a488b6389c2615a45e78fdb4d963 Mon Sep 17 00:00:00 2001 From: yystopf Date: Sun, 26 Sep 2021 14:32:24 +0800 Subject: [PATCH 070/135] add: release show api --- .../version_releases_controller.rb | 6 ++- app/services/gitea/versions/get_service.rb | 37 +++++++++++++++++++ .../_version_release.json.jbuilder | 14 +++++++ .../version_releases/index.json.jbuilder | 30 +-------------- app/views/version_releases/show.json.jbuilder | 2 + config/routes.rb | 2 +- 6 files changed, 61 insertions(+), 30 deletions(-) create mode 100644 app/services/gitea/versions/get_service.rb create mode 100644 app/views/version_releases/_version_release.json.jbuilder create mode 100644 app/views/version_releases/show.json.jbuilder diff --git a/app/controllers/version_releases_controller.rb b/app/controllers/version_releases_controller.rb index 618eb073..04578533 100644 --- a/app/controllers/version_releases_controller.rb +++ b/app/controllers/version_releases_controller.rb @@ -2,7 +2,7 @@ class VersionReleasesController < ApplicationController before_action :load_repository before_action :set_user before_action :require_login, except: [:index] - before_action :find_version , only: [:edit, :update, :destroy] + before_action :find_version , only: [:show, :edit, :update, :destroy] def index version_releases = Gitea::Versions::ListService.new(@user.gitea_token, @user.try(:login), @repository.try(:identifier)).call @@ -22,6 +22,10 @@ class VersionReleasesController < ApplicationController end end + def show + @release = Gitea::Versions::GetService.call(current_user.gitea_token, @user&.login, @repository&.identifier, @version&.version_gid) + end + def create if params[:name].nil? normal_status(-1, "名称不能为空") diff --git a/app/services/gitea/versions/get_service.rb b/app/services/gitea/versions/get_service.rb new file mode 100644 index 00000000..b3c6cf9c --- /dev/null +++ b/app/services/gitea/versions/get_service.rb @@ -0,0 +1,37 @@ +# Get a list of all commits from a repository +class Gitea::Versions::GetService < Gitea::ClientService + attr_reader :token, :user_name, :repo, :gid, :args + + # sha: SHA or branch to start listing commits from (usually 'master') + def initialize(token, user_name, repo, gid, args={}) + @token = token + @user_name = user_name + @repo = repo + @gid = gid + @args = args + end + + def call + response = get(url, params) + render_result(response) + end + + private + def params + args.merge(token: token) + end + + def url + "/repos/#{@user_name}/#{@repo}/releases/#{@gid}".freeze + end + + def render_result(response) + body = JSON.parse(response.body) + case response.status + when 200 + body + else + {status: -1, message: "#{body['message']}"} + end + end +end diff --git a/app/views/version_releases/_version_release.json.jbuilder b/app/views/version_releases/_version_release.json.jbuilder new file mode 100644 index 00000000..23c27518 --- /dev/null +++ b/app/views/version_releases/_version_release.json.jbuilder @@ -0,0 +1,14 @@ +json.version_id version.try(:id) +json.id re["id"] +json.tag_name re["tag_name"] +json.target_commitish re["target_commitish"] +json.name re["name"] +json.body re["body"] +json.url re["url"] +json.tarball_url render_tar_url(@owner, @repository, re["tag_name"]) +json.zipball_url render_zip_url(@owner, @repository, re["tag_name"]) +json.draft re["draft"] ? "草稿" : (re["prerelease"] ? "预发行" : "稳定") +json.created_at format_time(version.created_at.to_s.to_time) +json.published_at format_time(version.created_at.to_s.to_time) +json.user_name user.present? ? user.try(:show_real_name) : "" +json.image_url user.present? ? url_to_avatar(user) : "" \ No newline at end of file diff --git a/app/views/version_releases/index.json.jbuilder b/app/views/version_releases/index.json.jbuilder index 88ae36f2..29cc4fd2 100644 --- a/app/views/version_releases/index.json.jbuilder +++ b/app/views/version_releases/index.json.jbuilder @@ -7,36 +7,10 @@ json.releases do user = User.select(:id, :gitea_uid, :login, :lastname,:firstname, :nickname).find_by_gitea_uid(re["author"]["id"]) version = @forge_releases.find_by(version_gid: re["id"]) if @user_permission && re["draft"] - json.version_id version.try(:id) - json.id re["id"] - json.tag_name re["tag_name"] - json.target_commitish re["target_commitish"] - json.name re["name"] - json.body re["body"] - json.url re["url"] - json.tarball_url render_tar_url(@owner, @repository, re["tag_name"]) - json.zipball_url render_zip_url(@owner, @repository, re["tag_name"]) - json.draft re["draft"] ? "草稿" : (re["prerelease"] ? "预发行" : "稳定") - json.created_at format_time(version.created_at.to_s.to_time) - json.published_at format_time(version.created_at.to_s.to_time) - json.user_name user.present? ? user.try(:show_real_name) : "" - json.image_url user.present? ? url_to_avatar(user) : "" + json.partial! "version_release", locals: {version: version, user: user, re: re} else unless re["draft"] - json.version_id version.try(:id) - json.id re["id"] - json.tag_name re["tag_name"] - json.target_commitish re["target_commitish"] - json.name re["name"] - json.body re["body"] - json.url re["url"] - json.tarball_url render_tar_url(@owner, @repository, re["tag_name"]) - json.zipball_url render_zip_url(@owner, @repository, re["tag_name"]) - json.draft re["draft"] ? "草稿" : (re["prerelease"] ? "预发行" : "稳定") - json.created_at format_time(version.created_at.to_s.to_time) - json.published_at format_time(version.created_at.to_s.to_time) - json.user_name user.present? ? user.try(:show_real_name) : "" - json.image_url user.present? ? url_to_avatar(user) : "" + json.partial! "version_release", locals: {version: version, user: user, re: re} end end diff --git a/app/views/version_releases/show.json.jbuilder b/app/views/version_releases/show.json.jbuilder new file mode 100644 index 00000000..803ae477 --- /dev/null +++ b/app/views/version_releases/show.json.jbuilder @@ -0,0 +1,2 @@ +user = User.select(:id, :gitea_uid, :login, :lastname,:firstname, :nickname).find_by_gitea_uid(@release["author"]["id"]) +json.partial! "version_release", locals: {version: @version, user: user, re: @release} \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index 2a935b89..005bd926 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -528,7 +528,7 @@ Rails.application.routes.draw do resources :forks, only: [:create] resources :project_trends, :path => :activity, only: [:index, :create] resources :issue_tags, :path => :labels, only: [:create, :edit, :update, :destroy, :index] - resources :version_releases, :path => :releases, only: [:index,:new, :create, :edit, :update, :destroy] + resources :version_releases, :path => :releases, only: [:index,:new, :show, :create, :edit, :update, :destroy] scope module: :ci do scope do From 24e77300adee735ac7d9cf430703b238b30b2e55 Mon Sep 17 00:00:00 2001 From: yystopf Date: Sun, 26 Sep 2021 14:42:29 +0800 Subject: [PATCH 071/135] fix: relase attachments --- app/views/version_releases/_version_release.json.jbuilder | 7 ++++++- app/views/version_releases/index.json.jbuilder | 6 ------ 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/app/views/version_releases/_version_release.json.jbuilder b/app/views/version_releases/_version_release.json.jbuilder index 23c27518..498e05ee 100644 --- a/app/views/version_releases/_version_release.json.jbuilder +++ b/app/views/version_releases/_version_release.json.jbuilder @@ -11,4 +11,9 @@ json.draft re["draft"] ? "草稿" : (re["prerelease"] ? "预发行" : "稳定") json.created_at format_time(version.created_at.to_s.to_time) json.published_at format_time(version.created_at.to_s.to_time) json.user_name user.present? ? user.try(:show_real_name) : "" -json.image_url user.present? ? url_to_avatar(user) : "" \ No newline at end of file +json.image_url user.present? ? url_to_avatar(user) : "" +json.attachments do + json.array! version.try(:attachments) do |attachment| + json.partial! "attachments/attachment_simple", locals: {attachment: attachment} + end +end \ No newline at end of file diff --git a/app/views/version_releases/index.json.jbuilder b/app/views/version_releases/index.json.jbuilder index 29cc4fd2..cfafb200 100644 --- a/app/views/version_releases/index.json.jbuilder +++ b/app/views/version_releases/index.json.jbuilder @@ -13,12 +13,6 @@ json.releases do json.partial! "version_release", locals: {version: version, user: user, re: re} end end - - json.attachments do - json.array! version.try(:attachments) do |attachment| - json.partial! "attachments/attachment_simple", locals: {attachment: attachment} - end - end end end From f013ddcb7277ea63d955f500cabb6abacb821bb3 Mon Sep 17 00:00:00 2001 From: yystopf Date: Sun, 26 Sep 2021 14:44:26 +0800 Subject: [PATCH 072/135] fix --- app/controllers/version_releases_controller.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/controllers/version_releases_controller.rb b/app/controllers/version_releases_controller.rb index 04578533..c3aed146 100644 --- a/app/controllers/version_releases_controller.rb +++ b/app/controllers/version_releases_controller.rb @@ -1,7 +1,7 @@ class VersionReleasesController < ApplicationController before_action :load_repository before_action :set_user - before_action :require_login, except: [:index] + before_action :require_login, except: [:index, :show] before_action :find_version , only: [:show, :edit, :update, :destroy] def index From 1d0255440aeb4bb9208a90aa5226c286161de2b7 Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 27 Sep 2021 16:58:14 +0800 Subject: [PATCH 073/135] add: release list sha --- app/views/version_releases/_version_release.json.jbuilder | 1 + 1 file changed, 1 insertion(+) diff --git a/app/views/version_releases/_version_release.json.jbuilder b/app/views/version_releases/_version_release.json.jbuilder index 498e05ee..86165d5a 100644 --- a/app/views/version_releases/_version_release.json.jbuilder +++ b/app/views/version_releases/_version_release.json.jbuilder @@ -3,6 +3,7 @@ json.id re["id"] json.tag_name re["tag_name"] json.target_commitish re["target_commitish"] json.name re["name"] +json.sha re["sha"] json.body re["body"] json.url re["url"] json.tarball_url render_tar_url(@owner, @repository, re["tag_name"]) From cae59383b4df35c8b50daed77269aa81afeae6ec Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 29 Sep 2021 09:18:07 +0800 Subject: [PATCH 074/135] add: commit show committer --- .../repositories/_commit_author.json.jbuilder | 2 ++ app/views/repositories/commits.json.jbuilder | 34 +++++++++++-------- 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/app/views/repositories/_commit_author.json.jbuilder b/app/views/repositories/_commit_author.json.jbuilder index 1478cca0..c63edf9b 100644 --- a/app/views/repositories/_commit_author.json.jbuilder +++ b/app/views/repositories/_commit_author.json.jbuilder @@ -2,10 +2,12 @@ if user json.id user.id json.login user.login json.name user.real_name + json.type user&.type json.image_url url_to_avatar(user) else json.id nil json.login name json.name name + json.type nil json.image_url User::Avatar.get_letter_avatar_url(name) end diff --git a/app/views/repositories/commits.json.jbuilder b/app/views/repositories/commits.json.jbuilder index 9dd90446..cf4a409f 100644 --- a/app/views/repositories/commits.json.jbuilder +++ b/app/views/repositories/commits.json.jbuilder @@ -7,25 +7,31 @@ else json.array! @hash_commit[:body] do |commit| commiter = commit['committer'] - forge_user = - if commiter.present? - User.simple_select.find_by(gitea_uid: commiter['id']) - end + # forge_user = + # if commiter.present? + # User.simple_select.find_by(gitea_uid: commiter['id']) + # end json.sha commit['sha'] json.message commit['commit']['message'] json.timestamp render_unix_time(commit['commit']['author']['date']) json.time_from_now time_from_now(commit['commit']['author']['date']) - if forge_user - json.partial! 'author', user: forge_user - else - json.author do - json.id nil - json.login commit['commit']['author']['name'] - json.type nil - json.name commit['commit']['author']['name'] - json.image_url User::Avatar.get_letter_avatar_url(commit['commit']['author']['name']) - end + # if forge_user + # json.partial! 'author', user: forge_user + # else + # json.author do + # json.id nil + # json.login commit['commit']['author']['name'] + # json.type nil + # json.name commit['commit']['author']['name'] + # json.image_url User::Avatar.get_letter_avatar_url(commit['commit']['author']['name']) + # end + # end + json.author do + json.partial! 'commit_author', user: render_commit_author(commit['commit']['author']), name: commit['commit']['author']['name'] + end + json.committer do + json.partial! 'commit_author', user: render_commit_author(commit['commit']['committer']), name: commit['commit']['committer']['name'] end end end From c39990fff3c7ce47bce5262bd0953ed9bf8c9a16 Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 29 Sep 2021 09:20:28 +0800 Subject: [PATCH 075/135] fix: doc --- app/docs/slate/source/includes/_repositories.md | 2 +- public/docs/api.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/docs/slate/source/includes/_repositories.md b/app/docs/slate/source/includes/_repositories.md index 642a4cc3..3604689c 100644 --- a/app/docs/slate/source/includes/_repositories.md +++ b/app/docs/slate/source/includes/_repositories.md @@ -315,7 +315,7 @@ await octokit.request('GET /api/yystopf/csfjkkj/tags.json') |commit.message |string|commit的提交信息| |commit.time_ago|string|commit的提交时间| |commit.created_at_unix|string|commit的提交时间戳| -|commit.commiter|object|commit的提交者| +|commit.committer|object|commit的提交者| |commit.author|object|commit的作者| diff --git a/public/docs/api.html b/public/docs/api.html index fc942703..ef03d978 100644 --- a/public/docs/api.html +++ b/public/docs/api.html @@ -6311,7 +6311,7 @@ http://localhost:3000/api/ceshi1/ceshi_repo1/applied_transfer_projects/organizat commit的提交时间戳 -commit.commiter +commit.committer object commit的提交者 From c9bd81af4e15d559b6989f87fe8a74251e144353 Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 29 Sep 2021 10:01:46 +0800 Subject: [PATCH 076/135] fix: lastcommit author and committer --- app/views/repositories/_commit.json.jbuilder | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/views/repositories/_commit.json.jbuilder b/app/views/repositories/_commit.json.jbuilder index 3f3dd554..95cb0341 100644 --- a/app/views/repositories/_commit.json.jbuilder +++ b/app/views/repositories/_commit.json.jbuilder @@ -26,9 +26,9 @@ if @project.forge? end json.author do - json.partial! 'commit_author', user: render_commit_author(commit['author']), name: commit['commit']['author']['name'] + json.partial! 'commit_author', user: render_commit_author(commit['commit']['author']), name: commit['commit']['author']['name'] end json.committer do - json.partial! 'commit_author', user: render_commit_author(commit['committer']), name: commit['commit']['committer']['name'] + json.partial! 'commit_author', user: render_commit_author(commit['commit']['committer']), name: commit['commit']['committer']['name'] end end From d1f5c32f688b79c26e2e38a3742be141bb2b5b58 Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 29 Sep 2021 10:37:21 +0800 Subject: [PATCH 077/135] fix --- app/views/repositories/commit.json.jbuilder | 1 + 1 file changed, 1 insertion(+) diff --git a/app/views/repositories/commit.json.jbuilder b/app/views/repositories/commit.json.jbuilder index 77f6e3f1..b15abef7 100644 --- a/app/views/repositories/commit.json.jbuilder +++ b/app/views/repositories/commit.json.jbuilder @@ -9,3 +9,4 @@ json.parents @commit['parents'] do |parent| json.sha parent['sha'] # json.url EduSetting.get('host_name') + commit_repository_path(@repo, parent['sha']) end +json.branch @commit['branch'] From 520b0ef1bee2d33e80f56e5c12f9e23556f45ba9 Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 29 Sep 2021 11:43:04 +0800 Subject: [PATCH 078/135] fix: release creator token --- app/controllers/version_releases_controller.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/controllers/version_releases_controller.rb b/app/controllers/version_releases_controller.rb index c3aed146..b397a2bc 100644 --- a/app/controllers/version_releases_controller.rb +++ b/app/controllers/version_releases_controller.rb @@ -41,7 +41,7 @@ class VersionReleasesController < ApplicationController version_params = releases_params version_release = VersionRelease.new(version_params.merge(user_id: current_user.id, repository_id: @repository.id)) if version_release.save! - git_version_release = Gitea::Versions::CreateService.new(@user.gitea_token, @user.try(:login), @repository.try(:identifier), version_params).call + git_version_release = Gitea::Versions::CreateService.new(current_user.gitea_token, @user.try(:login), @repository.try(:identifier), version_params).call if git_version_release update_params = { tarball_url: git_version_release["tarball_url"], @@ -85,7 +85,7 @@ class VersionReleasesController < ApplicationController if @version.update_attributes!(version_params) create_attachments(params[:attachment_ids], @version) if params[:attachment_ids].present? - git_version_release = Gitea::Versions::UpdateService.new(@user.gitea_token, @user.try(:login), @repository.try(:identifier), version_params, @version.try(:version_gid)).call + git_version_release = Gitea::Versions::UpdateService.new(current_user.gitea_token, @user.try(:login), @repository.try(:identifier), version_params, @version.try(:version_gid)).call unless git_version_release raise Error, "更新失败" end @@ -106,7 +106,7 @@ class VersionReleasesController < ApplicationController ActiveRecord::Base.transaction do begin if @version.destroy - git_version_release = Gitea::Versions::DeleteService.new(@user.gitea_token, @user.try(:login), @repository.try(:identifier), @version.try(:version_gid)).call + git_version_release = Gitea::Versions::DeleteService.new(current_user.gitea_token, @user.try(:login), @repository.try(:identifier), @version.try(:version_gid)).call if git_version_release.status == 204 normal_status(0, "删除成功") From 69b8e0710c310a947c58046b213ddd520aceaab7 Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 29 Sep 2021 17:09:30 +0800 Subject: [PATCH 079/135] add: organization info --- .../organizations/_simple.json.jbuilder | 14 +++++++++----- app/views/organizations/teams/show.json.jbuilder | 5 ++++- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/app/views/organizations/organizations/_simple.json.jbuilder b/app/views/organizations/organizations/_simple.json.jbuilder index 12792b12..7fed762a 100644 --- a/app/views/organizations/organizations/_simple.json.jbuilder +++ b/app/views/organizations/organizations/_simple.json.jbuilder @@ -1,5 +1,9 @@ -json.id organization.id -json.name organization.login -json.nickname organization.nickname.blank? ? organization.name : organization.nickname -json.description organization.description -json.avatar_url url_to_avatar(organization) +if organization.present? + json.id organization.id + json.name organization.login + json.nickname organization.nickname.blank? ? organization.name : organization.nickname + json.description organization.description + json.avatar_url url_to_avatar(organization) +else + nil +end \ No newline at end of file diff --git a/app/views/organizations/teams/show.json.jbuilder b/app/views/organizations/teams/show.json.jbuilder index d0290897..c86f9b54 100644 --- a/app/views/organizations/teams/show.json.jbuilder +++ b/app/views/organizations/teams/show.json.jbuilder @@ -1,3 +1,6 @@ json.partial! "detail", team: @team, organization: @organization json.is_admin @is_admin -json.is_member @is_member \ No newline at end of file +json.is_member @is_member +json.organization do + json.partial! "organizations/organizations/simple", organization: @organization +end \ No newline at end of file From c1db02171acf608e466862200aedd9353c5d61e0 Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 29 Sep 2021 17:16:21 +0800 Subject: [PATCH 080/135] add: release admin permission field --- app/controllers/version_releases_controller.rb | 1 + app/views/version_releases/index.json.jbuilder | 1 + 2 files changed, 2 insertions(+) diff --git a/app/controllers/version_releases_controller.rb b/app/controllers/version_releases_controller.rb index b397a2bc..ade2d07e 100644 --- a/app/controllers/version_releases_controller.rb +++ b/app/controllers/version_releases_controller.rb @@ -8,6 +8,7 @@ class VersionReleasesController < ApplicationController version_releases = Gitea::Versions::ListService.new(@user.gitea_token, @user.try(:login), @repository.try(:identifier)).call @version_releases = version_releases @user_permission = current_user.present? && (@repository.project.all_developers.include?(current_user) || current_user.admin?) + @user_admin_permission = current_user.present? && (@repository.project.all_managers.include?(current_user) || current_user.admin?) @forge_releases = @repository.version_releases.select(:id,:version_gid, :created_at).includes(:attachments) end diff --git a/app/views/version_releases/index.json.jbuilder b/app/views/version_releases/index.json.jbuilder index cfafb200..8efb88bc 100644 --- a/app/views/version_releases/index.json.jbuilder +++ b/app/views/version_releases/index.json.jbuilder @@ -1,5 +1,6 @@ json.partial! "commons/success" json.user_permission @user_permission +json.user_admin_permission @user_admin_permission # json.releases @version_releases json.releases do json.array! @version_releases.to_a.each do |re| From b07781a514ee76fd8e7d24b3f3f96ad99607244f Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 29 Sep 2021 18:50:51 +0800 Subject: [PATCH 081/135] fix: some issues --- app/controllers/repositories_controller.rb | 2 +- app/helpers/repositories_helper.rb | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/app/controllers/repositories_controller.rb b/app/controllers/repositories_controller.rb index a7e909eb..db1db604 100644 --- a/app/controllers/repositories_controller.rb +++ b/app/controllers/repositories_controller.rb @@ -229,7 +229,7 @@ class RepositoriesController < ApplicationController file_path = [domain, api_url, url].join file_path = [file_path, "access_token=#{current_user&.gitea_token}"].join("&") if @repository.hidden? - redirect_to file_path + redirect_to URI.escape(file_path) end private diff --git a/app/helpers/repositories_helper.rb b/app/helpers/repositories_helper.rb index ee60b64a..d34e3a8d 100644 --- a/app/helpers/repositories_helper.rb +++ b/app/helpers/repositories_helper.rb @@ -10,12 +10,12 @@ module RepositoriesHelper end def download_type(str) - default_type = %w(xlsx xls ppt pptx pdf zip 7z rar exe pdb obj idb png jpg gif tif psd svg RData rdata doc docx mpp vsdx dot otf eot ttf woff woff2) + 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) default_type.include?(str&.downcase) end def image_type?(str) - default_type = %w(png jpg gif tif psd svg gif bmp webp jpeg) + default_type = %w(png jpg gif tif psd svg bmp webp jpeg) default_type.include?(str&.downcase) end @@ -83,12 +83,15 @@ module RepositoriesHelper 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, entry['path'], ref: ref)['content'] + content = Gitea::Repository::Entries::GetService.call(owner, repo.identifier, URI.escape(entry['path']), ref: ref)['content'] readme_render_decode64_content(content, 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'].nil? ? Gitea::Repository::Entries::GetService.call(owner, repo.identifier, entry['path'], ref: ref)['content'] : entry['content'] + return entry['content'] end render_decode64_content(entry['content']) end From aabfaad458615c65e65c25ec594eb4cf71864763 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 30 Sep 2021 11:09:13 +0800 Subject: [PATCH 082/135] add: release use database data --- .../version_releases_controller.rb | 7 +++---- app/models/version_release.rb | 6 ++++++ .../_version_release.json.jbuilder | 20 +++++++++---------- .../version_releases/index.json.jbuilder | 18 +++++++---------- app/views/version_releases/show.json.jbuilder | 4 ++-- ...10930025555_add_sha_to_version_releases.rb | 5 +++++ 6 files changed, 33 insertions(+), 27 deletions(-) create mode 100644 db/migrate/20210930025555_add_sha_to_version_releases.rb diff --git a/app/controllers/version_releases_controller.rb b/app/controllers/version_releases_controller.rb index ade2d07e..c66a4bf0 100644 --- a/app/controllers/version_releases_controller.rb +++ b/app/controllers/version_releases_controller.rb @@ -5,11 +5,9 @@ class VersionReleasesController < ApplicationController before_action :find_version , only: [:show, :edit, :update, :destroy] def index - version_releases = Gitea::Versions::ListService.new(@user.gitea_token, @user.try(:login), @repository.try(:identifier)).call - @version_releases = version_releases + @version_releases = kaminari_paginate(@repository.version_releases.order(created_at: :desc)) @user_permission = current_user.present? && (@repository.project.all_developers.include?(current_user) || current_user.admin?) @user_admin_permission = current_user.present? && (@repository.project.all_managers.include?(current_user) || current_user.admin?) - @forge_releases = @repository.version_releases.select(:id,:version_gid, :created_at).includes(:attachments) end def new @@ -24,7 +22,7 @@ class VersionReleasesController < ApplicationController end def show - @release = Gitea::Versions::GetService.call(current_user.gitea_token, @user&.login, @repository&.identifier, @version&.version_gid) + # @release = Gitea::Versions::GetService.call(current_user.gitea_token, @user&.login, @repository&.identifier, @version&.version_gid) end def create @@ -49,6 +47,7 @@ class VersionReleasesController < ApplicationController zipball_url: git_version_release["zipball_url"], url: git_version_release["url"], version_gid: git_version_release["id"], + sha: git_version_release["sha"] } version_release.update_attributes!(update_params) version_release.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: "create") diff --git a/app/models/version_release.rb b/app/models/version_release.rb index 16b823a7..3c97420e 100644 --- a/app/models/version_release.rb +++ b/app/models/version_release.rb @@ -17,6 +17,7 @@ # created_at :datetime not null # updated_at :datetime not null # repository_id :integer +# sha :string(255) # # Indexes # @@ -29,4 +30,9 @@ class VersionRelease < ApplicationRecord has_many :project_trends, as: :trend, dependent: :destroy scope :releases_size, ->{where(draft: false, prerelease: false).size} has_many :attachments, as: :container, dependent: :destroy + + def update_sha + git_release = Gitea::Versions::GetService.call(user.gitea_token, repository&.owner&.login, repository&.identifier, version_gid) + self.update(sha: git_release["sha"]) + end end diff --git a/app/views/version_releases/_version_release.json.jbuilder b/app/views/version_releases/_version_release.json.jbuilder index 86165d5a..ddf59ee7 100644 --- a/app/views/version_releases/_version_release.json.jbuilder +++ b/app/views/version_releases/_version_release.json.jbuilder @@ -1,14 +1,14 @@ json.version_id version.try(:id) -json.id re["id"] -json.tag_name re["tag_name"] -json.target_commitish re["target_commitish"] -json.name re["name"] -json.sha re["sha"] -json.body re["body"] -json.url re["url"] -json.tarball_url render_tar_url(@owner, @repository, re["tag_name"]) -json.zipball_url render_zip_url(@owner, @repository, re["tag_name"]) -json.draft re["draft"] ? "草稿" : (re["prerelease"] ? "预发行" : "稳定") +json.id version&.version_gid +json.tag_name version&.tag_name +json.target_commitish version&.target_commitish +json.name version&.name +json.sha version&.sha +json.body version&.body +json.url version&.url +json.tarball_url render_tar_url(@owner, @repository, version&.tag_name) +json.zipball_url render_zip_url(@owner, @repository, version&.tag_name) +json.draft version&.draft ? "草稿" : (version&.prerelease ? "预发行" : "稳定") json.created_at format_time(version.created_at.to_s.to_time) json.published_at format_time(version.created_at.to_s.to_time) json.user_name user.present? ? user.try(:show_real_name) : "" diff --git a/app/views/version_releases/index.json.jbuilder b/app/views/version_releases/index.json.jbuilder index 8efb88bc..300b1b60 100644 --- a/app/views/version_releases/index.json.jbuilder +++ b/app/views/version_releases/index.json.jbuilder @@ -3,18 +3,14 @@ json.user_permission @user_permission json.user_admin_permission @user_admin_permission # json.releases @version_releases json.releases do - json.array! @version_releases.to_a.each do |re| - if re.present? - user = User.select(:id, :gitea_uid, :login, :lastname,:firstname, :nickname).find_by_gitea_uid(re["author"]["id"]) - version = @forge_releases.find_by(version_gid: re["id"]) - if @user_permission && re["draft"] - json.partial! "version_release", locals: {version: version, user: user, re: re} - else - unless re["draft"] - json.partial! "version_release", locals: {version: version, user: user, re: re} - end + json.array! @version_releases.each do |version| + version.update_sha if version.sha.nil? + if @user_permission && version&.draft + json.partial! "version_release", locals: {version: version, user: version&.user} + else + unless version&.draft + json.partial! "version_release", locals: {version: version, user: version&.user} end end - end end diff --git a/app/views/version_releases/show.json.jbuilder b/app/views/version_releases/show.json.jbuilder index 803ae477..716f5d7b 100644 --- a/app/views/version_releases/show.json.jbuilder +++ b/app/views/version_releases/show.json.jbuilder @@ -1,2 +1,2 @@ -user = User.select(:id, :gitea_uid, :login, :lastname,:firstname, :nickname).find_by_gitea_uid(@release["author"]["id"]) -json.partial! "version_release", locals: {version: @version, user: user, re: @release} \ No newline at end of file + +json.partial! "version_release", locals: {version: @version, user: @version&.user} \ No newline at end of file diff --git a/db/migrate/20210930025555_add_sha_to_version_releases.rb b/db/migrate/20210930025555_add_sha_to_version_releases.rb new file mode 100644 index 00000000..475d361f --- /dev/null +++ b/db/migrate/20210930025555_add_sha_to_version_releases.rb @@ -0,0 +1,5 @@ +class AddShaToVersionReleases < ActiveRecord::Migration[5.2] + def change + add_column :version_releases, :sha, :string + end +end From 59fe010fdbe49947eccd4e332fc6fcecfecf0c96 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 30 Sep 2021 11:15:11 +0800 Subject: [PATCH 083/135] add: page totalcount --- app/views/version_releases/index.json.jbuilder | 1 + 1 file changed, 1 insertion(+) diff --git a/app/views/version_releases/index.json.jbuilder b/app/views/version_releases/index.json.jbuilder index 300b1b60..85d1be25 100644 --- a/app/views/version_releases/index.json.jbuilder +++ b/app/views/version_releases/index.json.jbuilder @@ -14,3 +14,4 @@ json.releases do end end end +json.total_count @version_releases.total_count \ No newline at end of file From f7ba082944951fd0cf7501bd58d8c4ab27db1b08 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 30 Sep 2021 14:59:37 +0800 Subject: [PATCH 084/135] fix: readme return decode data --- app/controllers/repositories_controller.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/controllers/repositories_controller.rb b/app/controllers/repositories_controller.rb index db1db604..d66a25a9 100644 --- a/app/controllers/repositories_controller.rb +++ b/app/controllers/repositories_controller.rb @@ -1,4 +1,5 @@ class RepositoriesController < ApplicationController + include RepositoriesHelper include ApplicationHelper include OperateProjectAbilityAble include Repository::LanguagesPercentagable @@ -198,7 +199,8 @@ class RepositoriesController < ApplicationController result = Gitea::Repository::Readme::GetService.call(@owner.login, @repository.identifier, params[:ref], current_user&.gitea_token) end @readme = result[:status] === :success ? result[:body] : nil - + @readme['content'] = decode64_content(@readme, @owner, @repository, params[:ref]) + Rails.logger.info "======+#{@readme}" render json: @readme.slice("type", "encoding", "size", "name", "path", "content", "sha") rescue render json: nil From 689f2658580e0a94e912b447ece7e7879b337326 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 30 Sep 2021 14:59:46 +0800 Subject: [PATCH 085/135] fix --- app/controllers/repositories_controller.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/app/controllers/repositories_controller.rb b/app/controllers/repositories_controller.rb index d66a25a9..9887a291 100644 --- a/app/controllers/repositories_controller.rb +++ b/app/controllers/repositories_controller.rb @@ -200,7 +200,6 @@ class RepositoriesController < ApplicationController end @readme = result[:status] === :success ? result[:body] : nil @readme['content'] = decode64_content(@readme, @owner, @repository, params[:ref]) - Rails.logger.info "======+#{@readme}" render json: @readme.slice("type", "encoding", "size", "name", "path", "content", "sha") rescue render json: nil From 9685c9717761d12c8d59241c24bf548bdcc60424 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 30 Sep 2021 17:40:18 +0800 Subject: [PATCH 086/135] fix: add user login and release authorize --- app/controllers/version_releases_controller.rb | 5 +++++ app/views/version_releases/_version_release.json.jbuilder | 1 + 2 files changed, 6 insertions(+) diff --git a/app/controllers/version_releases_controller.rb b/app/controllers/version_releases_controller.rb index c66a4bf0..2d7546a1 100644 --- a/app/controllers/version_releases_controller.rb +++ b/app/controllers/version_releases_controller.rb @@ -2,6 +2,7 @@ class VersionReleasesController < ApplicationController before_action :load_repository before_action :set_user before_action :require_login, except: [:index, :show] + before_action :check_release_authorize, except: [:index, :show] before_action :find_version , only: [:show, :edit, :update, :destroy] def index @@ -161,4 +162,8 @@ class VersionReleasesController < ApplicationController end end + def check_release_authorize + return render_forbidden("您没有权限进行此操作.") unless current_user.admin? || @project.manager?(current_user) + end + end diff --git a/app/views/version_releases/_version_release.json.jbuilder b/app/views/version_releases/_version_release.json.jbuilder index ddf59ee7..1ccdbe61 100644 --- a/app/views/version_releases/_version_release.json.jbuilder +++ b/app/views/version_releases/_version_release.json.jbuilder @@ -12,6 +12,7 @@ json.draft version&.draft ? "草稿" : (version&.prerelease ? "预发行" : "稳 json.created_at format_time(version.created_at.to_s.to_time) json.published_at format_time(version.created_at.to_s.to_time) json.user_name user.present? ? user.try(:show_real_name) : "" +json.user_login user&.login json.image_url user.present? ? url_to_avatar(user) : "" json.attachments do json.array! version.try(:attachments) do |attachment| From 588850440e8c6cb03c55029dd3e01b971b45b307 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 30 Sep 2021 19:49:17 +0800 Subject: [PATCH 087/135] fix: decode error --- app/controllers/repositories_controller.rb | 1 + app/helpers/repositories_helper.rb | 2 +- app/views/repositories/_simple_entry.json.jbuilder | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/app/controllers/repositories_controller.rb b/app/controllers/repositories_controller.rb index 9887a291..124dbc87 100644 --- a/app/controllers/repositories_controller.rb +++ b/app/controllers/repositories_controller.rb @@ -74,6 +74,7 @@ class RepositoriesController < ApplicationController def sub_entries file_path_uri = URI.parse(URI.encode(params[:filepath].to_s.strip)) + @path = Gitea.gitea_config[:domain]+"/#{@project.owner.login}/#{@project.identifier}/raw/branch/#{@ref}/" if @project.educoder? if params[:type] === 'file' diff --git a/app/helpers/repositories_helper.rb b/app/helpers/repositories_helper.rb index d34e3a8d..1096d1d2 100644 --- a/app/helpers/repositories_helper.rb +++ b/app/helpers/repositories_helper.rb @@ -6,7 +6,7 @@ module RepositoriesHelper def render_decode64_content(str) return nil if str.blank? - Base64.decode64(str).force_encoding("UTF-8") + Base64.decode64(str).force_encoding("UTF-8").encode("UTF-8", invalid: :replace) end def download_type(str) diff --git a/app/views/repositories/_simple_entry.json.jbuilder b/app/views/repositories/_simple_entry.json.jbuilder index cc9bdc3a..6f33ac35 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 decode64_content(entry, @owner, @repository, @ref) + json.content decode64_content(entry, @owner, @repository, @ref, @path) json.target entry['target'] download_url = From 76183344bc6c96a38220313db9378e1ff0785f7c Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 8 Oct 2021 14:04:13 +0800 Subject: [PATCH 088/135] fix: main content_type --- app/controllers/main_controller.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/controllers/main_controller.rb b/app/controllers/main_controller.rb index 7b7468f9..afe76789 100644 --- a/app/controllers/main_controller.rb +++ b/app/controllers/main_controller.rb @@ -23,9 +23,9 @@ class MainController < ApplicationController # TODO: 这块之后需要整合,者架构重新变化,统一跳转到index后再路由分发 if params[:path] && params[:path]&.include?("h5educoderbuild") && params[:path].split("/").first == "h5educoderbuild" - render file: 'public/h5educoderbuild/index.html', :layout => false + render file: 'public/h5educoderbuild/index.html', :layout => false, :content_type=> 'text/html' else - render file: 'public/react/build/index.html', :layout => false + render file: 'public/react/build/index.html', :layout => false, :content_type=> 'text/html' end end From 9d5503f09fefcb79665d344ddbb1a8bb2f743592 Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 8 Oct 2021 14:43:46 +0800 Subject: [PATCH 089/135] fix: lastcommit --- app/controllers/repositories_controller.rb | 10 ++++- .../repository/commits/file_list_service.rb | 43 +++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 app/services/gitea/repository/commits/file_list_service.rb diff --git a/app/controllers/repositories_controller.rb b/app/controllers/repositories_controller.rb index 124dbc87..5080dd94 100644 --- a/app/controllers/repositories_controller.rb +++ b/app/controllers/repositories_controller.rb @@ -254,8 +254,14 @@ class RepositoriesController < ApplicationController # TODO 获取最新commit信息 def project_commits - Gitea::Repository::Commits::ListService.new(@project.owner.login, @project.identifier, - sha: get_ref, page: 1, limit: 1, token: current_user&.gitea_token).call + 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 diff --git a/app/services/gitea/repository/commits/file_list_service.rb b/app/services/gitea/repository/commits/file_list_service.rb new file mode 100644 index 00000000..b1606a0f --- /dev/null +++ b/app/services/gitea/repository/commits/file_list_service.rb @@ -0,0 +1,43 @@ +# Get a list of all commits from a repository +class Gitea::Repository::Commits::FileListService < Gitea::ClientService + attr_reader :owner, :repo_name, :filepath, :args + + # sha: SHA or branch to start listing commits from (usually 'master') + # ex: + # Gitea::Repository::Commits::ListService.new(@project.owner.login, @project.identifier, + # sha: params[:sha], page: params[:page], limit: params[:limit], token: current_user&.gitea_token).call + def initialize(owner, repo_name, filepath, **args) + @owner = owner + @repo_name = repo_name + @filepath = filepath + @args = args + end + + def call + response = get(url, params) + render_result(response) + end + + private + def params + {sha: args[:sha] || 'master', page: args[:page] || PAGINATE_DEFAULT_PAGE, limit: args[:limit] || PAGINATE_DEFAULT_LIMIT, token: args[:token] || "" } + end + + def url + "/repos/#{owner}/#{repo_name}/file_commits/#{filepath}".freeze + end + + def render_result(response) + case response.status + when 200 + result = {} + headers = response.headers.to_hash + body = JSON.parse(response.body) + total_count = headers["x-total"] + result.merge(total_count: total_count.to_i, body: body) + else + nil + # {status: -1, message: "#{body['message']}"} + end + end +end From f957b6f95e24eacbb3d3ff169348b3d8b6f2bec5 Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 8 Oct 2021 14:58:29 +0800 Subject: [PATCH 090/135] fix: commits filter by filepath --- app/controllers/repositories_controller.rb | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/app/controllers/repositories_controller.rb b/app/controllers/repositories_controller.rb index 5080dd94..e1184fd1 100644 --- a/app/controllers/repositories_controller.rb +++ b/app/controllers/repositories_controller.rb @@ -105,8 +105,14 @@ class RepositoriesController < ApplicationController end def commits - @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 + 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 def commits_slice From 46ab55d50f555c2bd318bd93023c90a07421e592 Mon Sep 17 00:00:00 2001 From: yystopf Date: Sat, 9 Oct 2021 09:50:35 +0800 Subject: [PATCH 091/135] fix: issue change operate permission and repository detail remove garbage --- app/controllers/issues_controller.rb | 4 +- app/controllers/repositories_controller.rb | 10 ---- app/services/repositories/detail_service.rb | 52 +++++++------------- app/views/repositories/detail.json.jbuilder | 16 +----- app/views/repositories/entries.json.jbuilder | 1 - 5 files changed, 22 insertions(+), 61 deletions(-) diff --git a/app/controllers/issues_controller.rb b/app/controllers/issues_controller.rb index 7b90e310..bfa15aa5 100644 --- a/app/controllers/issues_controller.rb +++ b/app/controllers/issues_controller.rb @@ -15,7 +15,7 @@ class IssuesController < ApplicationController include TagChosenHelper def index - @user_admin_or_member = current_user.present? && current_user.logged? && (current_user.admin || @project.member?(current_user)) + @user_admin_or_member = current_user.present? && current_user.logged? && (current_user.admin || @project.member?(current_user) || @project.is_public?) issues = @project.issues.issue_issue.issue_index_includes issues = issues.where(is_private: false) unless @user_admin_or_member @@ -453,7 +453,7 @@ class IssuesController < ApplicationController end def operate_issue_permission - return render_forbidden("您没有权限进行此操作.") unless current_user.admin? || @project.member?(current_user) + return render_forbidden("您没有权限进行此操作.") unless current_user.present? && current_user.logged? && (current_user.admin? || @project.member?(current_user) || @project.is_public?) end def export_issues(issues) diff --git a/app/controllers/repositories_controller.rb b/app/controllers/repositories_controller.rb index e1184fd1..35f11f47 100644 --- a/app/controllers/repositories_controller.rb +++ b/app/controllers/repositories_controller.rb @@ -55,16 +55,6 @@ class RepositoriesController < ApplicationController @entries = Gitea::Repository::Entries::ListService.new(@owner, @project.identifier, ref: @ref).call @entries = @entries.present? ? @entries.sort_by{ |hash| hash['type'] } : [] @path = Gitea.gitea_config[:domain]+"/#{@project.owner.login}/#{@project.identifier}/raw/branch/#{@ref}/" - - # TODO - # 临时处理readme文件问题 - result = Gitea::Repository::Readme::GetService.call(@owner.login, @project.identifier, @ref, @owner&.gitea_token) - @readme = - if result[:status] == :success - result[:body] - else - {} - end end end diff --git a/app/services/repositories/detail_service.rb b/app/services/repositories/detail_service.rb index 984f10d5..4b29d50a 100644 --- a/app/services/repositories/detail_service.rb +++ b/app/services/repositories/detail_service.rb @@ -8,29 +8,25 @@ class Repositories::DetailService < ApplicationService end def call - if @repo.project.educoder? - return { - repo: {}, - release: [], - branch: [], - branch_type: [], - tag: [], - contributor: [], - language: {}, - readme: {} - } - else - return { - repo: repo_suitable, - release: release_suitable, - branch: branch_suitable, - branch_slice: branch_slice_suitable, - tag: tag_suitable, - contributor: contributor_suitable, - language: language_suitable, - readme: readme_suitable - } - end + return { + repo: repo_suitable, + release: release_suitable, + branch: branch_suitable, + tag: tag_suitable, + contributor: contributor_suitable, + language: language_suitable + } + rescue + return { + repo: {}, + release: [], + branch: [], + branch_type: [], + tag: [], + contributor: [], + language: {}, + readme: {} + } end private @@ -48,11 +44,6 @@ class Repositories::DetailService < ApplicationService branches.is_a?(Hash) && branches.key?(:status) ? [] : branches end - def branch_slice_suitable - branches = Gitea::Repository::Branches::ListSliceService.call(@owner, @repo.identifier) - branches.is_a?(Hash) && branches.key?(:status) ? [] : branches - end - def tag_suitable tags = Gitea::Repository::Tags::ListService.call(@owner&.gitea_token, @owner.login, @repo.identifier) tags.is_a?(Hash) && tags[:status] == -1 ? [] : tags @@ -67,9 +58,4 @@ class Repositories::DetailService < ApplicationService result = Gitea::Repository::Languages::ListService.call(@owner.login, @repo.identifier, @user&.gitea_token) result[:status] === :success ? hash_transform_precentagable(result[:body]) : nil end - - def readme_suitable - result = Gitea::Repository::Readme::GetService.call(@owner.login, @repo.identifier, @repo.default_branch, @owner.gitea_token) - result[:status] === :success ? result[:body] : nil - end end diff --git a/app/views/repositories/detail.json.jbuilder b/app/views/repositories/detail.json.jbuilder index 18b5dd88..c0807708 100644 --- a/app/views/repositories/detail.json.jbuilder +++ b/app/views/repositories/detail.json.jbuilder @@ -1,11 +1,6 @@ json.content @project.content json.website @project.website json.lesson_url @project.lesson_url -if @result[:readme].blank? - json.readme nil -else - json.readme @result[:readme].merge(content: readme_render_decode64_content(@result[:readme]["content"], nil)) -end json.identifier render_identifier(@project) json.invite_code @project.invite_code json.name @project.name @@ -72,15 +67,6 @@ json.branches do end json.total_count @result[:branch].size end -json.branches_slice do - json.list @result[:branch_slice].each do |branch_slice| - json.branch_type branch_slice["branch_name"] - json.list branch_slice["branches"].each do |branch| - json.name branch["name"] - end - end - json.total_count @result[:branch_slice].size -end json.tags do json.list @result[:tag].each do |tag| json.name tag["name"] @@ -104,6 +90,6 @@ json.contributors do end json.total_count total_count end -json.languages @result[:language] +json.languages @result[:language].blank? ? nil : @result[:language] json.partial! 'author', locals: { user: @project.owner } diff --git a/app/views/repositories/entries.json.jbuilder b/app/views/repositories/entries.json.jbuilder index 8c028e6a..8d1e67be 100644 --- a/app/views/repositories/entries.json.jbuilder +++ b/app/views/repositories/entries.json.jbuilder @@ -61,5 +61,4 @@ if @project.forge? end end - json.readme @readme.merge(content: readme_render_decode64_content(@readme["content"], nil)) end From 6e653f768a6492d95b4dca23fc29b86ce91bb3dd Mon Sep 17 00:00:00 2001 From: yystopf Date: Sat, 9 Oct 2021 10:45:13 +0800 Subject: [PATCH 092/135] fix: pullrequest comments_count --- app/views/pull_requests/show.json.jbuilder | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/views/pull_requests/show.json.jbuilder b/app/views/pull_requests/show.json.jbuilder index 6f634390..04680938 100644 --- a/app/views/pull_requests/show.json.jbuilder +++ b/app/views/pull_requests/show.json.jbuilder @@ -5,7 +5,7 @@ json.project_identifier @project.identifier json.pr_time time_from_now(@pull_request.updated_at) json.commits_count @pull_request.commits_count json.files_count @pull_request.files_count -json.comments_count @pull_request.comments_count +json.comments_count @issue.get_journals_size json.pull_request do json.extract! @pull_request, :id,:base, :head, :status,:fork_project_id, :is_original From a22327d0df7403aec002e507fcc6ac351d566307 Mon Sep 17 00:00:00 2001 From: yystopf Date: Sat, 9 Oct 2021 14:19:02 +0800 Subject: [PATCH 093/135] fix: add comments_total_count --- app/services/gitea/pull_request/files_service.rb | 2 +- app/views/pull_requests/show.json.jbuilder | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/app/services/gitea/pull_request/files_service.rb b/app/services/gitea/pull_request/files_service.rb index 9785588e..a8cb2662 100644 --- a/app/services/gitea/pull_request/files_service.rb +++ b/app/services/gitea/pull_request/files_service.rb @@ -24,7 +24,7 @@ class Gitea::PullRequest::FilesService < Gitea::ClientService def params Hash.new.merge(token: token) end - + def url "/repos/#{owner}/#{repo}/pulls/#{pull_number}/files".freeze end diff --git a/app/views/pull_requests/show.json.jbuilder b/app/views/pull_requests/show.json.jbuilder index 04680938..5c30bd17 100644 --- a/app/views/pull_requests/show.json.jbuilder +++ b/app/views/pull_requests/show.json.jbuilder @@ -5,7 +5,8 @@ json.project_identifier @project.identifier json.pr_time time_from_now(@pull_request.updated_at) json.commits_count @pull_request.commits_count json.files_count @pull_request.files_count -json.comments_count @issue.get_journals_size +json.comments_count @issue.journals.parent_journals.size +json.comments_total_count @issue.get_journals_size json.pull_request do json.extract! @pull_request, :id,:base, :head, :status,:fork_project_id, :is_original From 350502b4993f48700444e9a3fdcac0ee43513397 Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 11 Oct 2021 10:07:35 +0800 Subject: [PATCH 094/135] fix: pullrequest create info --- app/controllers/pull_requests_controller.rb | 1 - app/views/pull_requests/_detail.json.jbuilder | 24 +++++++++++++++++++ app/views/pull_requests/create.json.jbuilder | 2 ++ 3 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 app/views/pull_requests/_detail.json.jbuilder create mode 100644 app/views/pull_requests/create.json.jbuilder diff --git a/app/controllers/pull_requests_controller.rb b/app/controllers/pull_requests_controller.rb index 5fddbbc6..b75fcf92 100644 --- a/app/controllers/pull_requests_controller.rb +++ b/app/controllers/pull_requests_controller.rb @@ -61,7 +61,6 @@ class PullRequestsController < ApplicationController @pull_request.bind_gitea_pull_request!(@gitea_pull_request[:body]["number"]) SendTemplateMessageJob.perform_later('PullRequestAssigned', current_user.id, @pull_request&.id) SendTemplateMessageJob.perform_later('ProjectPullRequest', current_user.id, @pull_request&.id) - render_ok else render_error("create pull request error: #{@gitea_pull_request[:status]}") raise ActiveRecord::Rollback diff --git a/app/views/pull_requests/_detail.json.jbuilder b/app/views/pull_requests/_detail.json.jbuilder new file mode 100644 index 00000000..06c6377a --- /dev/null +++ b/app/views/pull_requests/_detail.json.jbuilder @@ -0,0 +1,24 @@ +pr = issue.pull_request +json.pull_request_id pr.id +json.pull_request_status pr.status +json.pull_request_head pr.head +json.pull_request_base pr.base +json.pull_request_staus pr.status == 1 ? "merged" : (pr.status == 2 ? "closed" : "open") +json.is_original pr.is_original +json.fork_project_id pr&.fork_project_id +json.fork_project_identifier pr&.fork_project&.identifier +json.fork_project_user pr&.fork_project&.owner.try(:login) + + +json.id issue.id +json.name issue.subject +json.pr_time time_from_now(pr.status == 1 ? pr.updated_at : issue.updated_on) +json.assign_user_name issue.get_assign_user.try(:show_real_name) +json.assign_user_login issue.get_assign_user.try(:login) +json.author_name issue.user.try(:show_real_name) +json.author_login issue.user.try(:login) +json.avatar_url url_to_avatar(issue.user) +json.priority issue.priority.try(:name) +json.version issue.version.try(:name) +json.journals_count issue.get_journals_size +json.issue_tags issue.get_issue_tags \ No newline at end of file diff --git a/app/views/pull_requests/create.json.jbuilder b/app/views/pull_requests/create.json.jbuilder new file mode 100644 index 00000000..1483420d --- /dev/null +++ b/app/views/pull_requests/create.json.jbuilder @@ -0,0 +1,2 @@ +json.partial! "commons/success" +json.partial! 'detail', pr: @pull_request, issue: @pull_request.issue \ No newline at end of file From 48b5117062326ca15678eda04bd7005e77754a6d Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 11 Oct 2021 18:10:28 +0800 Subject: [PATCH 095/135] fix: check pr can merge change redirect url --- app/controllers/pull_requests_controller.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/controllers/pull_requests_controller.rb b/app/controllers/pull_requests_controller.rb index b75fcf92..fe04dd5e 100644 --- a/app/controllers/pull_requests_controller.rb +++ b/app/controllers/pull_requests_controller.rb @@ -200,7 +200,7 @@ class PullRequestsController < ApplicationController if can_merge.present? render json: { status: -2, - message: "在这些分支之间的合并请求已存在:#{can_merge.first.try(:title)}", + message: "在这些分支之间的合并请求已存在:#{can_merge.first.try(:title)}", } else normal_status(0, "可以合并") From 301f82f84dc996b6d4cd03f99be4fa77f5204083 Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 11 Oct 2021 18:13:42 +0800 Subject: [PATCH 096/135] fix: check pr can merge change redirect url --- app/controllers/compare_controller.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/controllers/compare_controller.rb b/app/controllers/compare_controller.rb index bc81da56..8e8e3ec9 100644 --- a/app/controllers/compare_controller.rb +++ b/app/controllers/compare_controller.rb @@ -24,7 +24,7 @@ class CompareController < ApplicationController @exist_pullrequest = @project.pull_requests.where(is_original: false, head: @base, base: @head, status: 0).take end if @exist_pullrequest.present? - return -2, "在这些分支之间的合并请求已存在:#{@exist_pullrequest.try(:title)}" + return -2, "在这些分支之间的合并请求已存在:#{@exist_pullrequest.try(:title)}" else if @compare_result["Commits"].blank? && @compare_result["Diff"].blank? return -2, "分支内容相同,无需创建合并请求" From 0bdbc09ec0de325f551afeb94a38cc37f2762a34 Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 11 Oct 2021 18:15:10 +0800 Subject: [PATCH 097/135] fix: check pr can merge change redirect url --- app/controllers/compare_controller.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/controllers/compare_controller.rb b/app/controllers/compare_controller.rb index 8e8e3ec9..6dc9baad 100644 --- a/app/controllers/compare_controller.rb +++ b/app/controllers/compare_controller.rb @@ -24,7 +24,7 @@ class CompareController < ApplicationController @exist_pullrequest = @project.pull_requests.where(is_original: false, head: @base, base: @head, status: 0).take end if @exist_pullrequest.present? - return -2, "在这些分支之间的合并请求已存在:#{@exist_pullrequest.try(:title)}" + return -2, "在这些分支之间的合并请求已存在:#{@exist_pullrequest.try(:title)}" else if @compare_result["Commits"].blank? && @compare_result["Diff"].blank? return -2, "分支内容相同,无需创建合并请求" From 1fa44535bbd51c0f4fef3dd686b261d7cf83f815 Mon Sep 17 00:00:00 2001 From: jasder Date: Tue, 12 Oct 2021 18:36:14 +0800 Subject: [PATCH 098/135] =?UTF-8?q?FIX=20=E6=9B=B4=E6=96=B0pulls=E7=9A=84a?= =?UTF-8?q?pi=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 31 + app/docs/slate/source/includes/_pulls.md | 501 ++++++++++++ public/docs/api.html | 961 ++++++++++++++++++++++- 3 files changed, 1492 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a5250040..ecb743b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,35 @@ # Changelog +## [v3.2.0](https://forgeplus.trustie.net/projects/jasder/forgeplus/releases) - 2021-06-09 + +### ENHANCEMENTS + * ADD 集成邮件和平台站内信等通知系统 + * Fix 代码库二级页面-优化文件子目录浏览功能(#50388) + * Fix 代码库二级页面-优化commit提交详情页页面排版及数据显示(#50372) + * Fix 代码库二级页面-优化commit提交信息列表页加载方式和数据排序功能(#50348) + * Fix 代码库二级页面-优化创建发行版功能(#50346) + * Fix 代码库二级页面-优化标签列表页功能(#50344) + * Fix 代码库二级页面-优化发行版本列表页功能(#50345) + * Fix 代码库二级页面-优化分支列表页功能(#50343) + * Fix 其他问题优化(#51581) (#51343) (#51108) + +--- + +### BUGFIXES + * Fix 发行版—标签跳转链接错误(#51666) + * Fix 文件预览报错(#51660) + * Fix 标签创建时间显示错误(#51658) + * Fix 分支列表中头像显示问题(#51656) + * Fix 文本信息过长(#51630) (#51626) + * Fix 版本库中附件下载400(#51625) + * Fix loading页面优化(#51588) + * Fix 提交详情页面优化(#51577) + * Fix 修复易修复制功能(#51569) + * Fix 修复新建发行版用户信息显示错误的问题(#51665) + * Fix 修复查看文件详细信息报错的问题(#51561) + * Fix 修复提交记录中时间显示格式问题(#51526) + * Fix 组织下项目更加更新时间倒序排序(#50833) + + ## [v3.1.0](https://forgeplus.trustie.net/projects/jasder/forgeplus/releases) - 2021-06-09 * ENHANCEMENTS diff --git a/app/docs/slate/source/includes/_pulls.md b/app/docs/slate/source/includes/_pulls.md index 1df50f6b..b9ad3b0b 100644 --- a/app/docs/slate/source/includes/_pulls.md +++ b/app/docs/slate/source/includes/_pulls.md @@ -1 +1,502 @@ # Pulls + + +## Get a pull request +获取合并请求详情接口 + +> 示例: + +```shell +curl -X GET http://localhost:3000/api/Jasder/gitlink/pulls/88.json +``` + +```javascript +await octokit.request('GET /api/Jasder/gitlink/pulls/88.json') +``` + +### HTTP 请求 +`GET /api/:owner/:repo/pulls/:id.json` + +### 请求参数: +参数 | 必选 | 默认 | 类型 | 字段说明 +--------- | ------- | ------- | -------- | ---------- +|owner |是| |string |用户登录名 | +|repo |是| |string |项目标识identifier | +|id |是| | integer | pull id值 | + + + + +> 返回的JSON示例: + +```json +{ + "status": 0, + "message": "响应成功", + "project_name": "Gitlink", + "identifier": "forgeplus", + "project_identifier": "forgeplus", + "pr_time": "52分钟前", + "commits_count": 229, + "files_count": 328, + "comments_count": 0, + "comments_total_count": 0, + "pull_request": { + "id": 1189, + "base": "master", + "head": "develop", + "status": 0, + "fork_project_id": null, + "is_original": false, + "pull_request_staus": "open", + "fork_project_user": null, + "create_user": "jasder", + "mergeable": true, + "state": "open" + }, + "issue": { + "id": 51888, + "subject": "FIx release v3.2.0", + "description": null, + "is_private": false, + "branch_name": null, + "project_author_name": "Gitlink", + "closed_on": "", + "created_at": "2021-10-12 15:51", + "assign_user_name": "victor", + "assign_user_login": "moshenglv", + "author_name": "段甲生", + "author_login": "jasder", + "author_picture": "images/avatars/User/36480?t=1615520120", + "issue_status": "新增", + "priority": "正常", + "version": null, + "issue_tags": null + }, + "conflict_files": [] +} +``` + +## 获取pull request文件列表 +获取pull request文件列表 + +> 示例: + +```shell +curl -X GET \ +http://localhost:3000/api/Jason/gitlink/pulls/1/files.json +``` + +```javascript +await octokit.request('GET /api/jasder/gitlink/pulls/1/files.json') +``` + +### HTTP 请求 +`GET /api/:owner/:repo/pulls/:id/files.json` + +### 请求参数: +|参数名|必选|类型|说明| +|-|-|-|-| +|owner |是|string |用户登录名 | +|repo |是|string |project's identifier | +|id |是|int |pull request's id | + + +### 返回字段说明: +参数 | 类型 | 字段说明 +--------- | ----------- | ----------- +|-|-|-| +|files_count |int|文件更改的总数量| +|total_addition |int|添加代码总行数| +|total_deletion |int|删除代码总行数| +|files |array|| +|-- sha |string|commit's sha value| +|-- name |string|当前文件名| +|-- old_name |string| 修改之前的文件名称,与name相同的话,说明文件名未更改| +|-- addition |int|文件添加的行数| +|-- deletion |int|文件删除的行数| +|-- type |int|文件类型, 1: 表示该文件只添加了内容,2: 表示该文件内容有修改, 3: 表示文件被删除或者改文件只删除了内容| +|-- isCreated |boolean|当前文件是否为新增文件, true: 是, false: 否| +|-- isDeleted |boolean|当前文件是否被删除, true: 是,false: 否| +|-- isBin |boolean|当前文件是否为二进制文件,true: 是,false: 否| +|-- isLFSFile |boolean|当前文件是否为LFS文件,true: 是,false: 否| +|-- isRenamed |boolean|当前文件是否被重命名,true: 是,false: 否| +|-- sections |array|| +|---- fileName |string|文件名称| +|---- lines |array|| +|------ leftIdx |string|文件变动之前所在行数| +|------ rightIdx |string|文件更改后所在行数| +|------ type |string|文件变更类型,1: 新增,2: 修改, 3: 删除, 4: diff统计信息| +|------ content |string|文件变更的内容| +|------ sectionInfo |object|| +|-------- path |string|文件相对仓库的路径| +|-------- lastLeftIdx |int|| +|-------- lastRightIdx |int|| +|-------- leftHunkSize |int|文件变更之前的行数| +|-------- rightHunkSize |int|文件变更之后的行数(及当前页面编辑器显示的总行数)| +|-------- leftIdx |int|文件变更之前所在行数| +|-------- rightIdx |int|文件变更之后所在行数(即:页面编辑器开始显示的行数)| + + + +> 返回的JSON示例: + +```json +{ + "files_count": 6, + "total_addition": 447, + "total_deletion": 0, + "files": [ + { + "sha": "xefenisnii", + "name": "文件.txt", + "old_name": "文件.txt", + "index": 6, + "addition": 2, + "deletion": 0, + "type": 1, + "isCreated": true, + "isDeleted": false, + "isBin": false, + "isLFSFile": false, + "isRenamed": false, + "isSubmodule": false, + "sections": [ + { + "fileName": "文件.txt", + "name": "", + "lines": [ + { + "leftIdx": 0, + "rightIdx": 0, + "type": 4, + "content": "@@ -0,0 +1,2 @@", + "sectionInfo": { + "path": null, + "lastLeftIdx": null, + "lastRightIdx": null, + "leftIdx": 0, + "rightIdx": 0, + "leftHunkSize": null, + "rightHunkSize": null + } + }, + { + "leftIdx": 0, + "rightIdx": 1, + "type": 2, + "content": "+用例图一致性更新", + "sectionInfo": null + }, + { + "leftIdx": 0, + "rightIdx": 2, + "type": 2, + "content": "+工程文件直接上传会有文件缺失,现在压缩后上传", + "sectionInfo": null + } + ] + } + ] + } + ] +} +``` + + +## 获取pull request的commits列表 +获取pull request的commits列表 + +> 示例: + +```shell +curl -X GET http://localhost:3000/api/jasder/jasder_test/pulls/1/commits.json +``` + +```javascript +await octokit.request('GET /api/jasder/jasder_test/pulls/1/commits.json') +``` + +### HTTP 请求 +`GET /api/:owner/:repo/pulls/:id/commits.json` + +### 请求参数: +|参数名|必选|类型|说明| +|-|-|-|-| +|owner |是|string |用户登录名 | +|repo |是|string |project's identifier | +|id |是|int |pull request's id | + + +### 返回字段说明: +参数 | 类型 | 字段说明 +--------- | ----------- | ----------- +|commits_count |int|commits总数量| +|commits |array|| +|-- author |object|项目作者| +|---- login |string|用户login| +|---- name |string|用户姓名| +|---- image_url |string|用户头像| +|-- committer |object|commit提交用户| +|---- login |string|用户login| +|---- name |string|用户姓名| +|---- image_url |string|用户头像| +|-- timestamp |int|commit的unix时间戳| +|-- time_from_now|string|commit’s 提交时间距当前时间的时间值| +|-- message |string|commit说明信息| +|-- sha |string|commit’s sha值| + + +> 返回的JSON示例: + +```json +{ + "commits_count": 1, + "commits": [ + { + "author": { + "id": 36480, + "login": "jasder", + "name": "段甲生", + "image_url": "avatars/User/b" + }, + "committer": { + "id": 36480, + "login": "jasder", + "name": "段甲生", + "image_url": "avatars/User/b" + }, + "timestamp": 1604382982, + "time_from_now": "3小时前", + "message": "add some file\n* Add the tag list page to the release page\n* Apply suggestions from code review\n* Add the tags list view\n* Add the delete tag way on ui\n* Not delete tag and clear message when delete a release\n", + "sha": "8f5faee0d3b3be1b8063e84da0c79dd75327b968" + } + ] +} +``` + +## Compare two commits +Compare two commits + +> 示例: + +```shell +curl -X GET \ +http://localhost:3000/api/Jason/test-txt/compare/master...develop + +curl -X GET \ +http://localhost:3000/api/Jason/test-txt/compare/master...Jason/test-txt:develop +``` + +```javascript +await octokit.request('GET /api/Jason/test-txt/compare/master...Jason/test-txt:develop') +``` + +### HTTP 请求 +`GET /api/:owner/:repo/compare/{base}...{head}.json` + +### 请求参数: +|参数名|必选|类型|说明| +|-|-|-|-| +|owner |是|string |用户登录名 | +|repo |是|string |project's identifier | +|base |是|string |pull request's id | +|head |是|string |pull request's id | + + +### 返回字段说明: +参数 | 类型 | 字段说明 +--------- | ----------- | ----------- +|-|-|-| +|commits_count |int|commits总数量| +|commits |array|| +|-- author |object|项目作者| +|---- login |string|用户login| +|---- name |string|用户姓名| +|---- image_url |string|用户头像| +|-- committer |object|commit提交用户| +|---- login |string|用户login| +|---- name |string|用户姓名| +|---- image_url |string|用户头像| +|-- timestamp |int|commit的unix时间戳| +|-- time_from_now|string|commit’s 提交时间距当前时间的时间值| +|-- message |string|commit说明信息| +|-- sha |string|commit’s sha值| +|diff |object|| +|-- files_count |int|文件更改的总数量| +|-- total_addition |int|添加代码总行数| +|-- total_deletion |int|删除代码总行数| +|-- files |Array|| +|-- sha |string|commit's sha | +|-- name |string|当前文件名| +|-- old_name |string| 修改之前的文件名称,与name相同的话,说明文件名未更改| +|-- addition |int|文件添加的行数| +|-- deletion |int|文件删除的行数| +|-- type |int|文件类型, 1: 表示该文件只添加了内容,2: 表示该文件内容有修改, 3: 表示文件被删除或者改文件只删除了内容| +|-- isCreated |boolean|当前文件是否为新增文件, true: 是, false: 否| +|-- isDeleted |boolean|当前文件是否被删除, true: 是,false: 否| +|-- isBin |boolean|当前文件是否为二进制文件,true: 是,false: 否| +|-- isLFSFile |boolean|当前文件是否为LFS文件,true: 是,false: 否| +|-- isRenamed |boolean|当前文件是否被重命名,true: 是,false: 否| +|-- sections |array|| +|---- fileName |string|文件名称| +|---- lines |array|| +|------ leftIdx |string|文件变动之前所在行数| +|------ rightIdx |string|文件更改后所在行数| +|------ type |string|文件变更类型,1: 内容未改动,2: 添加, 3: 删除, 4: diff统计信息| +|------ content |string|文件变更的内容| +|------ sectionInfo |object|| +|-------- path |string|文件相对仓库的路径| +|-------- lastLeftIdx |int|| +|-------- lastRightIdx |int|| +|-------- leftHunkSize |int|文件变更之前的行数| +|-------- rightHunkSize |int|文件变更之后的行数(及当前页面编辑器显示的总行数)| +|-------- leftIdx |int|文件变更之前所在行数| +|-------- rightIdx |int|文件变更之后所在行数| + +> 返回的JSON示例: + +```json +{ + "commits_count": 1, + "commits": [ + { + "author": { + "id": 36480, + "login": "jasder", + "name": "段甲生", + "image_url": "avatars/User/b" + }, + "committer": { + "id": 36480, + "login": "jasder", + "name": "段甲生", + "image_url": "avatars/User/b" + }, + "timestamp": 1604382982, + "time_from_now": "4小时前", + "message": "add some file\n* Add the tag list page to the release page\n* Apply suggestions from code review\n* Add the tags list view\n* Add the delete tag way on ui\n* Not delete tag and clear message when delete a release\n", + "sha": "8f5faee0d3b3be1b8063e84da0c79dd75327b968" + } + ], + "diff": { + "files_count": 6, + "total_addition": 447, + "total_deletion": 0, + "files": [ + { + "name": "build.go", + "old_name": "build.go", + "index": 1, + "addition": 33, + "deletion": 0, + "type": 1, + "isCreated": true, + "isDeleted": false, + "isBin": false, + "isLFSFile": false, + "isRenamed": false, + "isSubmodule": false, + "sections": [ + { + "fileName": "build.go", + "name": "", + "lines": [ + { + "leftIdx": 0, + "rightIdx": 0, + "type": 4, + "content": "@@ -0,0 +1,33 @@", + "sectionInfo": { + "path": "build.go", + "lastLeftIdx": 0, + "lastRightIdx": 0, + "leftIdx": 0, + "rightIdx": 1, + "leftHunkSize": 0, + "rightHunkSize": 33 + } + }, + { + "leftIdx": 0, + "rightIdx": 1, + "type": 2, + "content": "+// Copyright 2020 The Gitea Authors. All rights reserved.", + "sectionInfo": null + } + ] + } + ] + } + ] + } +``` + + +## List pull requests +获取合并请求列表 + +> 示例: + +```shell +curl -X GET http://localhost:3000/api/Jasder/gitlink/pulls.json +``` + +```javascript +await octokit.request('GET /api/Jasder/gitlink/pulls.json') +``` + +### HTTP 请求 +`GET /api/:owner/:repo/pulls.json` + +### 请求参数: +参数 | 必选 | 默认 | 类型 | 字段说明 +--------- | ------- | ------- | -------- | ---------- +|owner |是| |string |用户登录名 | +|repo |是| |string |项目标识identifier | + + + + +> 返回的JSON示例: + +```json +{ + "status": 0, + "message": "响应成功", + "open_count": 4, + "close_count": 51, + "merged_issues_size": 123, + "search_count": 4, + "limit": null, + "user_admin_or_member": true, + "user_admin_or_developer": true, + "project_name": "Gitlink", + "project_author_name": "Gitlink", + "issues": [ + { + "pull_request_id": 1189, + "pull_request_status": 0, + "pull_request_head": "develop", + "pull_request_base": "master", + "pull_request_staus": "open", + "is_original": false, + "fork_project_id": null, + "fork_project_identifier": null, + "fork_project_user": null, + "id": 51888, + "name": "FIx release v3.2.0", + "pr_time": "59分钟前", + "assign_user_name": "victor", + "assign_user_login": "moshenglv", + "author_name": "段甲生", + "author_login": "jasder", + "avatar_url": "images/avatars/User/36480?t=1615520120", + "priority": "正常", + "version": null, + "journals_count": 0, + "issue_tags": null + } + ] +} +``` \ No newline at end of file diff --git a/public/docs/api.html b/public/docs/api.html index ef03d978..8368e8fa 100644 --- a/public/docs/api.html +++ b/public/docs/api.html @@ -533,6 +533,23 @@
  • Pulls +
  • Issues @@ -8909,7 +8926,949 @@ http://localhost:3000/api/yystopf/ceshi/webhooks/3/test.json -

    Pulls

    Issues

    Organizations

    Teams

    Errors

    +

    Pulls

    Get a pull request

    +

    获取合并请求详情接口

    + +
    +

    示例:

    +
    +
    curl -X GET http://localhost:3000/api/Jasder/gitlink/pulls/88.json
    +
    await octokit.request('GET /api/Jasder/gitlink/pulls/88.json')
    +

    HTTP 请求

    +

    GET /api/:owner/:repo/pulls/:id.json

    +

    请求参数:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数必选默认类型字段说明
    ownerstring用户登录名
    repostring项目标识identifier
    idintegerpull id值
    + +
    +

    返回的JSON示例:

    +
    +
    {
    +    "status": 0,
    +    "message": "响应成功",
    +    "project_name": "Gitlink",
    +    "identifier": "forgeplus",
    +    "project_identifier": "forgeplus",
    +    "pr_time": "52分钟前",
    +    "commits_count": 229,
    +    "files_count": 328,
    +    "comments_count": 0,
    +    "comments_total_count": 0,
    +    "pull_request": {
    +        "id": 1189,
    +        "base": "master",
    +        "head": "develop",
    +        "status": 0,
    +        "fork_project_id": null,
    +        "is_original": false,
    +        "pull_request_staus": "open",
    +        "fork_project_user": null,
    +        "create_user": "jasder",
    +        "mergeable": true,
    +        "state": "open"
    +    },
    +    "issue": {
    +        "id": 51888,
    +        "subject": "FIx release v3.2.0",
    +        "description": null,
    +        "is_private": false,
    +        "branch_name": null,
    +        "project_author_name": "Gitlink",
    +        "closed_on": "",
    +        "created_at": "2021-10-12 15:51",
    +        "assign_user_name": "victor",
    +        "assign_user_login": "moshenglv",
    +        "author_name": "段甲生",
    +        "author_login": "jasder",
    +        "author_picture": "images/avatars/User/36480?t=1615520120",
    +        "issue_status": "新增",
    +        "priority": "正常",
    +        "version": null,
    +        "issue_tags": null
    +    },
    +    "conflict_files": []
    +}
    +

    获取pull request文件列表

    +

    获取pull request文件列表

    + +
    +

    示例:

    +
    +
    curl -X GET \
    +http://localhost:3000/api/Jason/gitlink/pulls/1/files.json 
    +
    await octokit.request('GET /api/jasder/gitlink/pulls/1/files.json')
    +

    HTTP 请求

    +

    GET /api/:owner/:repo/pulls/:id/files.json

    +

    请求参数:

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数名必选类型说明
    ownerstring用户登录名
    repostringproject's identifier
    idintpull request's id
    +

    返回字段说明:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数类型字段说明
    ---
    files_countint文件更改的总数量
    total_additionint添加代码总行数
    total_deletionint删除代码总行数
    filesarray
    -- shastringcommit's sha value
    -- namestring当前文件名
    -- old_namestring修改之前的文件名称,与name相同的话,说明文件名未更改
    -- additionint文件添加的行数
    -- deletionint文件删除的行数
    -- typeint文件类型, 1: 表示该文件只添加了内容,2: 表示该文件内容有修改, 3: 表示文件被删除或者改文件只删除了内容
    -- isCreatedboolean当前文件是否为新增文件, true: 是, false: 否
    -- isDeletedboolean当前文件是否被删除, true: 是,false: 否
    -- isBinboolean当前文件是否为二进制文件,true: 是,false: 否
    -- isLFSFileboolean当前文件是否为LFS文件,true: 是,false: 否
    -- isRenamedboolean当前文件是否被重命名,true: 是,false: 否
    -- sectionsarray
    ---- fileNamestring文件名称
    ---- linesarray
    ------ leftIdxstring文件变动之前所在行数
    ------ rightIdxstring文件更改后所在行数
    ------ typestring文件变更类型,1: 新增,2: 修改, 3: 删除, 4: diff统计信息
    ------ contentstring文件变更的内容
    ------ sectionInfoobject
    -------- pathstring文件相对仓库的路径
    -------- lastLeftIdxint
    -------- lastRightIdxint
    -------- leftHunkSizeint文件变更之前的行数
    -------- rightHunkSizeint文件变更之后的行数(及当前页面编辑器显示的总行数)
    -------- leftIdxint文件变更之前所在行数
    -------- rightIdxint文件变更之后所在行数(即:页面编辑器开始显示的行数)
    + +
    +

    返回的JSON示例:

    +
    +
    {
    +  "files_count": 6,
    +  "total_addition": 447,
    +  "total_deletion": 0,
    +  "files": [
    +    {
    +      "sha": "xefenisnii",
    +      "name": "文件.txt",
    +      "old_name": "文件.txt",
    +      "index": 6,
    +      "addition": 2,
    +      "deletion": 0,
    +      "type": 1,
    +      "isCreated": true,
    +      "isDeleted": false,
    +      "isBin": false,
    +      "isLFSFile": false,
    +      "isRenamed": false,
    +      "isSubmodule": false,
    +      "sections": [
    +        {
    +          "fileName": "文件.txt",
    +          "name": "",
    +          "lines": [
    +            {
    +              "leftIdx": 0,
    +              "rightIdx": 0,
    +              "type": 4,
    +              "content": "@@ -0,0 +1,2 @@",
    +              "sectionInfo": {
    +                "path": null,
    +                "lastLeftIdx": null,
    +                "lastRightIdx": null,
    +                "leftIdx": 0,
    +                "rightIdx": 0,
    +                "leftHunkSize": null,
    +                "rightHunkSize": null
    +              }
    +            },
    +            {
    +              "leftIdx": 0,
    +              "rightIdx": 1,
    +              "type": 2,
    +              "content": "+用例图一致性更新",
    +              "sectionInfo": null
    +            },
    +            {
    +              "leftIdx": 0,
    +              "rightIdx": 2,
    +              "type": 2,
    +              "content": "+工程文件直接上传会有文件缺失,现在压缩后上传",
    +              "sectionInfo": null
    +            }
    +          ]
    +        }
    +      ]
    +    }
    +  ]
    +}
    +

    获取pull request的commits列表

    +

    获取pull request的commits列表

    + +
    +

    示例:

    +
    +
    curl -X GET http://localhost:3000/api/jasder/jasder_test/pulls/1/commits.json
    +
    await octokit.request('GET /api/jasder/jasder_test/pulls/1/commits.json')
    +

    HTTP 请求

    +

    GET /api/:owner/:repo/pulls/:id/commits.json

    +

    请求参数:

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数名必选类型说明
    ownerstring用户登录名
    repostringproject's identifier
    idintpull request's id
    +

    返回字段说明:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数类型字段说明
    commits_countintcommits总数量
    commitsarray
    -- authorobject项目作者
    ---- loginstring用户login
    ---- namestring用户姓名
    ---- image_urlstring用户头像
    -- committerobjectcommit提交用户
    ---- loginstring用户login
    ---- namestring用户姓名
    ---- image_urlstring用户头像
    -- timestampintcommit的unix时间戳
    -- time_from_nowstringcommit’s 提交时间距当前时间的时间值
    -- messagestringcommit说明信息
    -- shastringcommit’s sha值
    + +
    +

    返回的JSON示例:

    +
    +
    {
    +  "commits_count": 1,
    +  "commits": [
    +    {
    +      "author": {
    +        "id": 36480,
    +        "login": "jasder",
    +        "name": "段甲生",
    +        "image_url": "avatars/User/b"
    +      },
    +      "committer": {
    +        "id": 36480,
    +        "login": "jasder",
    +        "name": "段甲生",
    +        "image_url": "avatars/User/b"
    +      },
    +      "timestamp": 1604382982,
    +      "time_from_now": "3小时前",
    +      "message": "add some file\n* Add the tag list page to the release page\n* Apply suggestions from code review\n* Add the tags list view\n* Add the delete tag way on ui\n* Not delete tag and clear message when delete a release\n",
    +      "sha": "8f5faee0d3b3be1b8063e84da0c79dd75327b968"
    +    }
    +  ]
    +}
    +

    Compare two commits

    +

    Compare two commits

    + +
    +

    示例:

    +
    +
    curl -X GET \
    +http://localhost:3000/api/Jason/test-txt/compare/master...develop
    +
    +curl -X GET \
    +http://localhost:3000/api/Jason/test-txt/compare/master...Jason/test-txt:develop
    +
    await octokit.request('GET /api/Jason/test-txt/compare/master...Jason/test-txt:develop')
    +

    HTTP 请求

    +

    GET /api/:owner/:repo/compare/{base}...{head}.json

    +

    请求参数:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数名必选类型说明
    ownerstring用户登录名
    repostringproject's identifier
    basestringpull request's id
    headstringpull request's id
    +

    返回字段说明:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数类型字段说明
    ---
    commits_countintcommits总数量
    commitsarray
    -- authorobject项目作者
    ---- loginstring用户login
    ---- namestring用户姓名
    ---- image_urlstring用户头像
    -- committerobjectcommit提交用户
    ---- loginstring用户login
    ---- namestring用户姓名
    ---- image_urlstring用户头像
    -- timestampintcommit的unix时间戳
    -- time_from_nowstringcommit’s 提交时间距当前时间的时间值
    -- messagestringcommit说明信息
    -- shastringcommit’s sha值
    diffobject
    -- files_countint文件更改的总数量
    -- total_additionint添加代码总行数
    -- total_deletionint删除代码总行数
    -- filesArray
    -- shastringcommit's sha
    -- namestring当前文件名
    -- old_namestring修改之前的文件名称,与name相同的话,说明文件名未更改
    -- additionint文件添加的行数
    -- deletionint文件删除的行数
    -- typeint文件类型, 1: 表示该文件只添加了内容,2: 表示该文件内容有修改, 3: 表示文件被删除或者改文件只删除了内容
    -- isCreatedboolean当前文件是否为新增文件, true: 是, false: 否
    -- isDeletedboolean当前文件是否被删除, true: 是,false: 否
    -- isBinboolean当前文件是否为二进制文件,true: 是,false: 否
    -- isLFSFileboolean当前文件是否为LFS文件,true: 是,false: 否
    -- isRenamedboolean当前文件是否被重命名,true: 是,false: 否
    -- sectionsarray
    ---- fileNamestring文件名称
    ---- linesarray
    ------ leftIdxstring文件变动之前所在行数
    ------ rightIdxstring文件更改后所在行数
    ------ typestring文件变更类型,1: 内容未改动,2: 添加, 3: 删除, 4: diff统计信息
    ------ contentstring文件变更的内容
    ------ sectionInfoobject
    -------- pathstring文件相对仓库的路径
    -------- lastLeftIdxint
    -------- lastRightIdxint
    -------- leftHunkSizeint文件变更之前的行数
    -------- rightHunkSizeint文件变更之后的行数(及当前页面编辑器显示的总行数)
    -------- leftIdxint文件变更之前所在行数
    -------- rightIdxint文件变更之后所在行数
    + +
    +

    返回的JSON示例:

    +
    +
    {
    +  "commits_count": 1,
    +  "commits": [
    +    {
    +      "author": {
    +        "id": 36480,
    +        "login": "jasder",
    +        "name": "段甲生",
    +        "image_url": "avatars/User/b"
    +      },
    +      "committer": {
    +        "id": 36480,
    +        "login": "jasder",
    +        "name": "段甲生",
    +        "image_url": "avatars/User/b"
    +      },
    +      "timestamp": 1604382982,
    +      "time_from_now": "4小时前",
    +      "message": "add some file\n* Add the tag list page to the release page\n* Apply suggestions from code review\n* Add the tags list view\n* Add the delete tag way on ui\n* Not delete tag and clear message when delete a release\n",
    +      "sha": "8f5faee0d3b3be1b8063e84da0c79dd75327b968"
    +    }
    +  ],
    +  "diff": {
    +    "files_count": 6,
    +    "total_addition": 447,
    +    "total_deletion": 0,
    +    "files": [
    +      {
    +        "name": "build.go",
    +        "old_name": "build.go",
    +        "index": 1,
    +        "addition": 33,
    +        "deletion": 0,
    +        "type": 1,
    +        "isCreated": true,
    +        "isDeleted": false,
    +        "isBin": false,
    +        "isLFSFile": false,
    +        "isRenamed": false,
    +        "isSubmodule": false,
    +        "sections": [
    +          {
    +            "fileName": "build.go",
    +            "name": "",
    +            "lines": [
    +              {
    +                "leftIdx": 0,
    +                "rightIdx": 0,
    +                "type": 4,
    +                "content": "@@ -0,0 +1,33 @@",
    +                "sectionInfo": {
    +                  "path": "build.go",
    +                  "lastLeftIdx": 0,
    +                  "lastRightIdx": 0,
    +                  "leftIdx": 0,
    +                  "rightIdx": 1,
    +                  "leftHunkSize": 0,
    +                  "rightHunkSize": 33
    +                }
    +              },
    +              {
    +                "leftIdx": 0,
    +                "rightIdx": 1,
    +                "type": 2,
    +                "content": "+// Copyright 2020 The Gitea Authors. All rights reserved.",
    +                "sectionInfo": null
    +              }
    +            ]
    +          }
    +        ]
    +      }
    +    ]
    +  }
    +

    List pull requests

    +

    获取合并请求列表

    + +
    +

    示例:

    +
    +
    curl -X GET http://localhost:3000/api/Jasder/gitlink/pulls.json
    +
    await octokit.request('GET /api/Jasder/gitlink/pulls.json')
    +

    HTTP 请求

    +

    GET /api/:owner/:repo/pulls.json

    +

    请求参数:

    + + + + + + + + + + + + + + + + + + + + + + + +
    参数必选默认类型字段说明
    ownerstring用户登录名
    repostring项目标识identifier
    + +
    +

    返回的JSON示例:

    +
    +
    {
    +  "status": 0,
    +  "message": "响应成功",
    +  "open_count": 4,
    +  "close_count": 51,
    +  "merged_issues_size": 123,
    +  "search_count": 4,
    +  "limit": null,
    +  "user_admin_or_member": true,
    +  "user_admin_or_developer": true,
    +  "project_name": "Gitlink",
    +  "project_author_name": "Gitlink",
    +  "issues": [
    +    {
    +      "pull_request_id": 1189,
    +      "pull_request_status": 0,
    +      "pull_request_head": "develop",
    +      "pull_request_base": "master",
    +      "pull_request_staus": "open",
    +      "is_original": false,
    +      "fork_project_id": null,
    +      "fork_project_identifier": null,
    +      "fork_project_user": null,
    +      "id": 51888,
    +      "name": "FIx release v3.2.0",
    +      "pr_time": "59分钟前",
    +      "assign_user_name": "victor",
    +      "assign_user_login": "moshenglv",
    +      "author_name": "段甲生",
    +      "author_login": "jasder",
    +      "avatar_url": "images/avatars/User/36480?t=1615520120",
    +      "priority": "正常",
    +      "version": null,
    +      "journals_count": 0,
    +      "issue_tags": null
    +    }
    +  ]
    +}
    +

    Issues

    Organizations

    Teams

    Errors

    From 2587ccea2810ea6d7cbe8aa85ae277f5d8d1a940 Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 13 Oct 2021 11:23:43 +0800 Subject: [PATCH 099/135] add: pr compare exist pr --- app/controllers/compare_controller.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/controllers/compare_controller.rb b/app/controllers/compare_controller.rb index 6dc9baad..8e8e3ec9 100644 --- a/app/controllers/compare_controller.rb +++ b/app/controllers/compare_controller.rb @@ -24,7 +24,7 @@ class CompareController < ApplicationController @exist_pullrequest = @project.pull_requests.where(is_original: false, head: @base, base: @head, status: 0).take end if @exist_pullrequest.present? - return -2, "在这些分支之间的合并请求已存在:#{@exist_pullrequest.try(:title)}" + return -2, "在这些分支之间的合并请求已存在:#{@exist_pullrequest.try(:title)}" else if @compare_result["Commits"].blank? && @compare_result["Diff"].blank? return -2, "分支内容相同,无需创建合并请求" From 8ba1198b4ac8543d5c8b0b784165f8b8b533219c Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 14 Oct 2021 16:38:12 +0800 Subject: [PATCH 100/135] fix: pr files commits count --- app/views/pull_requests/show.json.jbuilder | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/views/pull_requests/show.json.jbuilder b/app/views/pull_requests/show.json.jbuilder index 5c30bd17..ee656396 100644 --- a/app/views/pull_requests/show.json.jbuilder +++ b/app/views/pull_requests/show.json.jbuilder @@ -3,8 +3,8 @@ json.project_name @project.name json.identifier @project.identifier json.project_identifier @project.identifier json.pr_time time_from_now(@pull_request.updated_at) -json.commits_count @pull_request.commits_count -json.files_count @pull_request.files_count +json.commits_count @gitea_pull["commit_num"] +json.files_count @gitea_pull["changed_files"] json.comments_count @issue.journals.parent_journals.size json.comments_total_count @issue.get_journals_size From 3d8b19fa7379638ab5dff9fcb3929c3a1e11cbbc Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 14 Oct 2021 16:59:43 +0800 Subject: [PATCH 101/135] fix: edit pr fork project info --- app/controllers/pull_requests_controller.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/controllers/pull_requests_controller.rb b/app/controllers/pull_requests_controller.rb index fe04dd5e..1a31704b 100644 --- a/app/controllers/pull_requests_controller.rb +++ b/app/controllers/pull_requests_controller.rb @@ -69,9 +69,9 @@ class PullRequestsController < ApplicationController end def edit - @fork_project_user_name = @project&.fork_project&.owner.try(:show_real_name) - @fork_project_user = @project&.fork_project&.owner.try(:login) - @fork_project_identifier = @project&.fork_project&.repository.try(:identifier) + @fork_project_user_name = @pull_request&.fork_project&.owner.try(:show_real_name) + @fork_project_user = @pull_request&.fork_project&.owner.try(:login) + @fork_project_identifier = @pull_request&.fork_project&.repository.try(:identifier) end def update From 119883042281d10bef72309e8596e2e3602ab2ae Mon Sep 17 00:00:00 2001 From: yystopf Date: Tue, 12 Oct 2021 16:41:01 +0800 Subject: [PATCH 102/135] add: project permit change identifier --- app/controllers/projects_controller.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index bea2b429..e4ad2f13 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -229,7 +229,7 @@ class ProjectsController < ApplicationController private def project_params - params.permit(:user_id, :name, :description, :repository_name, :website, :lesson_url, :default_branch, + params.permit(:user_id, :name, :description, :repository_name, :website, :lesson_url, :default_branch, :identifier, :project_category_id, :project_language_id, :license_id, :ignore_id, :private) end From 018745c062e1067ed1b9dd5938bc632f28fa838e Mon Sep 17 00:00:00 2001 From: yystopf Date: Tue, 12 Oct 2021 17:08:25 +0800 Subject: [PATCH 103/135] add: project permit change identifier --- app/controllers/projects_controller.rb | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index e4ad2f13..95d9bc1a 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -139,11 +139,12 @@ class ProjectsController < ApplicationController gitea_params = { private: private, default_branch: @project.default_branch, - website: @project.website + website: @project.website, + name: @project.identifier } if [true, false].include? private - Gitea::Repository::UpdateService.call(@owner, @project.identifier, gitea_params) - @project.repository.update_column(:hidden, private) + Gitea::Repository::UpdateService.call(@owner, @project&.repository&.identifier, gitea_params) + @project.repository.update_attributes({hidden: private, identifier: @project.identifier}) end end SendTemplateMessageJob.perform_later('ProjectSettingChanged', current_user.id, @project&.id, @project.previous_changes.slice(:name, :description, :project_category_id, :project_language_id, :is_public)) From 00100e59c451471b17cff059b2a4147f028e329e Mon Sep 17 00:00:00 2001 From: yystopf Date: Tue, 12 Oct 2021 17:15:50 +0800 Subject: [PATCH 104/135] add: project permit change identifier --- app/controllers/projects_controller.rb | 6 ++---- app/services/gitea/repository/update_service.rb | 3 ++- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index 95d9bc1a..25d8b8d7 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -142,10 +142,8 @@ class ProjectsController < ApplicationController website: @project.website, name: @project.identifier } - if [true, false].include? private - Gitea::Repository::UpdateService.call(@owner, @project&.repository&.identifier, gitea_params) - @project.repository.update_attributes({hidden: private, identifier: @project.identifier}) - end + gitea_repo = Gitea::Repository::UpdateService.call(@owner, @project&.repository&.identifier, gitea_params) + @project.repository.update_attributes({hidden: gitea_repo["private"], identifier: gitea_repo["name"]}) end SendTemplateMessageJob.perform_later('ProjectSettingChanged', current_user.id, @project&.id, @project.previous_changes.slice(:name, :description, :project_category_id, :project_language_id, :is_public)) end diff --git a/app/services/gitea/repository/update_service.rb b/app/services/gitea/repository/update_service.rb index 0d27922b..6c4eff1b 100644 --- a/app/services/gitea/repository/update_service.rb +++ b/app/services/gitea/repository/update_service.rb @@ -19,7 +19,8 @@ class Gitea::Repository::UpdateService < Gitea::ClientService end def call - patch(url, data_params) + response = patch(url, data_params) + render_200_response(response) end private From 98a45eb05cc30b6cb0e02817606324ef9fc732f8 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 14 Oct 2021 14:25:00 +0800 Subject: [PATCH 105/135] fix: update repository identifier valid --- app/controllers/projects_controller.rb | 4 ++-- app/forms/projects/update_form.rb | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index 25d8b8d7..54ae85ca 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -127,9 +127,9 @@ class ProjectsController < ApplicationController Gitea::Repository::UpdateService.call(@owner, @project.identifier, gitea_params) else validate_params = project_params.slice(:name, :description, - :project_category_id, :project_language_id, :private) + :project_category_id, :project_language_id, :private, :identifier) - Projects::UpdateForm.new(validate_params).validate! + Projects::UpdateForm.new(validate_params.merge(user_id: @project.user_id)).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 0cd2c945..9ccc611c 100644 --- a/app/forms/projects/update_form.rb +++ b/app/forms/projects/update_form.rb @@ -1,11 +1,12 @@ class Projects::UpdateForm < BaseForm - attr_accessor :name, :description, :project_category_id, :project_language_id, :private + attr_accessor :name, :description, :project_category_id, :project_language_id, :private, :identifier, :user_id validates :name, presence: true validates :name, length: { maximum: 50 } validates :description, length: { maximum: 200 } validate do check_project_category(project_category_id) check_project_language(project_language_id) + check_repository_name(user_id, identifier) unless identifier.blank? end end From 79b394d29162cb777ebaa7427961d3883bd38d0b Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 14 Oct 2021 15:30:00 +0800 Subject: [PATCH 106/135] fix: projecttrend show rule --- app/controllers/project_trends_controller.rb | 9 ++++----- app/models/pull_request.rb | 2 +- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/app/controllers/project_trends_controller.rb b/app/controllers/project_trends_controller.rb index dc1ffbdb..621a30d5 100644 --- a/app/controllers/project_trends_controller.rb +++ b/app/controllers/project_trends_controller.rb @@ -14,14 +14,13 @@ class ProjectTrendsController < ApplicationController project_trends = project_trends.where("created_at between ? and ?",(Time.now.beginning_of_day - check_time.days), Time.now.end_of_day) end - @project_open_issues_count = project_trends.where(trend_type: "Issue", action_type: "create").size @project_close_issues_count = project_trends.where(trend_type: "Issue", action_type: "close").size - @project_issues_count = @project_open_issues_count + @project_close_issues_count + @project_issues_count = project_trends.where(trend_type: "Issue", action_type: "create").size + @project_open_issues_count = @project_issues_count - @project_close_issues_count @project_pr_count = project_trends.where(trend_type: "PullRequest", action_type: "close").size - @project_new_pr_count = project_trends.where(trend_type: "PullRequest", action_type: "create").size - @project_pr_all_count = @project_pr_count + @project_new_pr_count - + @project_pr_all_count = project_trends.where(trend_type: "PullRequest", action_type: "create").size + @project_new_pr_count = @project_pr_all_count - @project_pr_count if check_type.present? project_trends = project_trends.where(trend_type: check_type.to_s.strip) end diff --git a/app/models/pull_request.rb b/app/models/pull_request.rb index ce0cb04a..14b89355 100644 --- a/app/models/pull_request.rb +++ b/app/models/pull_request.rb @@ -54,7 +54,7 @@ class PullRequest < ApplicationRecord Project.find_by(id: self.fork_project_id) end - def bind_gitea_pull_request!(gitea_pull_number, gitea_pull_id) + def bind_gitea_pull_request!(gitea_pull_number, gitea_pull_id=gitea_pull_number) update_columns( gitea_number: gitea_pull_number, gitea_id: gitea_pull_id) From ffa0715374475ee24659cd969e2262f9c648fdd7 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 14 Oct 2021 18:31:27 +0800 Subject: [PATCH 107/135] fix --- app/controllers/pull_requests_controller.rb | 2 +- app/models/pull_request.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/controllers/pull_requests_controller.rb b/app/controllers/pull_requests_controller.rb index 1a31704b..8f3df554 100644 --- a/app/controllers/pull_requests_controller.rb +++ b/app/controllers/pull_requests_controller.rb @@ -58,7 +58,7 @@ class PullRequestsController < ApplicationController ActiveRecord::Base.transaction do @pull_request, @gitea_pull_request = PullRequests::CreateService.call(current_user, @owner, @project, params) if @gitea_pull_request[:status] == :success - @pull_request.bind_gitea_pull_request!(@gitea_pull_request[:body]["number"]) + @pull_request.bind_gitea_pull_request!(@gitea_pull_request[:body]["number"], @gitea_pull_request[:body]["id"]) SendTemplateMessageJob.perform_later('PullRequestAssigned', current_user.id, @pull_request&.id) SendTemplateMessageJob.perform_later('ProjectPullRequest', current_user.id, @pull_request&.id) else diff --git a/app/models/pull_request.rb b/app/models/pull_request.rb index 14b89355..ce0cb04a 100644 --- a/app/models/pull_request.rb +++ b/app/models/pull_request.rb @@ -54,7 +54,7 @@ class PullRequest < ApplicationRecord Project.find_by(id: self.fork_project_id) end - def bind_gitea_pull_request!(gitea_pull_number, gitea_pull_id=gitea_pull_number) + def bind_gitea_pull_request!(gitea_pull_number, gitea_pull_id) update_columns( gitea_number: gitea_pull_number, gitea_id: gitea_pull_id) From 2a09fadf712e05d473154bd36f99d7743d17e82b Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 15 Oct 2021 14:36:50 +0800 Subject: [PATCH 108/135] fix: change projec trend rule and fix data --- app/controllers/issues_controller.rb | 12 ++++++++ app/controllers/project_trends_controller.rb | 12 ++++++-- app/controllers/pull_requests_controller.rb | 4 ++- app/models/project_trend.rb | 3 +- lib/tasks/refactor_project_trend.rake | 30 ++++++++++++++++++++ 5 files changed, 56 insertions(+), 5 deletions(-) create mode 100644 lib/tasks/refactor_project_trend.rake diff --git a/app/controllers/issues_controller.rb b/app/controllers/issues_controller.rb index bfa15aa5..f16edbb3 100644 --- a/app/controllers/issues_controller.rb +++ b/app/controllers/issues_controller.rb @@ -216,6 +216,12 @@ class IssuesController < ApplicationController if @issue.previous_changes[:due_date].present? previous_changes.merge!(due_date: [@issue.previous_changes[:due_date][0].to_s, @issue.previous_changes[:due_date][1].to_s]) end + if @issue.previous_changes[:status_id].present? && @issue.previous_changes[:status_id][1] == 5 + @issue.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: ProjectTrend::CLOSE) + end + if @issue.previous_changes[:status_id].present? && @issue.previous_changes[:status_id][0] == 5 + @issue.project_trends.where(action_type: ProjectTrend::CLOSE).destroy_all + end SendTemplateMessageJob.perform_later('IssueChanged', current_user.id, @issue&.id, previous_changes) SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @issue&.id) if @issue.previous_changes[:assigned_to_id].present? end @@ -338,6 +344,12 @@ class IssuesController < ApplicationController if i.previous_changes[:due_date].present? previous_changes.merge!(due_date: [i.previous_changes[:due_date][0].to_s, i.previous_changes[:due_date][1].to_s]) end + if i.previous_changes[:status_id].present? && i.previous_changes[:status_id][1] == 5 + i.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: ProjectTrend::CLOSE) + end + if i.previous_changes[:status_id].present? && i.previous_changes[:status_id][0] == 5 + i.project_trends.where(action_type: ProjectTrend::CLOSE).destroy_all + end SendTemplateMessageJob.perform_later('IssueChanged', current_user.id, i&.id, previous_changes) SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, i&.id) if i.previous_changes[:assigned_to_id].present? end diff --git a/app/controllers/project_trends_controller.rb b/app/controllers/project_trends_controller.rb index 621a30d5..66702608 100644 --- a/app/controllers/project_trends_controller.rb +++ b/app/controllers/project_trends_controller.rb @@ -3,7 +3,7 @@ class ProjectTrendsController < ApplicationController before_action :check_project_public def index - project_trends = @project.project_trends.includes(:user, trend: :user) + project_trends = @project.project_trends.preload(:user, trend: :user) check_time = params[:time] #时间的筛选 check_type = params[:type] #动态类型的筛选,目前已知的有 Issue, PullRequest, Version @@ -18,7 +18,7 @@ class ProjectTrendsController < ApplicationController @project_issues_count = project_trends.where(trend_type: "Issue", action_type: "create").size @project_open_issues_count = @project_issues_count - @project_close_issues_count - @project_pr_count = project_trends.where(trend_type: "PullRequest", action_type: "close").size + @project_pr_count = project_trends.where(trend_type: "PullRequest", action_type: ["close", "merge"]).size @project_pr_all_count = project_trends.where(trend_type: "PullRequest", action_type: "create").size @project_new_pr_count = @project_pr_all_count - @project_pr_count if check_type.present? @@ -26,7 +26,13 @@ class ProjectTrendsController < ApplicationController end if check_status.present? - project_trends = project_trends.where(action_type: check_status.to_s.strip) + if check_status == "delay" || check_status == "close" + project_trends = project_trends.where(action_type: ["close", "merge"]) + else + project_trends = project_trends.where(action_type: ["create"]).where.not(trend_id: project_trends.where(action_type: ["close", "merge"]).pluck(:trend_id)) + end + else + project_trends = project_trends.where(action_type: "create") end project_trends = project_trends.order("created_at desc") diff --git a/app/controllers/pull_requests_controller.rb b/app/controllers/pull_requests_controller.rb index 8f3df554..ac3968aa 100644 --- a/app/controllers/pull_requests_controller.rb +++ b/app/controllers/pull_requests_controller.rb @@ -130,6 +130,7 @@ class PullRequestsController < ApplicationController begin colsed = PullRequests::CloseService.call(@owner, @repository, @pull_request, current_user) if colsed === true + @pull_request.project_trends.create!(user: current_user, project: @project,action_type: ProjectTrend::CLOSE) SendTemplateMessageJob.perform_later('PullRequestClosed', current_user.id, @pull_request.id) normal_status(1, "已拒绝") else @@ -171,7 +172,8 @@ class PullRequestsController < ApplicationController end if success_condition && @pull_request.merge! - @pull_request.project_trend_status! + # @pull_request.project_trend_status! + @pull_request.project_trends.create!(user: current_user, project: @project,action_type: ProjectTrend::MERGE) @issue&.custom_journal_detail("merge", "", "该合并请求已被合并", current_user&.id) SendTemplateMessageJob.perform_later('PullRequestMerged', current_user.id, @pull_request.id) normal_status(1, "合并成功") diff --git a/app/models/project_trend.rb b/app/models/project_trend.rb index 8c55c4f9..7642e1df 100644 --- a/app/models/project_trend.rb +++ b/app/models/project_trend.rb @@ -20,7 +20,8 @@ class ProjectTrend < ApplicationRecord CLOSE = 'close' CREATE = 'create' - + MERGE = 'merge' + belongs_to :project belongs_to :trend, polymorphic: true, optional: true belongs_to :user diff --git a/lib/tasks/refactor_project_trend.rake b/lib/tasks/refactor_project_trend.rake new file mode 100644 index 00000000..e2092d02 --- /dev/null +++ b/lib/tasks/refactor_project_trend.rake @@ -0,0 +1,30 @@ +namespace :refactor_project_trend do + desc "refactor project trend data record" + + task issue_and_pull_request: :environment do + puts "========DELETE all old data begin========" + old_data_count = ProjectTrend.where(trend_type: ["PullRequest","Issue"]).destroy_all.size + puts "========DELETE all old data #{old_data_count}========" + puts "========DELETE all old data end========" + puts "========CREATE new issue data begin========" + issue_count = 0 + Issue.issue_issue.find_each do |issue| + issue_count += 1 + issue.project_trends.create(user_id: issue.assigned_to_id || issue.author_id, project_id: issue.project_id, action_type: ProjectTrend::CLOSE, created_at: issue.updated_on) if issue.status_id == 5 + issue.project_trends.create(user_id: issue.author_id, project_id: issue.project_id, action_type: ProjectTrend::CREATE, created_at: issue.created_on) + end + puts "========CREATE new issue data #{issue_count}========" + puts "========CREATE new issue data end========" + puts "========CREATE new pull_request data begin========" + pull_request_count = 0 + PullRequest.find_each do |pull_request| + pull_request_count += 1 + pull_request.project_trends.create(user_id: pull_request.user_id, project_id: pull_request.project_id, action_type: ProjectTrend::MERGE, created_at: pull_request.updated_at) if pull_request.status == PullRequest::MERGED + pull_request.project_trends.create(user_id: pull_request.user_id, project_id: pull_request.project_id, action_type: ProjectTrend::CLOSE, created_at: pull_request.updated_at) if pull_request.status == PullRequest::CLOSED + pull_request.project_trends.create(user_id: pull_request.user_id, project_id: pull_request.project_id, action_type: ProjectTrend::CREATE, created_at: pull_request.created_at) + end + puts "========CREATE new pull_request data #{pull_request_count}========" + puts "========CREATE new pull_request data end========" + + end +end \ No newline at end of file From a4ee5292166e45c40d5f826f74989dfa49c3afc0 Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 15 Oct 2021 16:47:01 +0800 Subject: [PATCH 109/135] fix: allow update repository identifier origin --- app/controllers/projects_controller.rb | 2 +- app/forms/projects/update_form.rb | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index 54ae85ca..0dbb666b 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -129,7 +129,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)).validate! + Projects::UpdateForm.new(validate_params.merge(user_id: @project.user_id, project_identifier: @project.identifier)).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 9ccc611c..ae93abf3 100644 --- a/app/forms/projects/update_form.rb +++ b/app/forms/projects/update_form.rb @@ -1,12 +1,14 @@ class Projects::UpdateForm < BaseForm - attr_accessor :name, :description, :project_category_id, :project_language_id, :private, :identifier, :user_id + attr_accessor :name, :description, :project_category_id, :project_language_id, :private, :identifier, :user_id, :project_identifier validates :name, presence: true validates :name, length: { maximum: 50 } validates :description, length: { maximum: 200 } validate do check_project_category(project_category_id) check_project_language(project_language_id) - check_repository_name(user_id, identifier) unless identifier.blank? + Rails.logger.info project_identifier + Rails.logger.info identifier + check_repository_name(user_id, identifier) unless identifier.blank? || identifier == project_identifier end end From 73f558d7c34f311b35a76d7e3c38e44988fd7c4b Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 18 Oct 2021 13:42:41 +0800 Subject: [PATCH 110/135] fix: issue subject validate --- app/forms/issues/create_form.rb | 2 +- app/forms/issues/update_form.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/forms/issues/create_form.rb b/app/forms/issues/create_form.rb index 7dde8ecd..602775ff 100644 --- a/app/forms/issues/create_form.rb +++ b/app/forms/issues/create_form.rb @@ -5,7 +5,7 @@ class Issues::CreateForm validates :subject, presence: { message: "不能为空" } - validates :subject, length: { maximum: 80, too_long: "不能超过80个字符" } + validates :subject, length: { maximum: 200, too_long: "不能超过200个字符" } end diff --git a/app/forms/issues/update_form.rb b/app/forms/issues/update_form.rb index 7447c8cc..64acdfb5 100644 --- a/app/forms/issues/update_form.rb +++ b/app/forms/issues/update_form.rb @@ -5,6 +5,6 @@ class Issues::UpdateForm validates :subject, presence: { message: "不能为空" } - validates :subject, length: { maximum: 80, too_long: "不能超过80个字符" } + validates :subject, length: { maximum: 200, too_long: "不能超过200个字符" } end \ No newline at end of file From d176508010884d034cff7c9f055894c46a9bc03d Mon Sep 17 00:00:00 2001 From: yystopf Date: Tue, 12 Oct 2021 16:14:45 +0800 Subject: [PATCH 111/135] add: system notification management --- .../admins/system_notifications/index.js | 76 +++++++++++++++++++ .../admins/system_notifications_controller.rb | 76 +++++++++++++++++++ app/models/system_notification.rb | 17 +++++ app/models/system_notification_history.rb | 21 +++++ app/models/user.rb | 4 +- app/views/admins/shared/_sidebar.html.erb | 4 +- .../system_notifications/_form.html.erb | 57 ++++++++++++++ .../system_notifications/_form_modal.html.erb | 40 ++++++++++ .../system_notifications/_list.html.erb | 35 +++++++++ .../admins/system_notifications/edit.js.erb | 2 + .../system_notifications/index.html.erb | 21 +++++ .../admins/system_notifications/index.js.erb | 1 + .../admins/system_notifications/new.js.erb | 2 + config/routes.rb | 5 ++ ...11012060724_create_system_notifications.rb | 13 ++++ ...37_create_system_notification_histories.rb | 10 +++ 16 files changed, 381 insertions(+), 3 deletions(-) create mode 100644 app/assets/javascripts/admins/system_notifications/index.js create mode 100644 app/controllers/admins/system_notifications_controller.rb create mode 100644 app/models/system_notification.rb create mode 100644 app/models/system_notification_history.rb create mode 100644 app/views/admins/system_notifications/_form.html.erb create mode 100644 app/views/admins/system_notifications/_form_modal.html.erb create mode 100644 app/views/admins/system_notifications/_list.html.erb create mode 100644 app/views/admins/system_notifications/edit.js.erb create mode 100644 app/views/admins/system_notifications/index.html.erb create mode 100644 app/views/admins/system_notifications/index.js.erb create mode 100644 app/views/admins/system_notifications/new.js.erb create mode 100644 db/migrate/20211012060724_create_system_notifications.rb create mode 100644 db/migrate/20211012060837_create_system_notification_histories.rb diff --git a/app/assets/javascripts/admins/system_notifications/index.js b/app/assets/javascripts/admins/system_notifications/index.js new file mode 100644 index 00000000..90809b34 --- /dev/null +++ b/app/assets/javascripts/admins/system_notifications/index.js @@ -0,0 +1,76 @@ +/* + * @Description: Do not edit + * @Date: 2021-08-31 11:16:45 + * @LastEditors: viletyy + * @Author: viletyy + * @LastEditTime: 2021-08-31 14:19:46 + * @FilePath: /forgeplus/app/assets/javascripts/admins/system_notifications/index.js + */ +$(document).on('turbolinks:load', function(){ + + var showSuccessNotify = function() { + $.notify({ + message: '操作成功' + },{ + type: 'success' + }); + } + + // close user + $('.system-notification-list-container').on('click', '.close-action', function(){ + var $closeAction = $(this); + var $uncloseAction = $closeAction.siblings('.unclose-action'); + + var keywordID = $closeAction.data('id'); + customConfirm({ + content: '确认取消置顶吗?', + ok: function(){ + $.ajax({ + url: '/admins/system_notifications/' + keywordID, + method: 'PUT', + dataType: 'json', + data: { + system_notification: { + is_top: false + } + }, + success: function() { + showSuccessNotify(); + $closeAction.hide(); + $uncloseAction.show(); + $(".system-notification-item-"+keywordID).children('td').eq(3).text("") + } + }); + } + }); + }); + + // unclose user + $('.system-notification-list-container').on('click', '.unclose-action', function(){ + var $uncloseAction = $(this); + var $closeAction = $uncloseAction.siblings('.close-action'); + + var keywordID = $uncloseAction.data('id'); + customConfirm({ + content: '确认置顶吗?', + ok: function () { + $.ajax({ + url: '/admins/system_notifications/' + keywordID, + method: 'PUT', + dataType: 'json', + data: { + system_notification: { + is_top: true + } + }, + success: function() { + showSuccessNotify(); + $closeAction.show(); + $uncloseAction.hide(); + $(".system-notification-item-"+keywordID).children('td').eq(3).text("√") + } + }); + } + }) + }); +}) \ No newline at end of file diff --git a/app/controllers/admins/system_notifications_controller.rb b/app/controllers/admins/system_notifications_controller.rb new file mode 100644 index 00000000..1a71173c --- /dev/null +++ b/app/controllers/admins/system_notifications_controller.rb @@ -0,0 +1,76 @@ +class Admins::SystemNotificationsController < Admins::BaseController + before_action :get_notification, only: [:history, :edit,:update, :destroy] + # before_action :validate_identifer, only: [:create, :update] + + def index + sort_by = SystemNotification.column_names.include?(params[:sort_by]) ? params[:sort_by] : 'created_at' + sort_direction = %w(desc asc).include?(params[:sort_direction]) ? params[:sort_direction] : 'desc' + q = SystemNotification.ransack(subject_cont: params[:search]) + notifications = q.result(distinct: true).order("#{sort_by} #{sort_direction},created_at desc") + @notifications = paginate(notifications) + end + + def history + @users = @notification.users + end + + def new + @notification = SystemNotification.new + end + + def edit + end + + def create + @notification = SystemNotification.new(notification_params) + if @notification.save + redirect_to admins_system_notifications_path + flash[:success] = '系统保留关键词创建成功' + else + redirect_to admins_system_notifications_path + flash[:danger] = @notification.errors.full_messages.join(",") + end + end + + def update + + respond_to do |format| + if @notification.update_attributes(notification_params) + format.html do + redirect_to admins_system_notifications_path + flash[:success] = '系统保留关键词更新成功' + end + format.js {render_ok} + else + format.html do + redirect_to admins_system_notifications_path + flash[:danger] = @notification.errors.full_messages.join(",") + end + format.js {render_js_error} + end + end + end + + def destroy + if @notification.destroy + redirect_to admins_system_notifications_path + flash[:success] = "系统保留关键词删除成功" + else + redirect_to admins_system_notifications_path + flash[:danger] = "系统保留关键词删除失败" + end + end + + private + def notification_params + params.require(:system_notification).permit! + end + + def get_notification + @notification = SystemNotification.find_by(id: params[:id]) + unless @notification.present? + redirect_to admins_system_notifications_path + flash[:danger] = "系统保留关键词不存在" + end + end +end \ No newline at end of file diff --git a/app/models/system_notification.rb b/app/models/system_notification.rb new file mode 100644 index 00000000..76c514cd --- /dev/null +++ b/app/models/system_notification.rb @@ -0,0 +1,17 @@ +# == Schema Information +# +# Table name: system_notifications +# +# id :integer not null, primary key +# subject :string(255) +# sub_subject :string(255) +# content :string(255) +# created_at :datetime not null +# updated_at :datetime not null +# + +class SystemNotification < ApplicationRecord + + has_many :system_notification_histories + has_many :users, through: :system_notification_histories +end diff --git a/app/models/system_notification_history.rb b/app/models/system_notification_history.rb new file mode 100644 index 00000000..8723ca91 --- /dev/null +++ b/app/models/system_notification_history.rb @@ -0,0 +1,21 @@ +# == Schema Information +# +# Table name: system_notification_histories +# +# id :integer not null, primary key +# system_message_id :integer +# user_id :integer +# created_at :datetime not null +# updated_at :datetime not null +# +# Indexes +# +# index_system_notification_histories_on_system_message_id (system_message_id) +# index_system_notification_histories_on_user_id (user_id) +# + +class SystemNotificationHistory < ApplicationRecord + + belongs_to :system_notification + belongs_to :user +end diff --git a/app/models/user.rb b/app/models/user.rb index 3c4a900a..22c5e3cd 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -170,7 +170,9 @@ class User < Owner has_many :issues, dependent: :destroy, foreign_key: :author_id has_many :pull_requests, dependent: :destroy has_many :public_keys, class_name: "Gitea::PublicKey",primary_key: :gitea_uid, foreign_key: :owner_id, dependent: :destroy - + has_many :system_notification_histories + has_many :system_notifications, through: :system_notification_histories + # Groups and active users scope :active, lambda { where(status: STATUS_ACTIVE) } scope :like, lambda { |keywords| diff --git a/app/views/admins/shared/_sidebar.html.erb b/app/views/admins/shared/_sidebar.html.erb index 402449b3..75abbc12 100644 --- a/app/views/admins/shared/_sidebar.html.erb +++ b/app/views/admins/shared/_sidebar.html.erb @@ -30,8 +30,6 @@
  • <%= sidebar_item(admins_reversed_keywords_path, '系统保留关键词', icon: 'key', controller: 'admins-reversed_keywords') %>
  • -
  • <%= sidebar_item(admins_message_templates_path, '消息模版', icon: 'folder', controller: 'admins-message_templates') %>
  • -
  • <%= sidebar_item(admins_laboratories_path, '云上实验室', icon: 'cloud', controller: 'admins-laboratories') %>
  • @@ -48,6 +46,8 @@ <%= sidebar_item_group('#setting-system', '系统配置', icon: 'wrench') do %>
  • <%= sidebar_item(admins_sites_path, 'setting接口配置', icon: 'deaf', controller: 'admins-sites') %>
  • <%= sidebar_item(admins_edu_settings_path, '全局变量配置', icon: 'pencil-square', controller: 'admins-edu_settings') %>
  • +
  • <%= sidebar_item(admins_system_notifications_path, '系统通知配置', icon: 'bell', controller: 'admins-system_notifications') %>
  • +
  • <%= sidebar_item(admins_message_templates_path, '消息模版配置', icon: 'folder', controller: 'admins-message_templates') %>
  • <% end %>
  • diff --git a/app/views/admins/system_notifications/_form.html.erb b/app/views/admins/system_notifications/_form.html.erb new file mode 100644 index 00000000..8e761910 --- /dev/null +++ b/app/views/admins/system_notifications/_form.html.erb @@ -0,0 +1,57 @@ +
    +
    <%= type == "create" ? "新建" : "编辑" %>忽略文件
    + <%= link_to "返回", admins_project_ignores_path, class: "btn btn-default pull-right" %> +
    + +
    + <%= form_for @notification, url: {controller: "system_notifications", action: "#{type}"} do |p| %> +
    + +
    + <%= p.text_field :subject, class: "form-control input-lg", placeholder: "请输入系统通知标题" %> +
    + +
    +
    + +
    + <%= p.text_field :sub_subject, class: "form-control input-lg", placeholder: "请输入系统通知副标题" %> +
    + +
    +
    + +
    + <%= p.text_area :content, class:"form-control", style: 'display: none;', rows: "10", cols: "20", placeholer: "请输入系统通知正文" %> +
    + +
    + +
    +
    + <%= p.check_box :is_top, class: "form-check-input", value:"true"%> + +
    +
    +
    + <%= p.submit "确认", class: "btn btn-primary submit-btn" %> +
    + <% end %> +
    \ No newline at end of file diff --git a/app/views/admins/system_notifications/_form_modal.html.erb b/app/views/admins/system_notifications/_form_modal.html.erb new file mode 100644 index 00000000..658bbc9c --- /dev/null +++ b/app/views/admins/system_notifications/_form_modal.html.erb @@ -0,0 +1,40 @@ + \ No newline at end of file diff --git a/app/views/admins/system_notifications/_list.html.erb b/app/views/admins/system_notifications/_list.html.erb new file mode 100644 index 00000000..0d86ab03 --- /dev/null +++ b/app/views/admins/system_notifications/_list.html.erb @@ -0,0 +1,35 @@ + + + + + + + + + + + + + <% if notifications.present? %> + <% notifications.each_with_index do |notification, index| %> + + + + + + + + + <% end %> + <% else %> + <%= render 'admins/shared/no_data_for_table' %> + <% end %> + +
    序号标题副标题<%= sort_tag('是否置顶', name: 'is_top', path: admins_system_notifications_path) %><%= sort_tag('创建时间', name: 'created_at', path: admins_system_notifications_path) %>操作
    <%= list_index_no((params[:page] || 1).to_i, index) %><%= notification.subject %><%= notification.sub_subject %><%= notification.is_top ? '√' : '' %><%= notification.created_at&.strftime('%Y-%m-%d %H:%M') %> + <%= javascript_void_link '置顶', class: 'action unclose-action', data: { id: notification.id }, style: notification.is_top ? 'display: none;' : '' %> + <%= javascript_void_link '取消置顶', class: 'action close-action', data: { id: notification.id }, style: notification.is_top ? '' : 'display: none;' %> + <%= link_to "编辑", edit_admins_system_notification_path(notification), remote: true, class: "action" %> + <%= link_to "删除", admins_system_notification_path(notification), method: :delete, data:{confirm: "确认删除的吗?"}, class: "action" %> +
    + +<%= render partial: 'admins/shared/paginate', locals: { objects: notifications } %> \ No newline at end of file diff --git a/app/views/admins/system_notifications/edit.js.erb b/app/views/admins/system_notifications/edit.js.erb new file mode 100644 index 00000000..63fad583 --- /dev/null +++ b/app/views/admins/system_notifications/edit.js.erb @@ -0,0 +1,2 @@ +$("#admins-system-notification-content").html("<%= j render(partial: 'admins/system_notifications/form', locals: {type: 'create'}) %>") +createMDEditor('system-notification-content-editor', { height: 500, placeholder: '请输入邮件模版' }); \ No newline at end of file diff --git a/app/views/admins/system_notifications/index.html.erb b/app/views/admins/system_notifications/index.html.erb new file mode 100644 index 00000000..01a35f21 --- /dev/null +++ b/app/views/admins/system_notifications/index.html.erb @@ -0,0 +1,21 @@ +<% define_admin_breadcrumbs do %> + <% add_admin_breadcrumb('系统通知模版') %> +<% end %> + +
    +
    + <%= form_tag(admins_system_notifications_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_system_notification_path, remote: true, class: "btn btn-primary pull-right", "data-disabled-with":"...新增" %> +
    + +
    +
    + +
    + <%= render partial: 'admins/system_notifications/list', locals: { notifications: @notifications } %> +
    +
    \ No newline at end of file diff --git a/app/views/admins/system_notifications/index.js.erb b/app/views/admins/system_notifications/index.js.erb new file mode 100644 index 00000000..a5cfec84 --- /dev/null +++ b/app/views/admins/system_notifications/index.js.erb @@ -0,0 +1 @@ +$('.system-notification-list-container').html("<%= j( render partial: 'admins/system_notifications/list', locals: { notifications: @notifications } ) %>"); \ No newline at end of file diff --git a/app/views/admins/system_notifications/new.js.erb b/app/views/admins/system_notifications/new.js.erb new file mode 100644 index 00000000..885357b5 --- /dev/null +++ b/app/views/admins/system_notifications/new.js.erb @@ -0,0 +1,2 @@ +$("#admins-system-notification-content").html("<%= j render(partial: 'admins/system_notifications/form', locals: {type: 'create'}) %>") +createMDEditor('system-notification-content-editor', { height: 500, placeholder: '请输入邮件模版' }); diff --git a/config/routes.rb b/config/routes.rb index 005bd926..b940ed70 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -670,6 +670,11 @@ Rails.application.routes.draw do resources :project_licenses resources :project_ignores resources :reversed_keywords + resources :system_notifications do + member do + get :history + end + end resources :message_templates, only: [:index, :edit, :update] do collection do get :init_data diff --git a/db/migrate/20211012060724_create_system_notifications.rb b/db/migrate/20211012060724_create_system_notifications.rb new file mode 100644 index 00000000..2dcade41 --- /dev/null +++ b/db/migrate/20211012060724_create_system_notifications.rb @@ -0,0 +1,13 @@ +class CreateSystemNotifications < ActiveRecord::Migration[5.2] + def change + # 系统消息 + create_table :system_notifications do |t| + t.string :subject, comment: "标题" + t.string :sub_subject, comment: "副标题" + t.string :content, comment: "正文" + t.boolean :is_top, comment: "是否置顶" + + t.timestamps + end + end +end diff --git a/db/migrate/20211012060837_create_system_notification_histories.rb b/db/migrate/20211012060837_create_system_notification_histories.rb new file mode 100644 index 00000000..9110f3ce --- /dev/null +++ b/db/migrate/20211012060837_create_system_notification_histories.rb @@ -0,0 +1,10 @@ +class CreateSystemNotificationHistories < ActiveRecord::Migration[5.2] + def change + create_table :system_notification_histories do |t| + t.references :system_notification + t.references :user + + t.timestamps + end + end +end From 490ce7a2344d6cd4e27aec9b95257409e0823274 Mon Sep 17 00:00:00 2001 From: yystopf Date: Tue, 12 Oct 2021 16:34:00 +0800 Subject: [PATCH 112/135] add: setting of system notification --- .../admins/system_notifications_controller.rb | 12 ++++++------ app/controllers/settings_controller.rb | 6 +++++- app/models/system_notification.rb | 9 +++++++++ app/views/settings/show.json.jbuilder | 9 +++++++++ 4 files changed, 29 insertions(+), 7 deletions(-) diff --git a/app/controllers/admins/system_notifications_controller.rb b/app/controllers/admins/system_notifications_controller.rb index 1a71173c..29109fd8 100644 --- a/app/controllers/admins/system_notifications_controller.rb +++ b/app/controllers/admins/system_notifications_controller.rb @@ -6,7 +6,7 @@ class Admins::SystemNotificationsController < Admins::BaseController sort_by = SystemNotification.column_names.include?(params[:sort_by]) ? params[:sort_by] : 'created_at' sort_direction = %w(desc asc).include?(params[:sort_direction]) ? params[:sort_direction] : 'desc' q = SystemNotification.ransack(subject_cont: params[:search]) - notifications = q.result(distinct: true).order("#{sort_by} #{sort_direction},created_at desc") + notifications = q.result(distinct: true).reorder("#{sort_by} #{sort_direction},created_at desc") @notifications = paginate(notifications) end @@ -25,7 +25,7 @@ class Admins::SystemNotificationsController < Admins::BaseController @notification = SystemNotification.new(notification_params) if @notification.save redirect_to admins_system_notifications_path - flash[:success] = '系统保留关键词创建成功' + flash[:success] = '系统消息创建成功' else redirect_to admins_system_notifications_path flash[:danger] = @notification.errors.full_messages.join(",") @@ -38,7 +38,7 @@ class Admins::SystemNotificationsController < Admins::BaseController if @notification.update_attributes(notification_params) format.html do redirect_to admins_system_notifications_path - flash[:success] = '系统保留关键词更新成功' + flash[:success] = '系统消息更新成功' end format.js {render_ok} else @@ -54,10 +54,10 @@ class Admins::SystemNotificationsController < Admins::BaseController def destroy if @notification.destroy redirect_to admins_system_notifications_path - flash[:success] = "系统保留关键词删除成功" + flash[:success] = "系统消息删除成功" else redirect_to admins_system_notifications_path - flash[:danger] = "系统保留关键词删除失败" + flash[:danger] = "系统消息删除失败" end end @@ -70,7 +70,7 @@ class Admins::SystemNotificationsController < Admins::BaseController @notification = SystemNotification.find_by(id: params[:id]) unless @notification.present? redirect_to admins_system_notifications_path - flash[:danger] = "系统保留关键词不存在" + flash[:danger] = "系统消息不存在" end end end \ No newline at end of file diff --git a/app/controllers/settings_controller.rb b/app/controllers/settings_controller.rb index b6662f66..b2dc2e90 100644 --- a/app/controllers/settings_controller.rb +++ b/app/controllers/settings_controller.rb @@ -4,7 +4,7 @@ class SettingsController < ApplicationController get_add_menu get_common_menu get_personal_menu - + get_top_system_notification end private @@ -40,6 +40,10 @@ class SettingsController < ApplicationController end end + def get_top_system_notification + @top_system_notification = SystemNotification.is_top.first + end + def get_site_url(key, value) key.to_s === "url" ? append_http(reset_site_url(value)) : reset_site_url(value) end diff --git a/app/models/system_notification.rb b/app/models/system_notification.rb index 76c514cd..11220dfc 100644 --- a/app/models/system_notification.rb +++ b/app/models/system_notification.rb @@ -12,6 +12,15 @@ class SystemNotification < ApplicationRecord + default_scope { order(created_at: :desc)} + has_many :system_notification_histories has_many :users, through: :system_notification_histories + + scope :is_top, lambda { where(is_top: true) } + + + def read_member?(user_id) + self.system_notification_histories.where(user_id: user_id).present? ? true : false + end end diff --git a/app/views/settings/show.json.jbuilder b/app/views/settings/show.json.jbuilder index 330966aa..c8d4c89e 100644 --- a/app/views/settings/show.json.jbuilder +++ b/app/views/settings/show.json.jbuilder @@ -56,4 +56,13 @@ json.setting do end json.common @common + + if @top_system_notification.present? + json.system_notification do + json.(@top_system_notification, :subject, :sub_subject, :content) + json.is_read @top_system_notification.read_member?(current_user.id) + end + else + json.system_notification nil + end end From 21af31f23c33c77e2a690a57d8bcf962eb17bc5d Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 13 Oct 2021 10:58:41 +0800 Subject: [PATCH 113/135] add: system notification history api --- ...ystem_notification_histories_controller.rb | 15 +++ app/docs/slate/source/includes/_users.md | 30 +++++ app/models/system_notification_history.rb | 2 + app/views/settings/show.json.jbuilder | 2 +- .../system_notification_histories/zh-CN.yml | 6 + config/routes.rb | 1 + public/docs/api.html | 113 ++++++++++++------ 7 files changed, 129 insertions(+), 40 deletions(-) create mode 100644 app/controllers/users/system_notification_histories_controller.rb create mode 100644 config/locales/system_notification_histories/zh-CN.yml diff --git a/app/controllers/users/system_notification_histories_controller.rb b/app/controllers/users/system_notification_histories_controller.rb new file mode 100644 index 00000000..70e91fbb --- /dev/null +++ b/app/controllers/users/system_notification_histories_controller.rb @@ -0,0 +1,15 @@ +class Users::SystemNotificationHistoriesController < Users::BaseController + before_action :private_user_resources!, only: [:create] + def create + @history = observed_user.system_notification_histories.new(system_notification_id: params[:system_notification_id]) + if @history.save + render_ok + else + Rails.logger.info @history.errors.as_json + render_error(@history.errors.full_messages.join(",")) + end + rescue Exception => e + uid_logger_error(e.message) + tip_exception(e.message) + end +end \ No newline at end of file diff --git a/app/docs/slate/source/includes/_users.md b/app/docs/slate/source/includes/_users.md index 9d6b8092..594ce725 100644 --- a/app/docs/slate/source/includes/_users.md +++ b/app/docs/slate/source/includes/_users.md @@ -199,6 +199,36 @@ await octokit.request('GET /api/users/:login/messages.json') Success Data. +## 用户阅读系统通知 +用户阅读系统通知 + +> 示例: + +```shell +curl -X POST http://localhost:3000/api/users/yystopf/system_notification_histories.json +``` + +```javascript +await octokit.request('GET /api/users/:login/system_notification_histories.json') +``` + +### HTTP 请求 +`POST /api/users/:login/system_notification_histories.json` + +### 请求字段说明: +参数 | 类型 | 字段说明 +--------- | ----------- | ----------- +|system_notification_id |integer |阅读的系统通知id | + +> 返回的JSON示例: + +```json +{ + "status": 0, + "message": "success" +} +``` + ## 发送消息 发送消息, 目前只支持atme diff --git a/app/models/system_notification_history.rb b/app/models/system_notification_history.rb index 8723ca91..b629babd 100644 --- a/app/models/system_notification_history.rb +++ b/app/models/system_notification_history.rb @@ -18,4 +18,6 @@ class SystemNotificationHistory < ApplicationRecord belongs_to :system_notification belongs_to :user + + validates :system_notification_id, uniqueness: { scope: :user_id, message: '只能阅读一次'} end diff --git a/app/views/settings/show.json.jbuilder b/app/views/settings/show.json.jbuilder index c8d4c89e..3b0935e0 100644 --- a/app/views/settings/show.json.jbuilder +++ b/app/views/settings/show.json.jbuilder @@ -59,7 +59,7 @@ json.setting do if @top_system_notification.present? json.system_notification do - json.(@top_system_notification, :subject, :sub_subject, :content) + json.(@top_system_notification, :id, :subject, :sub_subject, :content) json.is_read @top_system_notification.read_member?(current_user.id) end else diff --git a/config/locales/system_notification_histories/zh-CN.yml b/config/locales/system_notification_histories/zh-CN.yml new file mode 100644 index 00000000..8dd7b49d --- /dev/null +++ b/config/locales/system_notification_histories/zh-CN.yml @@ -0,0 +1,6 @@ +zh-CN: + activerecord: + attributes: + system_notification_history: + system_notification: "系统通知" + system_notification_id: "系统通知" \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index b940ed70..92061df9 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -263,6 +263,7 @@ Rails.application.routes.draw do end scope module: :users do + resources :system_notification_histories, only: [:create] resources :applied_messages, only: [:index] resources :applied_transfer_projects, only: [:index] do member do diff --git a/public/docs/api.html b/public/docs/api.html index 8368e8fa..0f112178 100644 --- a/public/docs/api.html +++ b/public/docs/api.html @@ -348,6 +348,9 @@
  • 用户消息列表
  • +
  • + 用户阅读系统通知 +
  • 发送消息
  • @@ -1328,7 +1331,39 @@ Success — a happy kitten is an authenticated kitten! -

    发送消息

    +

    用户阅读系统通知

    +

    用户阅读系统通知

    + +
    +

    示例:

    +
    +
    curl -X POST http://localhost:3000/api/users/yystopf/system_notification_histories.json
    +
    await octokit.request('GET /api/users/:login/system_notification_histories.json')
    +

    HTTP 请求

    +

    POST /api/users/:login/system_notification_histories.json

    +

    请求字段说明:

    + + + + + + + + + + + + +
    参数类型字段说明
    system_notification_idinteger阅读的系统通知id
    + +
    +

    返回的JSON示例:

    +
    +
    {
    +    "status": 0,
    +    "message": "success"
    +}
    +

    发送消息

    发送消息, 目前只支持atme

    @@ -1336,9 +1371,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/:login/messages.json
     
    await octokit.request('POST /api/users/:login/messages.json')
    -

    HTTP 请求

    +

    HTTP 请求

    POST api/users/yystopf/messages.json

    -

    请求字段说明:

    +

    请求字段说明:

    @@ -1397,9 +1432,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/:login/messages/read.json
     
    await octokit.request('POST /api/users/:login/messages/read.json')
    -

    HTTP 请求

    +

    HTTP 请求

    POST api/users/yystopf/messages/read.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -1438,9 +1473,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X DELETE http://localhost:3000/api/users/:login/messages.json
     
    await octokit.request('DELETE /api/users/:login/messages.json')
    -

    HTTP 请求

    +

    HTTP 请求

    DELETE api/users/yystopf/messages.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -1479,9 +1514,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X PATCH/PUT http://localhost:3000/api/users/yystopf.json
     
    await octokit.request('PATCH/PUT /api/users/:login.json')
    -

    HTTP 请求

    +

    HTTP 请求

    PATCH/PUT /api/users/:login.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -1577,7 +1612,7 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/is_pinned_projects.json
     
    await octokit.request('GET /api/users/:login/is_pinned_projects.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET api/users/:login/is_pinned_projects.json

    返回字段说明:

    参数
    @@ -1764,9 +1799,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/is_pinned_projects/pin.json
     
    await octokit.request('GET /api/users/:login/is_pinned_projects/pin.json')
    -

    HTTP 请求

    +

    HTTP 请求

    POST /api/users/:login/is_pinned_projects/pin.json

    -

    请求字段说明:

    同时设定多个星标项目

    +

    请求字段说明:

    同时设定多个星标项目

    @@ -1810,9 +1845,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X PATCH http://localhost:3000/api/users/yystopf/is_pinned_projects/11.json
     
    await octokit.request('PATCH/PUT /api/users/:login/is_pinned_projects/:id.json')
    -

    HTTP 请求

    +

    HTTP 请求

    PATCH/PUT /api/users/:login/is_pinned_projects/:id.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -1851,7 +1886,7 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/activity.json
     
    await octokit.request('GET /api/users/:login/statistics/activity.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/activity.json

    返回字段说明:

    参数
    @@ -1940,9 +1975,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/headmaps.json
     
    await octokit.request('GET /api/users/:login/headmaps.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET api/users/:login/headmaps.json

    -

    请求字段说明:

    +

    请求字段说明:

    @@ -2085,9 +2120,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/project_trends.json
     
    await octokit.request('GET /api/users/:login/project_trends.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET api/users/:login/project_trends.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2402,9 +2437,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/develop.json
     
    await octokit.request('GET /api/users/:login/statistics/develop.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/develop.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2545,9 +2580,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/role.json
     
    await octokit.request('GET /api/users/:login/statistics/role.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/role.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2627,9 +2662,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/major.json
     
    await octokit.request('GET /api/users/:login/statistics/major.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/major.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2688,9 +2723,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/applied_messages.json
     
    await octokit.request('GET /api/users/:login/applied_messages.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_messages.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2967,9 +3002,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/applied_transfer_projects.json
     
    await octokit.request('GET /api/users/:login/applied_transfer_projects.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_transfer_projects.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -3159,9 +3194,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/applied_transfer_projects/2/accept.json
     
    await octokit.request('GET /api/users/:login/applied_transfer_projects/:id/accept.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_transfer_projects/:id/accept.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -3350,9 +3385,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/applied_transfer_projects/2/refuse.json
     
    await octokit.request('GET /api/users/:login/applied_transfer_projects/:id/refuse.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_transfer_projects/:id/refuse.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -3541,9 +3576,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/applied_projects.json
     
    await octokit.request('GET /api/users/:login/applied_projects.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_projects.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -3701,9 +3736,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/applied_projects/2/accept.json
     
    await octokit.request('GET /api/users/:login/applied_projects/:id/accept.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_projects/:id/accept.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -3860,9 +3895,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/applied_projects/2/refuse.json
     
    await octokit.request('GET /api/users/:login/applied_projects/:id/refuse.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_projects/:id/refuse.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    From 1b87a7a733e0fb27d00b3b561097467ae596f45b Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 13 Oct 2021 15:50:51 +0800 Subject: [PATCH 114/135] fix: send message job need open notice menu --- app/controllers/issues_controller.rb | 26 +++++++++++++------ app/controllers/members_controller.rb | 10 +++---- .../organizations/team_users_controller.rb | 2 +- .../projects/project_units_controller.rb | 2 +- app/controllers/projects_controller.rb | 2 +- app/controllers/pull_requests_controller.rb | 12 ++++----- app/controllers/users/messages_controller.rb | 8 +++--- app/jobs/delay_expired_issue_job.rb | 4 +-- app/models/organization_user.rb | 4 +-- app/models/site.rb | 4 +++ app/models/watcher.rb | 2 +- app/services/projects/accept_join_service.rb | 4 +-- 12 files changed, 47 insertions(+), 33 deletions(-) diff --git a/app/controllers/issues_controller.rb b/app/controllers/issues_controller.rb index f16edbb3..adbe93e3 100644 --- a/app/controllers/issues_controller.rb +++ b/app/controllers/issues_controller.rb @@ -111,8 +111,8 @@ class IssuesController < ApplicationController Issues::CreateForm.new({subject:issue_params[:subject]}).validate! @issue = Issue.new(issue_params) if @issue.save! - SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @issue&.id) - SendTemplateMessageJob.perform_later('ProjectIssue', current_user.id, @issue&.id) + SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @issue&.id) if Site.has_notice_menu? + SendTemplateMessageJob.perform_later('ProjectIssue', current_user.id, @issue&.id) if Site.has_notice_menu? if params[:attachment_ids].present? params[:attachment_ids].each do |id| attachment = Attachment.select(:id, :container_id, :container_type)&.find_by_id(id) @@ -206,8 +206,8 @@ class IssuesController < ApplicationController Issues::UpdateForm.new({subject:issue_params[:subject]}).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)) - SendTemplateMessageJob.perform_later('PullRequestAssigned', current_user.id, @issue&.pull_request&.id ) if @issue.previous_changes[:assigned_to_id].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? + SendTemplateMessageJob.perform_later('PullRequestAssigned', current_user.id, @issue&.pull_request&.id ) if @issue.previous_changes[:assigned_to_id].present? && Site.has_notice_menu? else previous_changes = @issue.previous_changes.slice(:status_id, :assigned_to_id, :tracker_id, :priority_id, :fixed_version_id, :done_ratio, :issue_tags_value, :branch_name) if @issue.previous_changes[:start_date].present? @@ -216,6 +216,7 @@ class IssuesController < ApplicationController if @issue.previous_changes[:due_date].present? previous_changes.merge!(due_date: [@issue.previous_changes[:due_date][0].to_s, @issue.previous_changes[:due_date][1].to_s]) end +<<<<<<< HEAD if @issue.previous_changes[:status_id].present? && @issue.previous_changes[:status_id][1] == 5 @issue.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: ProjectTrend::CLOSE) end @@ -224,6 +225,10 @@ class IssuesController < ApplicationController end SendTemplateMessageJob.perform_later('IssueChanged', current_user.id, @issue&.id, previous_changes) SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @issue&.id) if @issue.previous_changes[:assigned_to_id].present? +======= + SendTemplateMessageJob.perform_later('IssueChanged', current_user.id, @issue&.id, previous_changes) if Site.has_notice_menu? + SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @issue&.id) if @issue.previous_changes[:assigned_to_id].present? && Site.has_notice_menu? +>>>>>>> 356cafdd (fix: send message job need open notice menu) end if params[:status_id].to_i == 5 #任务由非关闭状态到关闭状态时 @issue.issue_times.update_all(end_time: Time.now) @@ -276,7 +281,7 @@ class IssuesController < ApplicationController status_id = @issue.status_id token = @issue.token login = @issue.user.try(:login) - SendTemplateMessageJob.perform_later('IssueDeleted', current_user.id, @issue&.subject, @issue.assigned_to_id, @issue.author_id) + SendTemplateMessageJob.perform_later('IssueDeleted', current_user.id, @issue&.subject, @issue.assigned_to_id, @issue.author_id) if Site.has_notice_menu? if @issue.destroy if issue_type == "2" && status_id != 5 post_to_chain("add", token, login) @@ -299,7 +304,7 @@ class IssuesController < ApplicationController issues = Issue.where(id: issue_ids, issue_type: "1") if issues.present? issues.find_each do |i| - SendTemplateMessageJob.perform_later('IssueDeleted', current_user.id, i&.subject, i.assigned_to_id, i.author_id) + SendTemplateMessageJob.perform_later('IssueDeleted', current_user.id, i&.subject, i.assigned_to_id, i.author_id) if Site.has_notice_menu? end if issues.destroy_all normal_status(0, "删除成功") @@ -344,6 +349,7 @@ class IssuesController < ApplicationController if i.previous_changes[:due_date].present? previous_changes.merge!(due_date: [i.previous_changes[:due_date][0].to_s, i.previous_changes[:due_date][1].to_s]) end +<<<<<<< HEAD if i.previous_changes[:status_id].present? && i.previous_changes[:status_id][1] == 5 i.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: ProjectTrend::CLOSE) end @@ -352,6 +358,10 @@ class IssuesController < ApplicationController end SendTemplateMessageJob.perform_later('IssueChanged', current_user.id, i&.id, previous_changes) SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, i&.id) if i.previous_changes[:assigned_to_id].present? +======= + SendTemplateMessageJob.perform_later('IssueChanged', current_user.id, i&.id, previous_changes) if Site.has_notice_menu? + SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, i&.id) if i.previous_changes[:assigned_to_id].present? && Site.has_notice_menu? +>>>>>>> 356cafdd (fix: send message job need open notice menu) end normal_status(0, "批量更新成功") else @@ -366,8 +376,8 @@ class IssuesController < ApplicationController @new_issue = @issue.dup @new_issue.author_id = current_user.id if @new_issue.save - SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @new_issue&.id) - SendTemplateMessageJob.perform_later('ProjectIssue', current_user.id, @new_issue&.id) + SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @new_issue&.id) if Site.has_notice_menu? + SendTemplateMessageJob.perform_later('ProjectIssue', current_user.id, @new_issue&.id) if Site.has_notice_menu? issue_tags = @issue.issue_tags.pluck(:id) if issue_tags.present? issue_tags.each do |tag| diff --git a/app/controllers/members_controller.rb b/app/controllers/members_controller.rb index 0af4898f..77087770 100644 --- a/app/controllers/members_controller.rb +++ b/app/controllers/members_controller.rb @@ -9,8 +9,8 @@ class MembersController < ApplicationController def create interactor = Projects::AddMemberInteractor.call(@project.owner, @project, @user) - SendTemplateMessageJob.perform_later('ProjectJoined', current_user.id, @user.id, @project.id) - SendTemplateMessageJob.perform_later('ProjectMemberJoined', current_user.id, @user.id, @project.id) + SendTemplateMessageJob.perform_later('ProjectJoined', current_user.id, @user.id, @project.id) if Site.has_notice_menu? + SendTemplateMessageJob.perform_later('ProjectMemberJoined', current_user.id, @user.id, @project.id) if Site.has_notice_menu? render_response(interactor) rescue Exception => e uid_logger_error(e.message) @@ -30,8 +30,8 @@ class MembersController < ApplicationController def remove interactor = Projects::DeleteMemberInteractor.call(@project.owner, @project, @user) - SendTemplateMessageJob.perform_later('ProjectLeft', current_user.id, @user.id, @project.id) - SendTemplateMessageJob.perform_later('ProjectMemberLeft', current_user.id, @user.id, @project.id) + SendTemplateMessageJob.perform_later('ProjectLeft', current_user.id, @user.id, @project.id) if Site.has_notice_menu? + SendTemplateMessageJob.perform_later('ProjectMemberLeft', current_user.id, @user.id, @project.id) if Site.has_notice_menu? render_response(interactor) rescue Exception => e uid_logger_error(e.message) @@ -40,7 +40,7 @@ class MembersController < ApplicationController def change_role interactor = Projects::ChangeMemberRoleInteractor.call(@project.owner, @project, @user, params[:role]) - SendTemplateMessageJob.perform_later('ProjectRole', current_user.id, @user.id, @project.id, message_role_name) + SendTemplateMessageJob.perform_later('ProjectRole', current_user.id, @user.id, @project.id, message_role_name) if Site.has_notice_menu? render_response(interactor) rescue Exception => e uid_logger_error(e.message) diff --git a/app/controllers/organizations/team_users_controller.rb b/app/controllers/organizations/team_users_controller.rb index c6300526..0a5ff28a 100644 --- a/app/controllers/organizations/team_users_controller.rb +++ b/app/controllers/organizations/team_users_controller.rb @@ -18,7 +18,7 @@ class Organizations::TeamUsersController < Organizations::BaseController ActiveRecord::Base.transaction do @team_user = TeamUser.build(@organization.id, @operate_user.id, @team.id) @organization_user = OrganizationUser.build(@organization.id, @operate_user.id) - SendTemplateMessageJob.perform_later('OrganizationRole', @operate_user.id, @organization.id, @team.authorize_name) + SendTemplateMessageJob.perform_later('OrganizationRole', @operate_user.id, @organization.id, @team.authorize_name) if Site.has_notice_menu? Gitea::Organization::TeamUser::CreateService.call(@organization.gitea_token, @team.gtid, @operate_user.login) end rescue Exception => e diff --git a/app/controllers/projects/project_units_controller.rb b/app/controllers/projects/project_units_controller.rb index e8b8f67a..52cd857d 100644 --- a/app/controllers/projects/project_units_controller.rb +++ b/app/controllers/projects/project_units_controller.rb @@ -7,7 +7,7 @@ class Projects::ProjectUnitsController < Projects::BaseController if current_user.admin? || @project.manager?(current_user) ActiveRecord::Base.transaction do before_units, after_units = ProjectUnit.update_by_unit_types!(@project, unit_types) - SendTemplateMessageJob.perform_later('ProjectSettingChanged', current_user.id, @project&.id, {navbar: true}) unless before_units.eql?(after_units) + SendTemplateMessageJob.perform_later('ProjectSettingChanged', current_user.id, @project&.id, {navbar: true}) unless before_units.eql?(after_units) if Site.has_notice_menu? render_ok end else diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index 0dbb666b..3c5cb1f3 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -145,7 +145,7 @@ class ProjectsController < ApplicationController gitea_repo = Gitea::Repository::UpdateService.call(@owner, @project&.repository&.identifier, gitea_params) @project.repository.update_attributes({hidden: gitea_repo["private"], identifier: gitea_repo["name"]}) end - SendTemplateMessageJob.perform_later('ProjectSettingChanged', current_user.id, @project&.id, @project.previous_changes.slice(:name, :description, :project_category_id, :project_language_id, :is_public)) + SendTemplateMessageJob.perform_later('ProjectSettingChanged', current_user.id, @project&.id, @project.previous_changes.slice(:name, :description, :project_category_id, :project_language_id, :is_public)) if Site.has_notice_menu? end rescue Exception => e uid_logger_error(e.message) diff --git a/app/controllers/pull_requests_controller.rb b/app/controllers/pull_requests_controller.rb index ac3968aa..342f063d 100644 --- a/app/controllers/pull_requests_controller.rb +++ b/app/controllers/pull_requests_controller.rb @@ -59,8 +59,8 @@ class PullRequestsController < ApplicationController @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"]) - SendTemplateMessageJob.perform_later('PullRequestAssigned', current_user.id, @pull_request&.id) - SendTemplateMessageJob.perform_later('ProjectPullRequest', current_user.id, @pull_request&.id) + SendTemplateMessageJob.perform_later('PullRequestAssigned', current_user.id, @pull_request&.id) if Site.has_notice_menu? + SendTemplateMessageJob.perform_later('ProjectPullRequest', current_user.id, @pull_request&.id) if Site.has_notice_menu? else render_error("create pull request error: #{@gitea_pull_request[:status]}") raise ActiveRecord::Rollback @@ -118,8 +118,8 @@ class PullRequestsController < ApplicationController normal_status(-1, e.message) raise ActiveRecord::Rollback end - SendTemplateMessageJob.perform_later('PullRequestChanged', current_user.id, @pull_request&.id, @issue.previous_changes.slice(:assigned_to_id, :priority_id, :fixed_version_id, :issue_tags_value)) - SendTemplateMessageJob.perform_later('PullRequestAssigned', current_user.id, @pull_request&.id ) if @issue.previous_changes[:assigned_to_id].present? + SendTemplateMessageJob.perform_later('PullRequestChanged', current_user.id, @pull_request&.id, @issue.previous_changes.slice(:assigned_to_id, :priority_id, :fixed_version_id, :issue_tags_value)) if Site.has_notice_menu? + SendTemplateMessageJob.perform_later('PullRequestAssigned', current_user.id, @pull_request&.id ) if @issue.previous_changes[:assigned_to_id].present? && Site.has_notice_menu? end end @@ -131,7 +131,7 @@ class PullRequestsController < ApplicationController colsed = PullRequests::CloseService.call(@owner, @repository, @pull_request, current_user) if colsed === true @pull_request.project_trends.create!(user: current_user, project: @project,action_type: ProjectTrend::CLOSE) - SendTemplateMessageJob.perform_later('PullRequestClosed', current_user.id, @pull_request.id) + SendTemplateMessageJob.perform_later('PullRequestClosed', current_user.id, @pull_request.id) if Site.has_notice_menu? normal_status(1, "已拒绝") else normal_status(-1, '合并失败') @@ -175,7 +175,7 @@ class PullRequestsController < ApplicationController # @pull_request.project_trend_status! @pull_request.project_trends.create!(user: current_user, project: @project,action_type: ProjectTrend::MERGE) @issue&.custom_journal_detail("merge", "", "该合并请求已被合并", current_user&.id) - SendTemplateMessageJob.perform_later('PullRequestMerged', current_user.id, @pull_request.id) + SendTemplateMessageJob.perform_later('PullRequestMerged', current_user.id, @pull_request.id) if Site.has_notice_menu? normal_status(1, "合并成功") else normal_status(-1, result.message) diff --git a/app/controllers/users/messages_controller.rb b/app/controllers/users/messages_controller.rb index 035441cc..5116f580 100644 --- a/app/controllers/users/messages_controller.rb +++ b/app/controllers/users/messages_controller.rb @@ -18,16 +18,16 @@ class Users::MessagesController < Users::BaseController Notice::Write::CreateAtmeForm.new(atme_params).validate! case atme_params[:atmeable_type] when 'Issue' - SendTemplateMessageJob.perform_now('IssueAtme', @receivers, current_user.id, atme_params[:atmeable_id]) + SendTemplateMessageJob.perform_now('IssueAtme', @receivers, current_user.id, atme_params[:atmeable_id]) if Site.has_notice_menu? when 'PullRequest' - SendTemplateMessageJob.perform_now('PullRequestAtme', @receivers, current_user.id, atme_params[:atmeable_id]) + SendTemplateMessageJob.perform_now('PullRequestAtme', @receivers, current_user.id, atme_params[:atmeable_id]) if Site.has_notice_menu? when 'Journal' journal = Journal.find_by_id(atme_params[:atmeable_id]) if journal.present? if journal&.issue&.pull_request.present? - SendTemplateMessageJob.perform_now('PullRequestAtme', @receivers, current_user.id, atme_params[:atmeable_id]) + SendTemplateMessageJob.perform_now('PullRequestAtme', @receivers, current_user.id, atme_params[:atmeable_id]) if Site.has_notice_menu? else - SendTemplateMessageJob.perform_now('IssueAtme', @receivers, current_user.id, atme_params[:atmeable_id]) + SendTemplateMessageJob.perform_now('IssueAtme', @receivers, current_user.id, atme_params[:atmeable_id]) if Site.has_notice_menu? end end end diff --git a/app/jobs/delay_expired_issue_job.rb b/app/jobs/delay_expired_issue_job.rb index 4633a953..bf0e1d2e 100644 --- a/app/jobs/delay_expired_issue_job.rb +++ b/app/jobs/delay_expired_issue_job.rb @@ -3,8 +3,8 @@ class DelayExpiredIssueJob < ApplicationJob def perform Issue.where(due_date: Date.today + 1.days).find_each do |issue| - SendTemplateMessageJob.perform_later('IssueAssignerExpire', issue.id) - SendTemplateMessageJob.perform_later('IssueCreatorExpire', issue.id) + SendTemplateMessageJob.perform_later('IssueAssignerExpire', issue.id) if Site.has_notice_menu? + SendTemplateMessageJob.perform_later('IssueCreatorExpire', issue.id) if Site.has_notice_menu? end end diff --git a/app/models/organization_user.rb b/app/models/organization_user.rb index 1ad2abd9..4ff6946b 100644 --- a/app/models/organization_user.rb +++ b/app/models/organization_user.rb @@ -36,10 +36,10 @@ class OrganizationUser < ApplicationRecord end def send_create_message_to_notice_system - SendTemplateMessageJob.perform_later('OrganizationJoined', self.user_id, self.organization_id) + SendTemplateMessageJob.perform_later('OrganizationJoined', self.user_id, self.organization_id) if Site.has_notice_menu? end def send_destroy_message_to_notice_system - SendTemplateMessageJob.perform_later('OrganizationLeft', self.user_id, self.organization_id) + SendTemplateMessageJob.perform_later('OrganizationLeft', self.user_id, self.organization_id) if Site.has_notice_menu? end end diff --git a/app/models/site.rb b/app/models/site.rb index de352dcc..af5e7816 100644 --- a/app/models/site.rb +++ b/app/models/site.rb @@ -26,6 +26,10 @@ class Site < ApplicationRecord set_common_menu! end + def self.has_notice_menu? + self.common.where(key: 'notice').present? + end + private def self.set_add_menu! adds= [ diff --git a/app/models/watcher.rb b/app/models/watcher.rb index 7ff20943..6a8c94fc 100644 --- a/app/models/watcher.rb +++ b/app/models/watcher.rb @@ -37,7 +37,7 @@ class Watcher < ApplicationRecord end def send_create_message_to_notice_system - SendTemplateMessageJob.perform_later('FollowTip', self.id) if self.watchable.is_a?(User) + SendTemplateMessageJob.perform_later('FollowTip', self.id) if self.watchable.is_a?(User) if Site.has_notice_menu? end end diff --git a/app/services/projects/accept_join_service.rb b/app/services/projects/accept_join_service.rb index b1a996fd..2bbacad6 100644 --- a/app/services/projects/accept_join_service.rb +++ b/app/services/projects/accept_join_service.rb @@ -53,8 +53,8 @@ class Projects::AcceptJoinService < ApplicationService def operate_project_member Projects::AddMemberInteractor.call(@project.owner, @project, @applied_project.user, permission) - SendTemplateMessageJob.perform_later('ProjectJoined', @user.id, @applied_project.user_id, @project.id) - SendTemplateMessageJob.perform_later('ProjectMemberJoined', @user.id, @applied_project.user_id, @project.id) + SendTemplateMessageJob.perform_later('ProjectJoined', @user.id, @applied_project.user_id, @project.id) if Site.has_notice_menu? + SendTemplateMessageJob.perform_later('ProjectMemberJoined', @user.id, @applied_project.user_id, @project.id) if Site.has_notice_menu? end def send_apply_message From 0d60e58304d66636a063210442480998a0141c1d Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 13 Oct 2021 17:13:57 +0800 Subject: [PATCH 115/135] fix: system notification edit error --- app/controllers/admins/system_notifications_controller.rb | 1 - app/models/system_notification.rb | 3 ++- app/views/admins/system_notifications/_form.html.erb | 4 ++-- app/views/admins/system_notifications/edit.js.erb | 2 +- ...211013090556_change_system_notification_content_column.rb | 5 +++++ 5 files changed, 10 insertions(+), 5 deletions(-) create mode 100644 db/migrate/20211013090556_change_system_notification_content_column.rb diff --git a/app/controllers/admins/system_notifications_controller.rb b/app/controllers/admins/system_notifications_controller.rb index 29109fd8..e2081f1a 100644 --- a/app/controllers/admins/system_notifications_controller.rb +++ b/app/controllers/admins/system_notifications_controller.rb @@ -33,7 +33,6 @@ class Admins::SystemNotificationsController < Admins::BaseController end def update - respond_to do |format| if @notification.update_attributes(notification_params) format.html do diff --git a/app/models/system_notification.rb b/app/models/system_notification.rb index 11220dfc..8eacd437 100644 --- a/app/models/system_notification.rb +++ b/app/models/system_notification.rb @@ -5,7 +5,8 @@ # id :integer not null, primary key # subject :string(255) # sub_subject :string(255) -# content :string(255) +# content :text(65535) +# is_top :boolean # created_at :datetime not null # updated_at :datetime not null # diff --git a/app/views/admins/system_notifications/_form.html.erb b/app/views/admins/system_notifications/_form.html.erb index 8e761910..33c35747 100644 --- a/app/views/admins/system_notifications/_form.html.erb +++ b/app/views/admins/system_notifications/_form.html.erb @@ -1,6 +1,6 @@
    -
    <%= type == "create" ? "新建" : "编辑" %>忽略文件
    - <%= link_to "返回", admins_project_ignores_path, class: "btn btn-default pull-right" %> +
    <%= type == "create" ? "新建" : "编辑" %>系统通知
    + <%= link_to "返回", admins_system_notifications_path, class: "btn btn-default pull-right" %>
    diff --git a/app/views/admins/system_notifications/edit.js.erb b/app/views/admins/system_notifications/edit.js.erb index 63fad583..e5929f87 100644 --- a/app/views/admins/system_notifications/edit.js.erb +++ b/app/views/admins/system_notifications/edit.js.erb @@ -1,2 +1,2 @@ -$("#admins-system-notification-content").html("<%= j render(partial: 'admins/system_notifications/form', locals: {type: 'create'}) %>") +$("#admins-system-notification-content").html("<%= j render(partial: 'admins/system_notifications/form', locals: {type: 'update'}) %>") createMDEditor('system-notification-content-editor', { height: 500, placeholder: '请输入邮件模版' }); \ No newline at end of file diff --git a/db/migrate/20211013090556_change_system_notification_content_column.rb b/db/migrate/20211013090556_change_system_notification_content_column.rb new file mode 100644 index 00000000..1e0e8092 --- /dev/null +++ b/db/migrate/20211013090556_change_system_notification_content_column.rb @@ -0,0 +1,5 @@ +class ChangeSystemNotificationContentColumn < ActiveRecord::Migration[5.2] + def change + change_column :system_notifications, :content, :text + end +end From 1dcc38f6177b7f9553c3b676fe441c36975908b5 Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 15 Oct 2021 14:54:51 +0800 Subject: [PATCH 116/135] fix: remove system_notification_history --- .../admins/system_notifications_controller.rb | 4 - ...ystem_notification_histories_controller.rb | 15 --- app/docs/slate/source/includes/_users.md | 30 ----- app/models/system_notification.rb | 3 - app/models/system_notification_history.rb | 23 ---- app/models/user.rb | 2 - .../system_notification_histories/zh-CN.yml | 6 - config/routes.rb | 7 +- ...37_create_system_notification_histories.rb | 10 -- public/docs/api.html | 113 ++++++------------ 10 files changed, 40 insertions(+), 173 deletions(-) delete mode 100644 app/controllers/users/system_notification_histories_controller.rb delete mode 100644 app/models/system_notification_history.rb delete mode 100644 config/locales/system_notification_histories/zh-CN.yml delete mode 100644 db/migrate/20211012060837_create_system_notification_histories.rb diff --git a/app/controllers/admins/system_notifications_controller.rb b/app/controllers/admins/system_notifications_controller.rb index e2081f1a..0dc7dd2a 100644 --- a/app/controllers/admins/system_notifications_controller.rb +++ b/app/controllers/admins/system_notifications_controller.rb @@ -10,10 +10,6 @@ class Admins::SystemNotificationsController < Admins::BaseController @notifications = paginate(notifications) end - def history - @users = @notification.users - end - def new @notification = SystemNotification.new end diff --git a/app/controllers/users/system_notification_histories_controller.rb b/app/controllers/users/system_notification_histories_controller.rb deleted file mode 100644 index 70e91fbb..00000000 --- a/app/controllers/users/system_notification_histories_controller.rb +++ /dev/null @@ -1,15 +0,0 @@ -class Users::SystemNotificationHistoriesController < Users::BaseController - before_action :private_user_resources!, only: [:create] - def create - @history = observed_user.system_notification_histories.new(system_notification_id: params[:system_notification_id]) - if @history.save - render_ok - else - Rails.logger.info @history.errors.as_json - render_error(@history.errors.full_messages.join(",")) - end - rescue Exception => e - uid_logger_error(e.message) - tip_exception(e.message) - end -end \ No newline at end of file diff --git a/app/docs/slate/source/includes/_users.md b/app/docs/slate/source/includes/_users.md index 594ce725..9d6b8092 100644 --- a/app/docs/slate/source/includes/_users.md +++ b/app/docs/slate/source/includes/_users.md @@ -199,36 +199,6 @@ await octokit.request('GET /api/users/:login/messages.json') Success Data. -## 用户阅读系统通知 -用户阅读系统通知 - -> 示例: - -```shell -curl -X POST http://localhost:3000/api/users/yystopf/system_notification_histories.json -``` - -```javascript -await octokit.request('GET /api/users/:login/system_notification_histories.json') -``` - -### HTTP 请求 -`POST /api/users/:login/system_notification_histories.json` - -### 请求字段说明: -参数 | 类型 | 字段说明 ---------- | ----------- | ----------- -|system_notification_id |integer |阅读的系统通知id | - -> 返回的JSON示例: - -```json -{ - "status": 0, - "message": "success" -} -``` - ## 发送消息 发送消息, 目前只支持atme diff --git a/app/models/system_notification.rb b/app/models/system_notification.rb index 8eacd437..848d592d 100644 --- a/app/models/system_notification.rb +++ b/app/models/system_notification.rb @@ -15,9 +15,6 @@ class SystemNotification < ApplicationRecord default_scope { order(created_at: :desc)} - has_many :system_notification_histories - has_many :users, through: :system_notification_histories - scope :is_top, lambda { where(is_top: true) } diff --git a/app/models/system_notification_history.rb b/app/models/system_notification_history.rb deleted file mode 100644 index b629babd..00000000 --- a/app/models/system_notification_history.rb +++ /dev/null @@ -1,23 +0,0 @@ -# == Schema Information -# -# Table name: system_notification_histories -# -# id :integer not null, primary key -# system_message_id :integer -# user_id :integer -# created_at :datetime not null -# updated_at :datetime not null -# -# Indexes -# -# index_system_notification_histories_on_system_message_id (system_message_id) -# index_system_notification_histories_on_user_id (user_id) -# - -class SystemNotificationHistory < ApplicationRecord - - belongs_to :system_notification - belongs_to :user - - validates :system_notification_id, uniqueness: { scope: :user_id, message: '只能阅读一次'} -end diff --git a/app/models/user.rb b/app/models/user.rb index 22c5e3cd..623694b3 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -170,8 +170,6 @@ class User < Owner has_many :issues, dependent: :destroy, foreign_key: :author_id has_many :pull_requests, dependent: :destroy has_many :public_keys, class_name: "Gitea::PublicKey",primary_key: :gitea_uid, foreign_key: :owner_id, dependent: :destroy - has_many :system_notification_histories - has_many :system_notifications, through: :system_notification_histories # Groups and active users scope :active, lambda { where(status: STATUS_ACTIVE) } diff --git a/config/locales/system_notification_histories/zh-CN.yml b/config/locales/system_notification_histories/zh-CN.yml deleted file mode 100644 index 8dd7b49d..00000000 --- a/config/locales/system_notification_histories/zh-CN.yml +++ /dev/null @@ -1,6 +0,0 @@ -zh-CN: - activerecord: - attributes: - system_notification_history: - system_notification: "系统通知" - system_notification_id: "系统通知" \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index 92061df9..9e5ffa2f 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -263,7 +263,6 @@ Rails.application.routes.draw do end scope module: :users do - resources :system_notification_histories, only: [:create] resources :applied_messages, only: [:index] resources :applied_transfer_projects, only: [:index] do member do @@ -671,11 +670,7 @@ Rails.application.routes.draw do resources :project_licenses resources :project_ignores resources :reversed_keywords - resources :system_notifications do - member do - get :history - end - end + resources :system_notifications resources :message_templates, only: [:index, :edit, :update] do collection do get :init_data diff --git a/db/migrate/20211012060837_create_system_notification_histories.rb b/db/migrate/20211012060837_create_system_notification_histories.rb deleted file mode 100644 index 9110f3ce..00000000 --- a/db/migrate/20211012060837_create_system_notification_histories.rb +++ /dev/null @@ -1,10 +0,0 @@ -class CreateSystemNotificationHistories < ActiveRecord::Migration[5.2] - def change - create_table :system_notification_histories do |t| - t.references :system_notification - t.references :user - - t.timestamps - end - end -end diff --git a/public/docs/api.html b/public/docs/api.html index 0f112178..8368e8fa 100644 --- a/public/docs/api.html +++ b/public/docs/api.html @@ -348,9 +348,6 @@
  • 用户消息列表
  • -
  • - 用户阅读系统通知 -
  • 发送消息
  • @@ -1331,39 +1328,7 @@ Success — a happy kitten is an authenticated kitten! -

    用户阅读系统通知

    -

    用户阅读系统通知

    - -
    -

    示例:

    -
    -
    curl -X POST http://localhost:3000/api/users/yystopf/system_notification_histories.json
    -
    await octokit.request('GET /api/users/:login/system_notification_histories.json')
    -

    HTTP 请求

    -

    POST /api/users/:login/system_notification_histories.json

    -

    请求字段说明:

    -
    参数
    - - - - - - - - - - - -
    参数类型字段说明
    system_notification_idinteger阅读的系统通知id
    - -
    -

    返回的JSON示例:

    -
    -
    {
    -    "status": 0,
    -    "message": "success"
    -}
    -

    发送消息

    +

    发送消息

    发送消息, 目前只支持atme

    @@ -1371,9 +1336,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/:login/messages.json
     
    await octokit.request('POST /api/users/:login/messages.json')
    -

    HTTP 请求

    +

    HTTP 请求

    POST api/users/yystopf/messages.json

    -

    请求字段说明:

    +

    请求字段说明:

    @@ -1432,9 +1397,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/:login/messages/read.json
     
    await octokit.request('POST /api/users/:login/messages/read.json')
    -

    HTTP 请求

    +

    HTTP 请求

    POST api/users/yystopf/messages/read.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -1473,9 +1438,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X DELETE http://localhost:3000/api/users/:login/messages.json
     
    await octokit.request('DELETE /api/users/:login/messages.json')
    -

    HTTP 请求

    +

    HTTP 请求

    DELETE api/users/yystopf/messages.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -1514,9 +1479,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X PATCH/PUT http://localhost:3000/api/users/yystopf.json
     
    await octokit.request('PATCH/PUT /api/users/:login.json')
    -

    HTTP 请求

    +

    HTTP 请求

    PATCH/PUT /api/users/:login.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -1612,7 +1577,7 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/is_pinned_projects.json
     
    await octokit.request('GET /api/users/:login/is_pinned_projects.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET api/users/:login/is_pinned_projects.json

    返回字段说明:

    参数
    @@ -1799,9 +1764,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/is_pinned_projects/pin.json
     
    await octokit.request('GET /api/users/:login/is_pinned_projects/pin.json')
    -

    HTTP 请求

    +

    HTTP 请求

    POST /api/users/:login/is_pinned_projects/pin.json

    -

    请求字段说明:

    同时设定多个星标项目

    +

    请求字段说明:

    同时设定多个星标项目

    @@ -1845,9 +1810,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X PATCH http://localhost:3000/api/users/yystopf/is_pinned_projects/11.json
     
    await octokit.request('PATCH/PUT /api/users/:login/is_pinned_projects/:id.json')
    -

    HTTP 请求

    +

    HTTP 请求

    PATCH/PUT /api/users/:login/is_pinned_projects/:id.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -1886,7 +1851,7 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/activity.json
     
    await octokit.request('GET /api/users/:login/statistics/activity.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/activity.json

    返回字段说明:

    参数
    @@ -1975,9 +1940,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/headmaps.json
     
    await octokit.request('GET /api/users/:login/headmaps.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET api/users/:login/headmaps.json

    -

    请求字段说明:

    +

    请求字段说明:

    @@ -2120,9 +2085,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/project_trends.json
     
    await octokit.request('GET /api/users/:login/project_trends.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET api/users/:login/project_trends.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2437,9 +2402,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/develop.json
     
    await octokit.request('GET /api/users/:login/statistics/develop.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/develop.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2580,9 +2545,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/role.json
     
    await octokit.request('GET /api/users/:login/statistics/role.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/role.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2662,9 +2627,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/major.json
     
    await octokit.request('GET /api/users/:login/statistics/major.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/major.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2723,9 +2688,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/applied_messages.json
     
    await octokit.request('GET /api/users/:login/applied_messages.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_messages.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -3002,9 +2967,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/applied_transfer_projects.json
     
    await octokit.request('GET /api/users/:login/applied_transfer_projects.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_transfer_projects.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -3194,9 +3159,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/applied_transfer_projects/2/accept.json
     
    await octokit.request('GET /api/users/:login/applied_transfer_projects/:id/accept.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_transfer_projects/:id/accept.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -3385,9 +3350,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/applied_transfer_projects/2/refuse.json
     
    await octokit.request('GET /api/users/:login/applied_transfer_projects/:id/refuse.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_transfer_projects/:id/refuse.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -3576,9 +3541,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/applied_projects.json
     
    await octokit.request('GET /api/users/:login/applied_projects.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_projects.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -3736,9 +3701,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/applied_projects/2/accept.json
     
    await octokit.request('GET /api/users/:login/applied_projects/:id/accept.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_projects/:id/accept.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -3895,9 +3860,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/applied_projects/2/refuse.json
     
    await octokit.request('GET /api/users/:login/applied_projects/:id/refuse.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_projects/:id/refuse.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    From 0885b7d75d4e6c3c4378fe1ee8c08a612d03df66 Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 15 Oct 2021 15:02:56 +0800 Subject: [PATCH 117/135] fix --- app/models/system_notification.rb | 4 ---- 1 file changed, 4 deletions(-) diff --git a/app/models/system_notification.rb b/app/models/system_notification.rb index 848d592d..6f901b3f 100644 --- a/app/models/system_notification.rb +++ b/app/models/system_notification.rb @@ -17,8 +17,4 @@ class SystemNotification < ApplicationRecord scope :is_top, lambda { where(is_top: true) } - - def read_member?(user_id) - self.system_notification_histories.where(user_id: user_id).present? ? true : false - end end From 2d4f08316433a73f500ade1a6e745f94ecf64120 Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 15 Oct 2021 15:04:16 +0800 Subject: [PATCH 118/135] fix --- app/views/settings/show.json.jbuilder | 1 - 1 file changed, 1 deletion(-) diff --git a/app/views/settings/show.json.jbuilder b/app/views/settings/show.json.jbuilder index 3b0935e0..1147ffde 100644 --- a/app/views/settings/show.json.jbuilder +++ b/app/views/settings/show.json.jbuilder @@ -60,7 +60,6 @@ json.setting do if @top_system_notification.present? json.system_notification do json.(@top_system_notification, :id, :subject, :sub_subject, :content) - json.is_read @top_system_notification.read_member?(current_user.id) end else json.system_notification nil From ff97daac545e55f1eec46d4349961b9de7097dfe Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 18 Oct 2021 13:52:52 +0800 Subject: [PATCH 119/135] fix --- app/controllers/issues_controller.rb | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/app/controllers/issues_controller.rb b/app/controllers/issues_controller.rb index adbe93e3..446c699e 100644 --- a/app/controllers/issues_controller.rb +++ b/app/controllers/issues_controller.rb @@ -216,19 +216,14 @@ class IssuesController < ApplicationController if @issue.previous_changes[:due_date].present? previous_changes.merge!(due_date: [@issue.previous_changes[:due_date][0].to_s, @issue.previous_changes[:due_date][1].to_s]) end -<<<<<<< HEAD if @issue.previous_changes[:status_id].present? && @issue.previous_changes[:status_id][1] == 5 @issue.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: ProjectTrend::CLOSE) end if @issue.previous_changes[:status_id].present? && @issue.previous_changes[:status_id][0] == 5 @issue.project_trends.where(action_type: ProjectTrend::CLOSE).destroy_all end - SendTemplateMessageJob.perform_later('IssueChanged', current_user.id, @issue&.id, previous_changes) - SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @issue&.id) if @issue.previous_changes[:assigned_to_id].present? -======= SendTemplateMessageJob.perform_later('IssueChanged', current_user.id, @issue&.id, previous_changes) if Site.has_notice_menu? SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @issue&.id) if @issue.previous_changes[:assigned_to_id].present? && Site.has_notice_menu? ->>>>>>> 356cafdd (fix: send message job need open notice menu) end if params[:status_id].to_i == 5 #任务由非关闭状态到关闭状态时 @issue.issue_times.update_all(end_time: Time.now) @@ -349,19 +344,14 @@ class IssuesController < ApplicationController if i.previous_changes[:due_date].present? previous_changes.merge!(due_date: [i.previous_changes[:due_date][0].to_s, i.previous_changes[:due_date][1].to_s]) end -<<<<<<< HEAD if i.previous_changes[:status_id].present? && i.previous_changes[:status_id][1] == 5 i.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: ProjectTrend::CLOSE) end if i.previous_changes[:status_id].present? && i.previous_changes[:status_id][0] == 5 i.project_trends.where(action_type: ProjectTrend::CLOSE).destroy_all end - SendTemplateMessageJob.perform_later('IssueChanged', current_user.id, i&.id, previous_changes) - SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, i&.id) if i.previous_changes[:assigned_to_id].present? -======= SendTemplateMessageJob.perform_later('IssueChanged', current_user.id, i&.id, previous_changes) if Site.has_notice_menu? SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, i&.id) if i.previous_changes[:assigned_to_id].present? && Site.has_notice_menu? ->>>>>>> 356cafdd (fix: send message job need open notice menu) end normal_status(0, "批量更新成功") else From 8252cb7e71fb30fc4686d94de5912bcc2fe85dde Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 13 Oct 2021 17:04:28 +0800 Subject: [PATCH 120/135] add: template setting model --- app/models/template_message_setting.rb | 21 ++++++++++++++++ .../create_or_assign.rb | 25 +++++++++++++++++++ app/models/template_message_setting/manage.rb | 25 +++++++++++++++++++ app/models/template_message_setting/normal.rb | 23 +++++++++++++++++ app/models/template_message_setting/watch.rb | 21 ++++++++++++++++ app/models/user_template_message_setting.rb | 18 +++++++++++++ ...081221_create_template_message_settings.rb | 15 +++++++++++ ...3_create_user_template_message_settings.rb | 12 +++++++++ 8 files changed, 160 insertions(+) create mode 100644 app/models/template_message_setting.rb create mode 100644 app/models/template_message_setting/create_or_assign.rb create mode 100644 app/models/template_message_setting/manage.rb create mode 100644 app/models/template_message_setting/normal.rb create mode 100644 app/models/template_message_setting/watch.rb create mode 100644 app/models/user_template_message_setting.rb create mode 100644 db/migrate/20211013081221_create_template_message_settings.rb create mode 100644 db/migrate/20211013081713_create_user_template_message_settings.rb diff --git a/app/models/template_message_setting.rb b/app/models/template_message_setting.rb new file mode 100644 index 00000000..349805bd --- /dev/null +++ b/app/models/template_message_setting.rb @@ -0,0 +1,21 @@ +# == Schema Information +# +# Table name: template_message_settings +# +# id :integer not null, primary key +# type :string(255) +# name :string(255) +# key :string(255) +# openning :boolean +# notification_disabled :boolean +# email_disabled :boolean +# created_at :datetime not null +# updated_at :datetime not null +# + +class TemplateMessageSetting < ApplicationRecord + + def self.build_init_data + + end +end diff --git a/app/models/template_message_setting/create_or_assign.rb b/app/models/template_message_setting/create_or_assign.rb new file mode 100644 index 00000000..385a3af8 --- /dev/null +++ b/app/models/template_message_setting/create_or_assign.rb @@ -0,0 +1,25 @@ +# == Schema Information +# +# Table name: template_message_settings +# +# id :integer not null, primary key +# type :string(255) +# name :string(255) +# key :string(255) +# openning :boolean +# notification_disabled :boolean +# email_disabled :boolean +# created_at :datetime not null +# updated_at :datetime not null +# + +#我创建的或负责的 +class TemplateMessageSetting::CreateOrAssign < TemplateMessageSetting + + def self.build_init_data + self.find_or_create_by(name: "易修状态变更", key: "IssueChanged") + self.find_or_create_by(name: "易修被指派", key: "IssueAssigned") + self.find_or_create_by(name: "合并请求被指派", key: "PullRequestAssigned") + self.find_or_create_by(name: "合并请求状态变更", key: "PullRequestAssigned") + end +end diff --git a/app/models/template_message_setting/manage.rb b/app/models/template_message_setting/manage.rb new file mode 100644 index 00000000..925d503f --- /dev/null +++ b/app/models/template_message_setting/manage.rb @@ -0,0 +1,25 @@ +# == Schema Information +# +# Table name: template_message_settings +# +# id :integer not null, primary key +# type :string(255) +# name :string(255) +# key :string(255) +# openning :boolean +# notification_disabled :boolean +# email_disabled :boolean +# created_at :datetime not null +# updated_at :datetime not null +# + +#我管理的 +class TemplateMessageSetting::Manage < TemplateMessageSetting + + def self.build_init_data + self.find_or_create_by(name: "有新的易修", key: "ProjectIssue") + self.find_or_create_by(name: "有新的合并请求", key: "ProjectPullRequest") + self.find_or_create_by(name: "有成员变动", key: "ProjectMember") + self.find_or_create_by(name: "设置更改", key: "ProjectSettingChanged") + end +end diff --git a/app/models/template_message_setting/normal.rb b/app/models/template_message_setting/normal.rb new file mode 100644 index 00000000..9801891a --- /dev/null +++ b/app/models/template_message_setting/normal.rb @@ -0,0 +1,23 @@ +# == Schema Information +# +# Table name: template_message_settings +# +# id :integer not null, primary key +# type :string(255) +# name :string(255) +# key :string(255) +# openning :boolean +# notification_disabled :boolean +# email_disabled :boolean +# created_at :datetime not null +# updated_at :datetime not null +# + +class TemplateMessageSetting::Normal < TemplateMessageSetting + + def self.build_init_data + self.find_or_create_by(name: "被拉入或移出组织", key: "Organization") + self.find_or_create_by(name: "被拉入或移出项目", key: "Project") + self.find_or_create_by(name: "有权限变更", key: "Permission") + end +end diff --git a/app/models/template_message_setting/watch.rb b/app/models/template_message_setting/watch.rb new file mode 100644 index 00000000..d6d5820a --- /dev/null +++ b/app/models/template_message_setting/watch.rb @@ -0,0 +1,21 @@ +# == Schema Information +# +# Table name: template_message_settings +# +# id :integer not null, primary key +# type :string(255) +# name :string(255) +# key :string(255) +# openning :boolean +# notification_disabled :boolean +# email_disabled :boolean +# created_at :datetime not null +# updated_at :datetime not null +# + +#我关注的 +class TemplateMessageSetting::Watch < TemplateMessageSetting + + def self.build_init_data + end +end diff --git a/app/models/user_template_message_setting.rb b/app/models/user_template_message_setting.rb new file mode 100644 index 00000000..5c6f3a2f --- /dev/null +++ b/app/models/user_template_message_setting.rb @@ -0,0 +1,18 @@ +# == Schema Information +# +# Table name: user_template_message_settings +# +# id :integer not null, primary key +# user_id :integer +# notification_body :text(65535) +# email_body :text(65535) +# created_at :datetime not null +# updated_at :datetime not null +# +# Indexes +# +# index_user_template_message_settings_on_user_id (user_id) +# + +class UserTemplateMessageSetting < ApplicationRecord +end diff --git a/db/migrate/20211013081221_create_template_message_settings.rb b/db/migrate/20211013081221_create_template_message_settings.rb new file mode 100644 index 00000000..618d43b6 --- /dev/null +++ b/db/migrate/20211013081221_create_template_message_settings.rb @@ -0,0 +1,15 @@ +class CreateTemplateMessageSettings < ActiveRecord::Migration[5.2] + def change + # 平台的通知设置 + create_table :template_message_settings do |t| + t.string :type + t.string :name + t.string :key + t.boolean :openning, default: true + t.boolean :notification_disabled, default: true + t.boolean :email_disabled, default: false + + t.timestamps + end + end +end diff --git a/db/migrate/20211013081713_create_user_template_message_settings.rb b/db/migrate/20211013081713_create_user_template_message_settings.rb new file mode 100644 index 00000000..47964d3f --- /dev/null +++ b/db/migrate/20211013081713_create_user_template_message_settings.rb @@ -0,0 +1,12 @@ +class CreateUserTemplateMessageSettings < ActiveRecord::Migration[5.2] + def change + # 用户对系统通知的设置 + create_table :user_template_message_settings do |t| + t.references :user + t.text :notification_body + t.text :email_body + + t.timestamps + end + end +end From d54dcb6b676439457943fdf289196e87814b763a Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 14 Oct 2021 14:12:50 +0800 Subject: [PATCH 121/135] add: template message settings api --- .../template_message_settings_controller.rb | 8 + app/docs/slate/source/includes/_users.md | 140 ++++ app/models/template_message_setting.rb | 11 +- .../create_or_assign.rb | 4 + .../{manage.rb => manage_project.rb} | 6 +- app/models/template_message_setting/normal.rb | 4 + .../{watch.rb => watch_project.rb} | 6 +- .../_detail.json.jbuilder | 8 + .../index.json.jbuilder | 11 + config/routes.rb | 2 + ...081221_create_template_message_settings.rb | 2 + public/docs/api.html | 607 +++++++++++------- 12 files changed, 587 insertions(+), 222 deletions(-) create mode 100644 app/controllers/template_message_settings_controller.rb rename app/models/template_message_setting/{manage.rb => manage_project.rb} (86%) rename app/models/template_message_setting/{watch.rb => watch_project.rb} (80%) create mode 100644 app/views/template_message_settings/_detail.json.jbuilder create mode 100644 app/views/template_message_settings/index.json.jbuilder diff --git a/app/controllers/template_message_settings_controller.rb b/app/controllers/template_message_settings_controller.rb new file mode 100644 index 00000000..967481f2 --- /dev/null +++ b/app/controllers/template_message_settings_controller.rb @@ -0,0 +1,8 @@ +class TemplateMessageSettingsController < ApplicationController + before_action :require_login + + def index + @group_settings = TemplateMessageSetting.group(:type).count + end + +end \ No newline at end of file diff --git a/app/docs/slate/source/includes/_users.md b/app/docs/slate/source/includes/_users.md index 9d6b8092..d0251602 100644 --- a/app/docs/slate/source/includes/_users.md +++ b/app/docs/slate/source/includes/_users.md @@ -372,6 +372,146 @@ await octokit.request('PATCH/PUT /api/users/:login.json') "message": "success" } ``` + +## 获取平台消息设置配置信息 +获取平台消息设置配置信息 + +> 示例: + +```shell +curl -X GET http://localhost:3000/api/template_message_settings.json +``` + +```javascript +await octokit.request('GET /api/template_message_settings.json') +``` + +### HTTP 请求 +`GET /api/template_message_settings.json` + +### 返回字段说明: +参数 | 类型 | 字段说明 +--------- | ----------- | ----------- +|type |string |消息配置类型 | +|type_name |string |消息配置类型含义| +|total_settings_count |int |配置条数| +|settings.name |string |配置名称| +|settings.key |string |配置标识| +|settings.notification_disabled |boolean |站内信设置是否禁用| +|settings.email_disabled |boolean |邮件设置是否禁用| + + +> 返回的JSON示例: + +```json +{ + "status": 0, + "message": "响应成功", + "setting_types": [ + { + "type": "TemplateMessageSetting::CreateOrAssign", + "type_name": "我创建的或负责的", + "total_settings_count": 4, + "settings": [ + { + "name": "易修状态变更", + "key": "IssueChanged", + "openning": true, + "notification_disabled": true, + "email_disabled": false + }, + { + "name": "易修被指派", + "key": "IssueAssigned", + "openning": true, + "notification_disabled": true, + "email_disabled": false + }, + { + "name": "合并请求被指派", + "key": "PullRequestAssigned", + "openning": true, + "notification_disabled": true, + "email_disabled": false + }, + { + "name": "合并请求状态变更", + "key": "PullRequestAssigned", + "openning": true, + "notification_disabled": true, + "email_disabled": false + } + ] + }, + { + "type": "TemplateMessageSetting::ManageProject", + "type_name": "我管理的仓库", + "total_settings_count": 4, + "settings": [ + { + "name": "有新的易修", + "key": "ProjectIssue", + "openning": true, + "notification_disabled": true, + "email_disabled": false + }, + { + "name": "有新的合并请求", + "key": "ProjectPullRequest", + "openning": true, + "notification_disabled": true, + "email_disabled": false + }, + { + "name": "有成员变动", + "key": "ProjectMember", + "openning": true, + "notification_disabled": true, + "email_disabled": false + }, + { + "name": "设置更改", + "key": "ProjectSettingChanged", + "openning": true, + "notification_disabled": true, + "email_disabled": false + } + ] + }, + { + "type": "TemplateMessageSetting::Normal", + "type_name": "", + "total_settings_count": 3, + "settings": [ + { + "name": "被拉入或移出组织", + "key": "Organization", + "openning": true, + "notification_disabled": true, + "email_disabled": false + }, + { + "name": "被拉入或移出项目", + "key": "Project", + "openning": true, + "notification_disabled": true, + "email_disabled": false + }, + { + "name": "有权限变更", + "key": "Permission", + "openning": true, + "notification_disabled": true, + "email_disabled": false + } + ] + } + ] +} +``` + ## 获取用户星标项目 获取用户星标项目 diff --git a/app/models/template_message_setting.rb b/app/models/template_message_setting.rb index 349805bd..a9c81500 100644 --- a/app/models/template_message_setting.rb +++ b/app/models/template_message_setting.rb @@ -15,7 +15,16 @@ class TemplateMessageSetting < ApplicationRecord + scope :openning, ->() {where(openning: true)} + + def self.type_name + "" + end + def self.build_init_data - + TemplateMessageSetting::CreateOrAssign.build_init_data + TemplateMessageSetting::ManageProject.build_init_data + TemplateMessageSetting::Normal.build_init_data + TemplateMessageSetting::WatchProject.build_init_data end end diff --git a/app/models/template_message_setting/create_or_assign.rb b/app/models/template_message_setting/create_or_assign.rb index 385a3af8..df98a5ca 100644 --- a/app/models/template_message_setting/create_or_assign.rb +++ b/app/models/template_message_setting/create_or_assign.rb @@ -16,6 +16,10 @@ #我创建的或负责的 class TemplateMessageSetting::CreateOrAssign < TemplateMessageSetting + def self.type_name + "我创建的或负责的" + end + def self.build_init_data self.find_or_create_by(name: "易修状态变更", key: "IssueChanged") self.find_or_create_by(name: "易修被指派", key: "IssueAssigned") diff --git a/app/models/template_message_setting/manage.rb b/app/models/template_message_setting/manage_project.rb similarity index 86% rename from app/models/template_message_setting/manage.rb rename to app/models/template_message_setting/manage_project.rb index 925d503f..b0f535ea 100644 --- a/app/models/template_message_setting/manage.rb +++ b/app/models/template_message_setting/manage_project.rb @@ -14,7 +14,11 @@ # #我管理的 -class TemplateMessageSetting::Manage < TemplateMessageSetting +class TemplateMessageSetting::ManageProject < TemplateMessageSetting + + def self.type_name + "我管理的仓库" + end def self.build_init_data self.find_or_create_by(name: "有新的易修", key: "ProjectIssue") diff --git a/app/models/template_message_setting/normal.rb b/app/models/template_message_setting/normal.rb index 9801891a..789e35b6 100644 --- a/app/models/template_message_setting/normal.rb +++ b/app/models/template_message_setting/normal.rb @@ -15,6 +15,10 @@ class TemplateMessageSetting::Normal < TemplateMessageSetting + def self.type_name + "" + end + def self.build_init_data self.find_or_create_by(name: "被拉入或移出组织", key: "Organization") self.find_or_create_by(name: "被拉入或移出项目", key: "Project") diff --git a/app/models/template_message_setting/watch.rb b/app/models/template_message_setting/watch_project.rb similarity index 80% rename from app/models/template_message_setting/watch.rb rename to app/models/template_message_setting/watch_project.rb index d6d5820a..169e68e8 100644 --- a/app/models/template_message_setting/watch.rb +++ b/app/models/template_message_setting/watch_project.rb @@ -14,7 +14,11 @@ # #我关注的 -class TemplateMessageSetting::Watch < TemplateMessageSetting +class TemplateMessageSetting::WatchProject < TemplateMessageSetting + + def self.type_name + "我关注的仓库" + end def self.build_init_data end diff --git a/app/views/template_message_settings/_detail.json.jbuilder b/app/views/template_message_settings/_detail.json.jbuilder new file mode 100644 index 00000000..d85a4c4e --- /dev/null +++ b/app/views/template_message_settings/_detail.json.jbuilder @@ -0,0 +1,8 @@ +json.type type +json.type_name type.constantize.type_name +json.total_settings_count count +json.settings do + json.array! type.constantize.openning.limit(100).each do |setting| + json.(setting, :name, :key, :notification_disabled, :email_disabled) + end +end \ No newline at end of file diff --git a/app/views/template_message_settings/index.json.jbuilder b/app/views/template_message_settings/index.json.jbuilder new file mode 100644 index 00000000..3ca13679 --- /dev/null +++ b/app/views/template_message_settings/index.json.jbuilder @@ -0,0 +1,11 @@ +json.partial! "commons/success" +json.setting_types do + + json.array! @group_settings.keys.each do |k| + json.partial! "detail", type: k, count: @group_settings[k] + end + + # json.array! @group_settings, partial: 'detail', as: :type + + +end \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index 9e5ffa2f..34fa0ed6 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -150,6 +150,8 @@ Rails.application.routes.draw do resources :issue_depends, only: [:create, :destroy] end + resources :template_message_settings, only: [:index] + resources :applied_projects, only: [:create] resources :project_categories, only: [:index, :show] do diff --git a/db/migrate/20211013081221_create_template_message_settings.rb b/db/migrate/20211013081221_create_template_message_settings.rb index 618d43b6..a3140493 100644 --- a/db/migrate/20211013081221_create_template_message_settings.rb +++ b/db/migrate/20211013081221_create_template_message_settings.rb @@ -11,5 +11,7 @@ class CreateTemplateMessageSettings < ActiveRecord::Migration[5.2] t.timestamps end + + TemplateMessageSetting.build_init_data end end diff --git a/public/docs/api.html b/public/docs/api.html index 8368e8fa..ecfdb055 100644 --- a/public/docs/api.html +++ b/public/docs/api.html @@ -360,6 +360,9 @@
  • 更改用户信息
  • +
  • + 获取平台消息设置配置信息 +
  • 获取用户星标项目
  • @@ -1569,7 +1572,173 @@ Success — a happy kitten is an authenticated kitten! "status": 0, "message": "success" } -

    获取用户星标项目

    +

    获取平台消息设置配置信息

    +

    获取平台消息设置配置信息

    + +
    +

    示例:

    +
    +
    curl -X GET http://localhost:3000/api/template_message_settings.json
    +
    await octokit.request('GET /api/template_message_settings.json')
    +

    HTTP 请求

    +

    GET /api/template_message_settings.json

    +

    返回字段说明:

    +
    参数
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数类型字段说明
    typestring消息配置类型
    type_namestring消息配置类型含义
    total_settings_countint配置条数
    settings.namestring配置名称
    settings.keystring配置标识
    settings.notification_disabledboolean站内信设置是否禁用
    settings.email_disabledboolean邮件设置是否禁用
    + +
    +

    返回的JSON示例:

    +
    +
    {
    +    "status": 0,
    +    "message": "响应成功",
    +    "setting_types": [
    +        {
    +            "type": "TemplateMessageSetting::CreateOrAssign",
    +            "type_name": "我创建的或负责的",
    +            "total_settings_count": 4,
    +            "settings": [
    +                {
    +                    "name": "易修状态变更",
    +                    "key": "IssueChanged",
    +                    "openning": true,
    +                    "notification_disabled": true,
    +                    "email_disabled": false
    +                },
    +                {
    +                    "name": "易修被指派",
    +                    "key": "IssueAssigned",
    +                    "openning": true,
    +                    "notification_disabled": true,
    +                    "email_disabled": false
    +                },
    +                {
    +                    "name": "合并请求被指派",
    +                    "key": "PullRequestAssigned",
    +                    "openning": true,
    +                    "notification_disabled": true,
    +                    "email_disabled": false
    +                },
    +                {
    +                    "name": "合并请求状态变更",
    +                    "key": "PullRequestAssigned",
    +                    "openning": true,
    +                    "notification_disabled": true,
    +                    "email_disabled": false
    +                }
    +            ]
    +        },
    +        {
    +            "type": "TemplateMessageSetting::ManageProject",
    +            "type_name": "我管理的仓库",
    +            "total_settings_count": 4,
    +            "settings": [
    +                {
    +                    "name": "有新的易修",
    +                    "key": "ProjectIssue",
    +                    "openning": true,
    +                    "notification_disabled": true,
    +                    "email_disabled": false
    +                },
    +                {
    +                    "name": "有新的合并请求",
    +                    "key": "ProjectPullRequest",
    +                    "openning": true,
    +                    "notification_disabled": true,
    +                    "email_disabled": false
    +                },
    +                {
    +                    "name": "有成员变动",
    +                    "key": "ProjectMember",
    +                    "openning": true,
    +                    "notification_disabled": true,
    +                    "email_disabled": false
    +                },
    +                {
    +                    "name": "设置更改",
    +                    "key": "ProjectSettingChanged",
    +                    "openning": true,
    +                    "notification_disabled": true,
    +                    "email_disabled": false
    +                }
    +            ]
    +        },
    +        {
    +            "type": "TemplateMessageSetting::Normal",
    +            "type_name": "",
    +            "total_settings_count": 3,
    +            "settings": [
    +                {
    +                    "name": "被拉入或移出组织",
    +                    "key": "Organization",
    +                    "openning": true,
    +                    "notification_disabled": true,
    +                    "email_disabled": false
    +                },
    +                {
    +                    "name": "被拉入或移出项目",
    +                    "key": "Project",
    +                    "openning": true,
    +                    "notification_disabled": true,
    +                    "email_disabled": false
    +                },
    +                {
    +                    "name": "有权限变更",
    +                    "key": "Permission",
    +                    "openning": true,
    +                    "notification_disabled": true,
    +                    "email_disabled": false
    +                }
    +            ]
    +        }
    +    ]
    +}
    +
    + +

    获取用户星标项目

    获取用户星标项目

    @@ -1577,9 +1746,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/is_pinned_projects.json
     
    await octokit.request('GET /api/users/:login/is_pinned_projects.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET api/users/:login/is_pinned_projects.json

    -

    返回字段说明:

    +

    返回字段说明:

    @@ -1764,7 +1933,7 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/is_pinned_projects/pin.json
     
    await octokit.request('GET /api/users/:login/is_pinned_projects/pin.json')
    -

    HTTP 请求

    +

    HTTP 请求

    POST /api/users/:login/is_pinned_projects/pin.json

    请求字段说明:

    同时设定多个星标项目

    参数
    @@ -1810,7 +1979,7 @@ Success — a happy kitten is an authenticated kitten!
    curl -X PATCH http://localhost:3000/api/users/yystopf/is_pinned_projects/11.json
     
    await octokit.request('PATCH/PUT /api/users/:login/is_pinned_projects/:id.json')
    -

    HTTP 请求

    +

    HTTP 请求

    PATCH/PUT /api/users/:login/is_pinned_projects/:id.json

    请求字段说明:

    @@ -1851,9 +2020,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/activity.json
     
    await octokit.request('GET /api/users/:login/statistics/activity.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/activity.json

    -

    返回字段说明:

    +

    返回字段说明:

    @@ -1940,7 +2109,7 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/headmaps.json
     
    await octokit.request('GET /api/users/:login/headmaps.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET api/users/:login/headmaps.json

    请求字段说明:

    参数
    @@ -1956,7 +2125,7 @@ Success — a happy kitten is an authenticated kitten!
    年份
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -2085,7 +2254,7 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/project_trends.json
     
    await octokit.request('GET /api/users/:login/project_trends.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET api/users/:login/project_trends.json

    请求字段说明:

    参数
    @@ -2101,7 +2270,7 @@ Success — a happy kitten is an authenticated kitten!
    日期,格式: 2021-05-28
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -2402,7 +2571,7 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/develop.json
     
    await octokit.request('GET /api/users/:login/statistics/develop.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/develop.json

    请求字段说明:

    参数
    @@ -2423,7 +2592,7 @@ Success — a happy kitten is an authenticated kitten!
    时间戳,结束时间,格式:1622131200
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -2545,7 +2714,7 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/role.json
     
    await octokit.request('GET /api/users/:login/statistics/role.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/role.json

    请求字段说明:

    参数
    @@ -2566,7 +2735,7 @@ Success — a happy kitten is an authenticated kitten!
    时间戳,结束时间,格式:1622131200
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -2627,7 +2796,7 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/major.json
     
    await octokit.request('GET /api/users/:login/statistics/major.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/major.json

    请求字段说明:

    参数
    @@ -2648,7 +2817,7 @@ Success — a happy kitten is an authenticated kitten!
    时间戳,结束时间,格式:1622131200
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -2688,7 +2857,7 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/applied_messages.json
     
    await octokit.request('GET /api/users/:login/applied_messages.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_messages.json

    请求字段说明:

    参数
    @@ -2704,7 +2873,7 @@ Success — a happy kitten is an authenticated kitten!
    用户标识
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -2967,7 +3136,7 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/applied_transfer_projects.json
     
    await octokit.request('GET /api/users/:login/applied_transfer_projects.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_transfer_projects.json

    请求字段说明:

    参数
    @@ -2983,7 +3152,7 @@ Success — a happy kitten is an authenticated kitten!
    用户标识
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -3159,7 +3328,7 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/applied_transfer_projects/2/accept.json
     
    await octokit.request('GET /api/users/:login/applied_transfer_projects/:id/accept.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_transfer_projects/:id/accept.json

    请求字段说明:

    参数
    @@ -3180,197 +3349,6 @@ Success — a happy kitten is an authenticated kitten!
    迁移id
    -

    返回字段说明:

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    参数类型字段说明
    idint迁移id
    statusstring迁移状态,canceled:取消,common:正在迁移, accept:已接受,refuse:已拒绝
    time_agostring迁移创建的时间
    project.idint迁移项目的id
    project.identifierstring迁移项目的标识
    project.namestring迁移项目的名称
    project.descriptionstring迁移项目的描述
    project.is_publicbool迁移项目是否公开
    project.owner.idbool迁移项目拥有者id
    project.owner.typestring迁移项目拥有者类型
    project.owner.namestring迁移项目拥有者昵称
    project.owner.loginstring迁移项目拥有者标识
    project.owner.image_urlstring迁移项目拥有者头像
    user.idint迁移创建者的id
    user.typestring迁移创建者的类型
    user.namestring迁移创建者的名称
    user.loginstring迁移创建者的标识
    user.image_urlstring迁移创建者头像
    owner.idint迁移接受者的id
    owner.typestring迁移接受者的类型
    owner.namestring迁移接受者的名称
    owner.loginstring迁移接受者的标识
    owner.image_urlstring迁移接受者头像
    - -
    -

    返回的JSON示例:

    -
    -
    {
    -    "project": {
    -        "id": 86,
    -        "identifier": "ceshi_repo1",
    -        "name": "测试项目啊1",
    -        "description": "二十多",
    -        "is_public": true,
    -        "owner": {
    -            "id": 52,
    -            "type": "Organization",
    -            "name": "身份卡手动阀",
    -            "login": "ceshi1",
    -            "image_url": "images/avatars/Organization/52?t=1618805056"
    -        }
    -    },
    -    "user": {
    -        "id": 6,
    -        "type": "User",
    -        "name": "yystopf",
    -        "login": "yystopf",
    -        "image_url": "system/lets/letter_avatars/2/Y/241_125_89/120.png"
    -    },
    -    "owner": {
    -        "id": 52,
    -        "type": "Organization",
    -        "name": "身份卡手动阀",
    -        "login": "ceshi1",
    -        "image_url": "images/avatars/Organization/52?t=1618805056"
    -    },
    -    "id": 1,
    -    "status": "canceled",
    -    "created_at": "2021-04-25 18:06",
    -    "time_ago": "16小时前"
    -}
    -

    用户拒绝迁移

    -

    用户拒绝迁移

    - -
    -

    示例:

    -
    -
    curl -X POST http://localhost:3000/api/users/yystopf/applied_transfer_projects/2/refuse.json
    -
    await octokit.request('GET /api/users/:login/applied_transfer_projects/:id/refuse.json')
    -

    HTTP 请求

    -

    GET /api/users/:login/applied_transfer_projects/:id/refuse.json

    -

    请求字段说明:

    - - - - - - - - - - - - - - - - - -
    参数类型字段说明
    loginstring用户标识
    idint迁移id

    返回字段说明:

    @@ -3496,6 +3474,197 @@ Success — a happy kitten is an authenticated kitten!
    +
    +

    返回的JSON示例:

    +
    +
    {
    +    "project": {
    +        "id": 86,
    +        "identifier": "ceshi_repo1",
    +        "name": "测试项目啊1",
    +        "description": "二十多",
    +        "is_public": true,
    +        "owner": {
    +            "id": 52,
    +            "type": "Organization",
    +            "name": "身份卡手动阀",
    +            "login": "ceshi1",
    +            "image_url": "images/avatars/Organization/52?t=1618805056"
    +        }
    +    },
    +    "user": {
    +        "id": 6,
    +        "type": "User",
    +        "name": "yystopf",
    +        "login": "yystopf",
    +        "image_url": "system/lets/letter_avatars/2/Y/241_125_89/120.png"
    +    },
    +    "owner": {
    +        "id": 52,
    +        "type": "Organization",
    +        "name": "身份卡手动阀",
    +        "login": "ceshi1",
    +        "image_url": "images/avatars/Organization/52?t=1618805056"
    +    },
    +    "id": 1,
    +    "status": "canceled",
    +    "created_at": "2021-04-25 18:06",
    +    "time_ago": "16小时前"
    +}
    +

    用户拒绝迁移

    +

    用户拒绝迁移

    + +
    +

    示例:

    +
    +
    curl -X POST http://localhost:3000/api/users/yystopf/applied_transfer_projects/2/refuse.json
    +
    await octokit.request('GET /api/users/:login/applied_transfer_projects/:id/refuse.json')
    +

    HTTP 请求

    +

    GET /api/users/:login/applied_transfer_projects/:id/refuse.json

    +

    请求字段说明:

    + + + + + + + + + + + + + + + + + +
    参数类型字段说明
    loginstring用户标识
    idint迁移id
    +

    返回字段说明:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    参数类型字段说明
    idint迁移id
    statusstring迁移状态,canceled:取消,common:正在迁移, accept:已接受,refuse:已拒绝
    time_agostring迁移创建的时间
    project.idint迁移项目的id
    project.identifierstring迁移项目的标识
    project.namestring迁移项目的名称
    project.descriptionstring迁移项目的描述
    project.is_publicbool迁移项目是否公开
    project.owner.idbool迁移项目拥有者id
    project.owner.typestring迁移项目拥有者类型
    project.owner.namestring迁移项目拥有者昵称
    project.owner.loginstring迁移项目拥有者标识
    project.owner.image_urlstring迁移项目拥有者头像
    user.idint迁移创建者的id
    user.typestring迁移创建者的类型
    user.namestring迁移创建者的名称
    user.loginstring迁移创建者的标识
    user.image_urlstring迁移创建者头像
    owner.idint迁移接受者的id
    owner.typestring迁移接受者的类型
    owner.namestring迁移接受者的名称
    owner.loginstring迁移接受者的标识
    owner.image_urlstring迁移接受者头像
    +

    返回的JSON示例:

    @@ -3541,7 +3710,7 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/applied_projects.json
     
    await octokit.request('GET /api/users/:login/applied_projects.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_projects.json

    请求字段说明:

    @@ -3557,7 +3726,7 @@ Success — a happy kitten is an authenticated kitten!
    用户标识
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -3701,7 +3870,7 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/applied_projects/2/accept.json
     
    await octokit.request('GET /api/users/:login/applied_projects/:id/accept.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_projects/:id/accept.json

    请求字段说明:

    参数
    @@ -3722,7 +3891,7 @@ Success — a happy kitten is an authenticated kitten!
    申请id
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -3860,7 +4029,7 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/applied_projects/2/refuse.json
     
    await octokit.request('GET /api/users/:login/applied_projects/:id/refuse.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_projects/:id/refuse.json

    请求字段说明:

    参数
    @@ -3881,7 +4050,7 @@ Success — a happy kitten is an authenticated kitten!
    申请id
    -

    返回字段说明:

    +

    返回字段说明:

    From dbdd2e2dd3b7ac3f0c7681f92dcd289c11810d4b Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 18 Oct 2021 11:54:42 +0800 Subject: [PATCH 122/135] add: user template message setting --- .../template_message_settings_controller.rb | 36 ++ app/docs/slate/source/includes/_users.md | 248 ++++++++++-- .../create_or_assign.rb | 4 +- .../manage_project.rb | 8 +- app/models/user.rb | 4 +- app/models/user_template_message_setting.rb | 54 +++ .../index.json.jbuilder | 2 +- .../_detail.json.jbuilder | 5 + .../current_setting.json.jbuilder | 2 + .../update_setting.json.jbuilder | 2 + config/routes.rb | 2 + public/docs/api.html | 364 ++++++++++++++---- 12 files changed, 599 insertions(+), 132 deletions(-) create mode 100644 app/controllers/users/template_message_settings_controller.rb create mode 100644 app/views/users/template_message_settings/_detail.json.jbuilder create mode 100644 app/views/users/template_message_settings/current_setting.json.jbuilder create mode 100644 app/views/users/template_message_settings/update_setting.json.jbuilder diff --git a/app/controllers/users/template_message_settings_controller.rb b/app/controllers/users/template_message_settings_controller.rb new file mode 100644 index 00000000..2234e730 --- /dev/null +++ b/app/controllers/users/template_message_settings_controller.rb @@ -0,0 +1,36 @@ +class Users::TemplateMessageSettingsController < Users::BaseController + before_action :check_auth + before_action :get_current_setting + + def current_setting + + end + + def update_setting + Rails.logger.info setting_params[:notification_body] + Rails.logger.info setting_params[:email_body] + + @current_setting.notification_body = setting_params[:notification_body].to_hash + @current_setting.email_body = setting_params[:email_body].to_hash + return render_error("保存失败") unless @current_setting.save! + end + + private + def check_auth + return render_forbidden unless current_user.admin? || observed_logged_user? + end + + def get_current_setting + @current_setting = @_observed_user.user_template_message_setting + @current_setting = UserTemplateMessageSetting.build(@_observed_user.id) if @current_setting.nil? + end + + def setting_params + params.require(:setting).permit(notification_body: {}, email_body: {}) + end + + def valid_setting_params + setting_params[:notification_body].keys.equal?(UserTemplateMessageSetting.init_notification_body.keys) && setting_params[:email_body].keys.equal?(UserTemplateMessageSetting.init_email_body) + end + +end \ No newline at end of file diff --git a/app/docs/slate/source/includes/_users.md b/app/docs/slate/source/includes/_users.md index d0251602..4df28755 100644 --- a/app/docs/slate/source/includes/_users.md +++ b/app/docs/slate/source/includes/_users.md @@ -408,6 +408,31 @@ await octokit.request('GET /api/template_message_settings.json') "status": 0, "message": "响应成功", "setting_types": [ + { + "type": "TemplateMessageSetting::Normal", + "type_name": "", + "total_settings_count": 3, + "settings": [ + { + "name": "被拉入或移出组织", + "key": "Organization", + "notification_disabled": true, + "email_disabled": false + }, + { + "name": "被拉入或移出项目", + "key": "Project", + "notification_disabled": true, + "email_disabled": false + }, + { + "name": "有权限变更", + "key": "Permission", + "notification_disabled": true, + "email_disabled": false + } + ] + }, { "type": "TemplateMessageSetting::CreateOrAssign", "type_name": "我创建的或负责的", @@ -416,28 +441,24 @@ await octokit.request('GET /api/template_message_settings.json') { "name": "易修状态变更", "key": "IssueChanged", - "openning": true, "notification_disabled": true, "email_disabled": false }, { "name": "易修被指派", "key": "IssueAssigned", - "openning": true, "notification_disabled": true, "email_disabled": false }, { "name": "合并请求被指派", "key": "PullRequestAssigned", - "openning": true, "notification_disabled": true, "email_disabled": false }, { "name": "合并请求状态变更", "key": "PullRequestAssigned", - "openning": true, "notification_disabled": true, "email_disabled": false } @@ -450,57 +471,25 @@ await octokit.request('GET /api/template_message_settings.json') "settings": [ { "name": "有新的易修", - "key": "ProjectIssue", - "openning": true, + "key": "Issue", "notification_disabled": true, "email_disabled": false }, { "name": "有新的合并请求", - "key": "ProjectPullRequest", - "openning": true, + "key": "PullRequest", "notification_disabled": true, "email_disabled": false }, { "name": "有成员变动", - "key": "ProjectMember", - "openning": true, + "key": "Member", "notification_disabled": true, "email_disabled": false }, { "name": "设置更改", - "key": "ProjectSettingChanged", - "openning": true, - "notification_disabled": true, - "email_disabled": false - } - ] - }, - { - "type": "TemplateMessageSetting::Normal", - "type_name": "", - "total_settings_count": 3, - "settings": [ - { - "name": "被拉入或移出组织", - "key": "Organization", - "openning": true, - "notification_disabled": true, - "email_disabled": false - }, - { - "name": "被拉入或移出项目", - "key": "Project", - "openning": true, - "notification_disabled": true, - "email_disabled": false - }, - { - "name": "有权限变更", - "key": "Permission", - "openning": true, + "key": "SettingChanged", "notification_disabled": true, "email_disabled": false } @@ -512,6 +501,185 @@ await octokit.request('GET /api/template_message_settings.json') + +## 获取用户消息设置配置信息 +获取用户消息设置配置信息 + +> 示例: + +```shell +curl -X GET http://localhost:3000/api/users/yystopf/template_message_settings.json +``` + +```javascript +await octokit.request('GET /api/uses/yystopf/template_message_settings.json') +``` + +### HTTP 请求 +`GET /api/users/:user_id/template_message_settings.json` + +### 返回字段说明: +参数 | 类型 | 字段说明 +--------- | ----------- | ----------- +|notification_body |string |站内信配置 | +|email_body |string |邮件配置| + + +> 返回的JSON示例: + +```json +{ + "status": 0, + "message": "响应成功", + "user": { + "id": 2, + "type": "User", + "name": "heh", + "login": "yystopf", + "image_url": "system/lets/letter_avatars/2/H/188_239_142/120.png" + }, + "notification_body": { + "CreateOrAssign::IssueChanged": true, + "CreateOrAssign::IssueAssigned": true, + "CreateOrAssign::PullRequestAssigned": true, + "CreateOrAssign::PullRequestChanged": true, + "ManageProject::Issue": true, + "ManageProject::PullRequest": true, + "ManageProject::Member": true, + "ManageProject::SettingChanged": true, + "Normal::Organization": true, + "Normal::Project": true, + "Normal::Permission": true + }, + "email_body": { + "CreateOrAssign::IssueChanged": false, + "CreateOrAssign::IssueAssigned": false, + "CreateOrAssign::PullRequestAssigned": false, + "CreateOrAssign::PullRequestChanged": false, + "ManageProject::Issue": false, + "ManageProject::PullRequest": false, + "ManageProject::Member": false, + "ManageProject::SettingChanged": true, + "Normal::Organization": false, + "Normal::Project": true, + "Normal::Permission": false + } +} +``` + + +## 重新设置用户消息设置配置信息 +重新设置用户消息设置配置信息 + +> 示例: + +```shell +curl -X POST http://localhost:3000/api/users/yystopf/template_message_settings/update_setting.json +``` + +```javascript +await octokit.request('POST /api/uses/yystopf/template_message_settings/update_setting.json') +``` + +### HTTP 请求 +`POST /api/users/:user_id/template_message_settings/update_setting.json` + +### 请求字段说明: +参数 | 类型 | 字段说明 +--------- | ----------- | ----------- +|notification_body |string |站内信配置 | +|email_body |string |邮件配置| + + +> 请求的JSON示例: + +```json +{ + "setting": { + "notification_body": { + "CreateOrAssign::IssueChanged": true, + "CreateOrAssign::IssueAssigned": true, + "CreateOrAssign::PullRequestAssigned": true, + "CreateOrAssign::PullRequestChanged": true, + "ManageProject::Issue": true, + "ManageProject::PullRequest": true, + "ManageProject::Member": true, + "ManageProject::SettingChanged": true, + "Normal::Organization": true, + "Normal::Project": true, + "Normal::Permission": true + }, + "email_body": { + "CreateOrAssign::IssueChanged": false, + "CreateOrAssign::IssueAssigned": false, + "CreateOrAssign::PullRequestAssigned": false, + "CreateOrAssign::PullRequestChanged": false, + "ManageProject::Issue": false, + "ManageProject::PullRequest": false, + "ManageProject::Member": false, + "ManageProject::SettingChanged": true, + "Normal::Organization": false, + "Normal::Project": "t", + "Normal::Permission": false + } + } +} +``` + +### 返回字段说明: +参数 | 类型 | 字段说明 +--------- | ----------- | ----------- +|notification_body |string |站内信配置 | +|email_body |string |邮件配置| + + +> 返回的JSON示例: + +```json +{ + "status": 0, + "message": "响应成功", + "user": { + "id": 2, + "type": "User", + "name": "heh", + "login": "yystopf", + "image_url": "system/lets/letter_avatars/2/H/188_239_142/120.png" + }, + "notification_body": { + "CreateOrAssign::IssueChanged": true, + "CreateOrAssign::IssueAssigned": true, + "CreateOrAssign::PullRequestAssigned": true, + "CreateOrAssign::PullRequestChanged": true, + "ManageProject::Issue": true, + "ManageProject::PullRequest": true, + "ManageProject::Member": true, + "ManageProject::SettingChanged": true, + "Normal::Organization": true, + "Normal::Project": true, + "Normal::Permission": true + }, + "email_body": { + "CreateOrAssign::IssueChanged": false, + "CreateOrAssign::IssueAssigned": false, + "CreateOrAssign::PullRequestAssigned": false, + "CreateOrAssign::PullRequestChanged": false, + "ManageProject::Issue": false, + "ManageProject::PullRequest": false, + "ManageProject::Member": false, + "ManageProject::SettingChanged": true, + "Normal::Organization": false, + "Normal::Project": true, + "Normal::Permission": false + } +} +``` + + ## 获取用户星标项目 获取用户星标项目 diff --git a/app/models/template_message_setting/create_or_assign.rb b/app/models/template_message_setting/create_or_assign.rb index df98a5ca..65bf2642 100644 --- a/app/models/template_message_setting/create_or_assign.rb +++ b/app/models/template_message_setting/create_or_assign.rb @@ -21,9 +21,9 @@ class TemplateMessageSetting::CreateOrAssign < TemplateMessageSetting end def self.build_init_data - self.find_or_create_by(name: "易修状态变更", key: "IssueChanged") self.find_or_create_by(name: "易修被指派", key: "IssueAssigned") + self.find_or_create_by(name: "易修状态变更", key: "IssueChanged") self.find_or_create_by(name: "合并请求被指派", key: "PullRequestAssigned") - self.find_or_create_by(name: "合并请求状态变更", key: "PullRequestAssigned") + self.find_or_create_by(name: "合并请求状态变更", key: "PullRequestChanged") end end diff --git a/app/models/template_message_setting/manage_project.rb b/app/models/template_message_setting/manage_project.rb index b0f535ea..b1e69a5a 100644 --- a/app/models/template_message_setting/manage_project.rb +++ b/app/models/template_message_setting/manage_project.rb @@ -21,9 +21,9 @@ class TemplateMessageSetting::ManageProject < TemplateMessageSetting end def self.build_init_data - self.find_or_create_by(name: "有新的易修", key: "ProjectIssue") - self.find_or_create_by(name: "有新的合并请求", key: "ProjectPullRequest") - self.find_or_create_by(name: "有成员变动", key: "ProjectMember") - self.find_or_create_by(name: "设置更改", key: "ProjectSettingChanged") + self.find_or_create_by(name: "有新的易修", key: "Issue") + self.find_or_create_by(name: "有新的合并请求", key: "PullRequest") + self.find_or_create_by(name: "有成员变动", key: "Member") + self.find_or_create_by(name: "设置更改", key: "SettingChanged") end end diff --git a/app/models/user.rb b/app/models/user.rb index 623694b3..fc4c3361 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -170,7 +170,9 @@ class User < Owner has_many :issues, dependent: :destroy, foreign_key: :author_id has_many :pull_requests, dependent: :destroy has_many :public_keys, class_name: "Gitea::PublicKey",primary_key: :gitea_uid, foreign_key: :owner_id, dependent: :destroy - + + has_one :user_template_message_setting, dependent: :destroy + # Groups and active users scope :active, lambda { where(status: STATUS_ACTIVE) } scope :like, lambda { |keywords| diff --git a/app/models/user_template_message_setting.rb b/app/models/user_template_message_setting.rb index 5c6f3a2f..5992adbb 100644 --- a/app/models/user_template_message_setting.rb +++ b/app/models/user_template_message_setting.rb @@ -15,4 +15,58 @@ # class UserTemplateMessageSetting < ApplicationRecord + serialize :notification_body, Hash + serialize :email_body, Hash + + belongs_to :user + + before_update :set_body_value + + def self.build(user_id) + self.create!(user_id: user_id, notification_body: init_notification_body, email_body: init_email_body) + end + + def self.init_notification_body + { + "CreateOrAssign::IssueChanged": true, + "CreateOrAssign::IssueAssigned": true, + "CreateOrAssign::PullRequestAssigned": true, + "CreateOrAssign::PullRequestChanged": true, + "ManageProject::Issue": true, + "ManageProject::PullRequest": true, + "ManageProject::Member": true, + "ManageProject::SettingChanged": true, + "Normal::Organization": true, + "Normal::Project": true, + "Normal::Permission": true, + }.stringify_keys! + end + + def self.init_email_body + { + "CreateOrAssign::IssueChanged": false, + "CreateOrAssign::IssueAssigned": false, + "CreateOrAssign::PullRequestAssigned": false, + "CreateOrAssign::PullRequestChanged": false, + "ManageProject::Issue": false, + "ManageProject::PullRequest": false, + "ManageProject::Member": false, + "ManageProject::SettingChanged": false, + "Normal::Organization": false, + "Normal::Project": false, + "Normal::Permission": false, + }.stringify_keys! + end + + private + + def set_body_value + self.notification_body.each do |k, v| + self.notification_body[k] = ActiveModel::Type::Boolean.new.cast(v).nil? ? false : ActiveModel::Type::Boolean.new.cast(v) + end + + self.email_body.each do |k, v| + self.email_body[k] = ActiveModel::Type::Boolean.new.cast(v).nil? ? false : ActiveModel::Type::Boolean.new.cast(v) + end + end end diff --git a/app/views/template_message_settings/index.json.jbuilder b/app/views/template_message_settings/index.json.jbuilder index 3ca13679..eae5bb01 100644 --- a/app/views/template_message_settings/index.json.jbuilder +++ b/app/views/template_message_settings/index.json.jbuilder @@ -1,7 +1,7 @@ json.partial! "commons/success" json.setting_types do - json.array! @group_settings.keys.each do |k| + json.array! @group_settings.keys.sort_by{|i| i.constantize.type_name}.each do |k| json.partial! "detail", type: k, count: @group_settings[k] end diff --git a/app/views/users/template_message_settings/_detail.json.jbuilder b/app/views/users/template_message_settings/_detail.json.jbuilder new file mode 100644 index 00000000..18a3e31e --- /dev/null +++ b/app/views/users/template_message_settings/_detail.json.jbuilder @@ -0,0 +1,5 @@ +json.user do + json.partial! 'users/user_simple', locals: { user: setting.user } +end +json.notification_body setting.notification_body +json.email_body setting.email_body \ No newline at end of file diff --git a/app/views/users/template_message_settings/current_setting.json.jbuilder b/app/views/users/template_message_settings/current_setting.json.jbuilder new file mode 100644 index 00000000..514aadb7 --- /dev/null +++ b/app/views/users/template_message_settings/current_setting.json.jbuilder @@ -0,0 +1,2 @@ +json.partial! "commons/success" +json.partial! "detail", locals: {setting: @current_setting} \ No newline at end of file diff --git a/app/views/users/template_message_settings/update_setting.json.jbuilder b/app/views/users/template_message_settings/update_setting.json.jbuilder new file mode 100644 index 00000000..514aadb7 --- /dev/null +++ b/app/views/users/template_message_settings/update_setting.json.jbuilder @@ -0,0 +1,2 @@ +json.partial! "commons/success" +json.partial! "detail", locals: {setting: @current_setting} \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index 34fa0ed6..35fea39c 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -265,6 +265,8 @@ Rails.application.routes.draw do end scope module: :users do + get 'template_message_settings', to: 'template_message_settings#current_setting' + post 'template_message_settings/update_setting', to: 'template_message_settings#update_setting' resources :applied_messages, only: [:index] resources :applied_transfer_projects, only: [:index] do member do diff --git a/public/docs/api.html b/public/docs/api.html index ecfdb055..e2a64202 100644 --- a/public/docs/api.html +++ b/public/docs/api.html @@ -363,6 +363,12 @@
  • 获取平台消息设置配置信息
  • +
  • + 获取用户消息设置配置信息 +
  • +
  • + 重新设置用户消息设置配置信息 +
  • 获取用户星标项目
  • @@ -1634,6 +1640,31 @@ Success — a happy kitten is an authenticated kitten! "status": 0, "message": "响应成功", "setting_types": [ + { + "type": "TemplateMessageSetting::Normal", + "type_name": "", + "total_settings_count": 3, + "settings": [ + { + "name": "被拉入或移出组织", + "key": "Organization", + "notification_disabled": true, + "email_disabled": false + }, + { + "name": "被拉入或移出项目", + "key": "Project", + "notification_disabled": true, + "email_disabled": false + }, + { + "name": "有权限变更", + "key": "Permission", + "notification_disabled": true, + "email_disabled": false + } + ] + }, { "type": "TemplateMessageSetting::CreateOrAssign", "type_name": "我创建的或负责的", @@ -1642,28 +1673,24 @@ Success — a happy kitten is an authenticated kitten! { "name": "易修状态变更", "key": "IssueChanged", - "openning": true, "notification_disabled": true, "email_disabled": false }, { "name": "易修被指派", "key": "IssueAssigned", - "openning": true, "notification_disabled": true, "email_disabled": false }, { "name": "合并请求被指派", "key": "PullRequestAssigned", - "openning": true, "notification_disabled": true, "email_disabled": false }, { "name": "合并请求状态变更", "key": "PullRequestAssigned", - "openning": true, "notification_disabled": true, "email_disabled": false } @@ -1676,57 +1703,25 @@ Success — a happy kitten is an authenticated kitten! "settings": [ { "name": "有新的易修", - "key": "ProjectIssue", - "openning": true, + "key": "Issue", "notification_disabled": true, "email_disabled": false }, { "name": "有新的合并请求", - "key": "ProjectPullRequest", - "openning": true, + "key": "PullRequest", "notification_disabled": true, "email_disabled": false }, { "name": "有成员变动", - "key": "ProjectMember", - "openning": true, + "key": "Member", "notification_disabled": true, "email_disabled": false }, { "name": "设置更改", - "key": "ProjectSettingChanged", - "openning": true, - "notification_disabled": true, - "email_disabled": false - } - ] - }, - { - "type": "TemplateMessageSetting::Normal", - "type_name": "", - "total_settings_count": 3, - "settings": [ - { - "name": "被拉入或移出组织", - "key": "Organization", - "openning": true, - "notification_disabled": true, - "email_disabled": false - }, - { - "name": "被拉入或移出项目", - "key": "Project", - "openning": true, - "notification_disabled": true, - "email_disabled": false - }, - { - "name": "有权限变更", - "key": "Permission", - "openning": true, + "key": "SettingChanged", "notification_disabled": true, "email_disabled": false } @@ -1738,6 +1733,207 @@ Success — a happy kitten is an authenticated kitten! +

    获取用户消息设置配置信息

    +

    获取用户消息设置配置信息

    + +
    +

    示例:

    +
    +
    curl -X GET http://localhost:3000/api/users/yystopf/template_message_settings.json
    +
    await octokit.request('GET /api/uses/yystopf/template_message_settings.json')
    +

    HTTP 请求

    +

    GET /api/users/:user_id/template_message_settings.json

    +

    返回字段说明:

    +
    参数
    + + + + + + + + + + + + + + + + +
    参数类型字段说明
    notification_bodystring站内信配置
    email_bodystring邮件配置
    + +
    +

    返回的JSON示例:

    +
    +
    {
    +    "status": 0,
    +    "message": "响应成功",
    +    "user": {
    +        "id": 2,
    +        "type": "User",
    +        "name": "heh",
    +        "login": "yystopf",
    +        "image_url": "system/lets/letter_avatars/2/H/188_239_142/120.png"
    +    },
    +    "notification_body": {
    +        "CreateOrAssign::IssueChanged": true,
    +        "CreateOrAssign::IssueAssigned": true,
    +        "CreateOrAssign::PullRequestAssigned": true,
    +        "CreateOrAssign::PullRequestChanged": true,
    +        "ManageProject::Issue": true,
    +        "ManageProject::PullRequest": true,
    +        "ManageProject::Member": true,
    +        "ManageProject::SettingChanged": true,
    +        "Normal::Organization": true,
    +        "Normal::Project": true,
    +        "Normal::Permission": true
    +    },
    +    "email_body": {
    +        "CreateOrAssign::IssueChanged": false,
    +        "CreateOrAssign::IssueAssigned": false,
    +        "CreateOrAssign::PullRequestAssigned": false,
    +        "CreateOrAssign::PullRequestChanged": false,
    +        "ManageProject::Issue": false,
    +        "ManageProject::PullRequest": false,
    +        "ManageProject::Member": false,
    +        "ManageProject::SettingChanged": true,
    +        "Normal::Organization": false,
    +        "Normal::Project": true,
    +        "Normal::Permission": false
    +    }
    +}
    +
    + +

    重新设置用户消息设置配置信息

    +

    重新设置用户消息设置配置信息

    + +
    +

    示例:

    +
    +
    curl -X POST http://localhost:3000/api/users/yystopf/template_message_settings/update_setting.json
    +
    await octokit.request('POST /api/uses/yystopf/template_message_settings/update_setting.json')
    +

    HTTP 请求

    +

    POST /api/users/:user_id/template_message_settings/update_setting.json

    +

    请求字段说明:

    + + + + + + + + + + + + + + + + + +
    参数类型字段说明
    notification_bodystring站内信配置
    email_bodystring邮件配置
    + +
    +

    请求的JSON示例:

    +
    +
    {
    +    "setting": {
    +        "notification_body": {
    +            "CreateOrAssign::IssueChanged": true,
    +            "CreateOrAssign::IssueAssigned": true,
    +            "CreateOrAssign::PullRequestAssigned": true,
    +            "CreateOrAssign::PullRequestChanged": true,
    +            "ManageProject::Issue": true,
    +            "ManageProject::PullRequest": true,
    +            "ManageProject::Member": true,
    +            "ManageProject::SettingChanged": true,
    +            "Normal::Organization": true,
    +            "Normal::Project": true,
    +            "Normal::Permission": true
    +        },
    +        "email_body": {
    +            "CreateOrAssign::IssueChanged": false,
    +            "CreateOrAssign::IssueAssigned": false,
    +            "CreateOrAssign::PullRequestAssigned": false,
    +            "CreateOrAssign::PullRequestChanged": false,
    +            "ManageProject::Issue": false,
    +            "ManageProject::PullRequest": false,
    +            "ManageProject::Member": false,
    +            "ManageProject::SettingChanged": true,
    +            "Normal::Organization": false,
    +            "Normal::Project": "t",
    +            "Normal::Permission": false
    +        }
    +   }
    +}
    +

    返回字段说明:

    + + + + + + + + + + + + + + + + + +
    参数类型字段说明
    notification_bodystring站内信配置
    email_bodystring邮件配置
    + +
    +

    返回的JSON示例:

    +
    +
    {
    +    "status": 0,
    +    "message": "响应成功",
    +    "user": {
    +        "id": 2,
    +        "type": "User",
    +        "name": "heh",
    +        "login": "yystopf",
    +        "image_url": "system/lets/letter_avatars/2/H/188_239_142/120.png"
    +    },
    +    "notification_body": {
    +        "CreateOrAssign::IssueChanged": true,
    +        "CreateOrAssign::IssueAssigned": true,
    +        "CreateOrAssign::PullRequestAssigned": true,
    +        "CreateOrAssign::PullRequestChanged": true,
    +        "ManageProject::Issue": true,
    +        "ManageProject::PullRequest": true,
    +        "ManageProject::Member": true,
    +        "ManageProject::SettingChanged": true,
    +        "Normal::Organization": true,
    +        "Normal::Project": true,
    +        "Normal::Permission": true
    +    },
    +    "email_body": {
    +        "CreateOrAssign::IssueChanged": false,
    +        "CreateOrAssign::IssueAssigned": false,
    +        "CreateOrAssign::PullRequestAssigned": false,
    +        "CreateOrAssign::PullRequestChanged": false,
    +        "ManageProject::Issue": false,
    +        "ManageProject::PullRequest": false,
    +        "ManageProject::Member": false,
    +        "ManageProject::SettingChanged": true,
    +        "Normal::Organization": false,
    +        "Normal::Project": true,
    +        "Normal::Permission": false
    +    }
    +}
    +
    +

    获取用户星标项目

    获取用户星标项目

    @@ -1746,9 +1942,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/is_pinned_projects.json
     
    await octokit.request('GET /api/users/:login/is_pinned_projects.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET api/users/:login/is_pinned_projects.json

    -

    返回字段说明:

    +

    返回字段说明:

    @@ -1933,9 +2129,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/is_pinned_projects/pin.json
     
    await octokit.request('GET /api/users/:login/is_pinned_projects/pin.json')
    -

    HTTP 请求

    +

    HTTP 请求

    POST /api/users/:login/is_pinned_projects/pin.json

    -

    请求字段说明:

    同时设定多个星标项目

    +

    请求字段说明:

    同时设定多个星标项目

    参数
    @@ -1979,9 +2175,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X PATCH http://localhost:3000/api/users/yystopf/is_pinned_projects/11.json
     
    await octokit.request('PATCH/PUT /api/users/:login/is_pinned_projects/:id.json')
    -

    HTTP 请求

    +

    HTTP 请求

    PATCH/PUT /api/users/:login/is_pinned_projects/:id.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2020,9 +2216,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/activity.json
     
    await octokit.request('GET /api/users/:login/statistics/activity.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/activity.json

    -

    返回字段说明:

    +

    返回字段说明:

    参数
    @@ -2109,9 +2305,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/headmaps.json
     
    await octokit.request('GET /api/users/:login/headmaps.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET api/users/:login/headmaps.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2125,7 +2321,7 @@ Success — a happy kitten is an authenticated kitten!
    参数年份
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -2254,9 +2450,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/project_trends.json
     
    await octokit.request('GET /api/users/:login/project_trends.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET api/users/:login/project_trends.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2270,7 +2466,7 @@ Success — a happy kitten is an authenticated kitten!
    参数日期,格式: 2021-05-28
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -2571,9 +2767,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/develop.json
     
    await octokit.request('GET /api/users/:login/statistics/develop.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/develop.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2592,7 +2788,7 @@ Success — a happy kitten is an authenticated kitten!
    参数时间戳,结束时间,格式:1622131200
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -2714,9 +2910,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/role.json
     
    await octokit.request('GET /api/users/:login/statistics/role.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/role.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2735,7 +2931,7 @@ Success — a happy kitten is an authenticated kitten!
    参数时间戳,结束时间,格式:1622131200
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -2796,9 +2992,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/statistics/major.json
     
    await octokit.request('GET /api/users/:login/statistics/major.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/statistics/major.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2817,7 +3013,7 @@ Success — a happy kitten is an authenticated kitten!
    参数时间戳,结束时间,格式:1622131200
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -2857,9 +3053,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/applied_messages.json
     
    await octokit.request('GET /api/users/:login/applied_messages.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_messages.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -2873,7 +3069,7 @@ Success — a happy kitten is an authenticated kitten!
    参数用户标识
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -3136,9 +3332,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/applied_transfer_projects.json
     
    await octokit.request('GET /api/users/:login/applied_transfer_projects.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_transfer_projects.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -3152,7 +3348,7 @@ Success — a happy kitten is an authenticated kitten!
    参数用户标识
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -3328,9 +3524,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/applied_transfer_projects/2/accept.json
     
    await octokit.request('GET /api/users/:login/applied_transfer_projects/:id/accept.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_transfer_projects/:id/accept.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -3349,7 +3545,7 @@ Success — a happy kitten is an authenticated kitten!
    参数迁移id
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -3519,9 +3715,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/applied_transfer_projects/2/refuse.json
     
    await octokit.request('GET /api/users/:login/applied_transfer_projects/:id/refuse.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_transfer_projects/:id/refuse.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -3540,7 +3736,7 @@ Success — a happy kitten is an authenticated kitten!
    参数迁移id
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -3710,9 +3906,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X GET http://localhost:3000/api/users/yystopf/applied_projects.json
     
    await octokit.request('GET /api/users/:login/applied_projects.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_projects.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -3726,7 +3922,7 @@ Success — a happy kitten is an authenticated kitten!
    参数用户标识
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -3870,9 +4066,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/applied_projects/2/accept.json
     
    await octokit.request('GET /api/users/:login/applied_projects/:id/accept.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_projects/:id/accept.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -3891,7 +4087,7 @@ Success — a happy kitten is an authenticated kitten!
    参数申请id
    -

    返回字段说明:

    +

    返回字段说明:

    @@ -4029,9 +4225,9 @@ Success — a happy kitten is an authenticated kitten!
    curl -X POST http://localhost:3000/api/users/yystopf/applied_projects/2/refuse.json
     
    await octokit.request('GET /api/users/:login/applied_projects/:id/refuse.json')
    -

    HTTP 请求

    +

    HTTP 请求

    GET /api/users/:login/applied_projects/:id/refuse.json

    -

    请求字段说明:

    +

    请求字段说明:

    参数
    @@ -4050,7 +4246,7 @@ Success — a happy kitten is an authenticated kitten!
    参数申请id
    -

    返回字段说明:

    +

    返回字段说明:

    From 88a7456300dd24c08741deb10c31d30c5576db5e Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 18 Oct 2021 15:49:06 +0800 Subject: [PATCH 123/135] add: template message control by setting --- app/models/message_template/issue_assigned.rb | 9 +++++++++ app/models/message_template/organization_joined.rb | 9 +++++++++ app/models/message_template/organization_left.rb | 9 +++++++++ app/models/message_template/organization_role.rb | 9 +++++++++ app/models/message_template/project_issue.rb | 9 +++++++++ app/models/message_template/project_joined.rb | 9 +++++++++ app/models/message_template/project_left.rb | 8 ++++++++ app/models/message_template/project_member_joined.rb | 9 +++++++++ app/models/message_template/project_member_left.rb | 9 +++++++++ app/models/message_template/project_pull_request.rb | 9 +++++++++ app/models/message_template/project_role.rb | 9 +++++++++ app/models/message_template/project_setting_changed.rb | 9 +++++++++ app/models/message_template/pull_request_assigned.rb | 9 +++++++++ app/models/template_message_setting/create_or_assign.rb | 2 -- 14 files changed, 116 insertions(+), 2 deletions(-) diff --git a/app/models/message_template/issue_assigned.rb b/app/models/message_template/issue_assigned.rb index 91daa8dc..4ed58105 100644 --- a/app/models/message_template/issue_assigned.rb +++ b/app/models/message_template/issue_assigned.rb @@ -17,6 +17,12 @@ class MessageTemplate::IssueAssigned < MessageTemplate # MessageTemplate::IssueAssigned.get_message_content(User.where(login: 'yystopf'), User.last, Issue.last) def self.get_message_content(receivers, operator, issue) + receivers.each do |receiver| + if receiver.user_template_message_setting.present? + receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["CreateOrAssign::IssueAssigned"] + end + end + return '', '', '' if receivers.blank? project = issue&.project owner = project&.owner content = sys_notice.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub('{title}', issue&.subject) @@ -28,6 +34,9 @@ class MessageTemplate::IssueAssigned < MessageTemplate end def self.get_email_message_content(receiver, operator, issue) + if receiver.user_template_message_setting.present? + return '', '', '' unless receiver.user_template_message_setting.email_body["CreateOrAssign::IssueAssigned"] + end project = issue&.project owner = project&.owner title = email_title diff --git a/app/models/message_template/organization_joined.rb b/app/models/message_template/organization_joined.rb index 9045ac42..22cfb48d 100644 --- a/app/models/message_template/organization_joined.rb +++ b/app/models/message_template/organization_joined.rb @@ -17,6 +17,12 @@ class MessageTemplate::OrganizationJoined < MessageTemplate # MessageTemplate::OrganizationJoined.get_message_content(User.where(login: 'yystopf'), Organization.last) def self.get_message_content(receivers, organization) + receivers.each do |receiver| + if receiver.user_template_message_setting.present? + receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["Normal::Organization"] + end + end + return '', '', '' if receivers.blank? content = sys_notice.gsub('{organization}', organization&.real_name) url = notification_url.gsub('{login}', organization&.name) return receivers_string(receivers), content, url @@ -26,6 +32,9 @@ class MessageTemplate::OrganizationJoined < MessageTemplate end def self.get_email_message_content(receiver, organization) + if receiver.user_template_message_setting.present? + return '', '', '' unless receiver.user_template_message_setting.email_body["Normal::Organization"] + end title = email_title title.gsub!('{organization}', organization&.real_name) content = email diff --git a/app/models/message_template/organization_left.rb b/app/models/message_template/organization_left.rb index edf8b32e..eee752f0 100644 --- a/app/models/message_template/organization_left.rb +++ b/app/models/message_template/organization_left.rb @@ -17,6 +17,12 @@ class MessageTemplate::OrganizationLeft < MessageTemplate # MessageTemplate::OrganizationLeft.get_message_content(User.where(login: 'yystopf'), Organization.last) def self.get_message_content(receivers, organization) + receivers.each do |receiver| + if receiver.user_template_message_setting.present? + receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["Normal::Organization"] + end + end + return '', '', '' if receivers.blank? content = sys_notice.gsub('{organization}', organization&.real_name) url = notification_url.gsub('{login}', organization&.name) return receivers_string(receivers), content, url @@ -26,6 +32,9 @@ class MessageTemplate::OrganizationLeft < MessageTemplate end def self.get_email_message_content(receiver, organization) + if receiver.user_template_message_setting.present? + return '', '', '' unless receiver.user_template_message_setting.email_body["Normal::Organization"] + end title = email_title title.gsub!('{organization}', organization&.real_name) content = email diff --git a/app/models/message_template/organization_role.rb b/app/models/message_template/organization_role.rb index 4bc96a63..b6024f61 100644 --- a/app/models/message_template/organization_role.rb +++ b/app/models/message_template/organization_role.rb @@ -17,6 +17,12 @@ class MessageTemplate::OrganizationRole < MessageTemplate # MessageTemplate::OrganizationRole.get_message_content(User.where(login: 'yystopf'), Organization.last, '管理员') def self.get_message_content(receivers, organization, role) + receivers.each do |receiver| + if receiver.user_template_message_setting.present? + receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["Normal::Permission"] + end + end + return '', '', '' if receivers.blank? content = sys_notice.gsub('{organization}', organization&.real_name).gsub('{role}', role) url = notification_url.gsub('{login}', organization&.login) return receivers_string(receivers), content, url @@ -26,6 +32,9 @@ class MessageTemplate::OrganizationRole < MessageTemplate end def self.get_email_message_content(receiver, organization, role) + if receiver.user_template_message_setting.present? + return '', '', '' unless receiver.user_template_message_setting.email_body["Normal::Permission"] + end title = email_title title.gsub!('{organization}', organization&.real_name) title.gsub!('{role}', role) diff --git a/app/models/message_template/project_issue.rb b/app/models/message_template/project_issue.rb index 8e319bf3..15548b21 100644 --- a/app/models/message_template/project_issue.rb +++ b/app/models/message_template/project_issue.rb @@ -17,6 +17,12 @@ class MessageTemplate::ProjectIssue < MessageTemplate # MessageTemplate::ProjectIssue.get_message_content(User.where(login: 'yystopf'), User.where(login: 'forgetest1'), User.last, Issue.last) def self.get_message_content(managers, followers, operator, issue) + managers.each do |receiver| + if receiver.user_template_message_setting.present? + managers = managers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["ManageProject::Issue"] + end + end + return '', '', '' if receivers.blank? project = issue&.project owner = project&.owner receivers = managers + followers @@ -30,6 +36,9 @@ class MessageTemplate::ProjectIssue < MessageTemplate end def self.get_email_message_content(receiver, is_manager, operator, issue) + if receiver.user_template_message_setting.present? && is_manager + return '', '', '' unless receiver.user_template_message_setting.email_body["ManageProject::Issue"] + end project = issue&.project owner = project&.owner title = email_title diff --git a/app/models/message_template/project_joined.rb b/app/models/message_template/project_joined.rb index 3ff1d23d..b46dc51a 100644 --- a/app/models/message_template/project_joined.rb +++ b/app/models/message_template/project_joined.rb @@ -17,6 +17,12 @@ class MessageTemplate::ProjectJoined < MessageTemplate # MessageTemplate::ProjectJoined.get_message_content(User.where(login: 'yystopf'), Project.last) def self.get_message_content(receivers, project) + receivers.each do |receiver| + if receiver.user_template_message_setting.present? + receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["Normal::Project"] + end + end + return '', '', '' if receivers.blank? content = sys_notice.gsub('{repository}', project&.name) url = notification_url.gsub('{owner}', project&.owner&.login).gsub('{identifier}', project&.identifier) return receivers_string(receivers), content, url @@ -26,6 +32,9 @@ class MessageTemplate::ProjectJoined < MessageTemplate end def self.get_email_message_content(receiver, project) + if receiver.user_template_message_setting.present? + return '', '', '' unless receiver.user_template_message_setting.email_body["Normal::Project"] + end title = email_title title.gsub!('{repository}', project&.name) diff --git a/app/models/message_template/project_left.rb b/app/models/message_template/project_left.rb index 3244e59a..3dfa7bb6 100644 --- a/app/models/message_template/project_left.rb +++ b/app/models/message_template/project_left.rb @@ -17,6 +17,11 @@ class MessageTemplate::ProjectLeft < MessageTemplate # MessageTemplate::ProjectLeft.get_message_content(User.where(login: 'yystopf'), Project.last) def self.get_message_content(receivers, project) + receivers.each do |receiver| + if receiver.user_template_message_setting.present? + receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["Normal::Project"] + end + end content = sys_notice.gsub('{repository}', project&.name) url = notification_url.gsub('{owner}', project&.owner&.login).gsub('{identifier}', project&.identifier) return receivers_string(receivers), content, url @@ -26,6 +31,9 @@ class MessageTemplate::ProjectLeft < MessageTemplate end def self.get_email_message_content(receiver, project) + if receiver.user_template_message_setting.present? + return '', '', '' unless receiver.user_template_message_setting.email_body["Normal::Project"] + end title = email_title title.gsub!('{repository}', project&.name) diff --git a/app/models/message_template/project_member_joined.rb b/app/models/message_template/project_member_joined.rb index e2ab7d61..7a781750 100644 --- a/app/models/message_template/project_member_joined.rb +++ b/app/models/message_template/project_member_joined.rb @@ -17,6 +17,12 @@ class MessageTemplate::ProjectMemberJoined < MessageTemplate # MessageTemplate::ProjectMemberJoined.get_message_content(User.where(login: 'yystopf')) def self.get_message_content(receivers, user, project) + receivers.each do |receiver| + if receiver.user_template_message_setting.present? + receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["ManageProject::Member"] + end + end + return '', '', '' if receivers.blank? content = sys_notice.gsub('{nickname1}', user&.real_name).gsub('{nickname2}', project&.owner&.real_name).gsub('{repository}', project&.name) url = notification_url.gsub('{owner}', project&.owner&.login).gsub('{identifier}', project&.identifier) return receivers_string(receivers), content, url @@ -26,6 +32,9 @@ class MessageTemplate::ProjectMemberJoined < MessageTemplate end def self.get_email_message_content(receiver, user, project) + if receiver.user_template_message_setting.present? + return '', '', '' unless receiver.user_template_message_setting.email_body["ManageProject::Member"] + end title = email_title title.gsub!('{nickname1}', user&.real_name) title.gsub!('{nickname2}', project&.owner&.real_name) diff --git a/app/models/message_template/project_member_left.rb b/app/models/message_template/project_member_left.rb index a7d9911d..f4179123 100644 --- a/app/models/message_template/project_member_left.rb +++ b/app/models/message_template/project_member_left.rb @@ -17,6 +17,12 @@ class MessageTemplate::ProjectMemberLeft < MessageTemplate # MessageTemplate::ProjectMemberLeft.get_message_content(User.where(login: 'yystopf'), User.last, Project.last) def self.get_message_content(receivers, user, project) + receivers.each do |receiver| + if receiver.user_template_message_setting.present? + receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["ManageProject::Member"] + end + end + return '', '', '' if receivers.blank? content = sys_notice.gsub('{nickname1}', user&.real_name).gsub('{nickname2}', project&.owner&.real_name).gsub('{repository}', project&.name) url = notification_url.gsub('{owner}', project&.owner&.login).gsub('{identifier}', project&.identifier) return receivers_string(receivers), content, url @@ -26,6 +32,9 @@ class MessageTemplate::ProjectMemberLeft < MessageTemplate end def self.get_email_message_content(receiver, user, project) + if receiver.user_template_message_setting.present? + return '', '', '' unless receiver.user_template_message_setting.email_body["ManageProject::Member"] + end title = email_title title.gsub!('{nickname1}', user&.real_name) title.gsub!('{nickname2}', project&.owner&.real_name) diff --git a/app/models/message_template/project_pull_request.rb b/app/models/message_template/project_pull_request.rb index 704936f5..ac04651e 100644 --- a/app/models/message_template/project_pull_request.rb +++ b/app/models/message_template/project_pull_request.rb @@ -17,9 +17,15 @@ class MessageTemplate::ProjectPullRequest < MessageTemplate # MessageTemplate::ProjectPullRequest.get_message_content(User.where(login: 'yystopf'), User.where(login: 'testforge2'), User.last, PullRequest.last) def self.get_message_content(managers, followers, operator, pull_request) + managers.each do |receiver| + if receiver.user_template_message_setting.present? + managers = managers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["ManageProject::PullRequest"] + end + end project = pull_request&.project owner = project&.owner receivers = managers + followers + return '', '', '' if receivers.blank? content = sys_notice.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub('{title}', pull_request&.title) url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', pull_request&.id.to_s) @@ -30,6 +36,9 @@ class MessageTemplate::ProjectPullRequest < MessageTemplate end def self.get_email_message_content(receiver, is_manager, operator, pull_request) + if receiver.user_template_message_setting.present? && is_manager + return '', '', '' unless receiver.user_template_message_setting.email_body["ManageProject::PullRequest"] + end project = pull_request&.project owner = project&.owner title = email_title diff --git a/app/models/message_template/project_role.rb b/app/models/message_template/project_role.rb index 4db81ab4..340db2c9 100644 --- a/app/models/message_template/project_role.rb +++ b/app/models/message_template/project_role.rb @@ -17,6 +17,12 @@ class MessageTemplate::ProjectRole < MessageTemplate # MessageTemplate::ProjectRole.get_message_content(User.where(login: 'yystopf'), Project.last, '管理员') def self.get_message_content(receivers, project, role) + receivers.each do |receiver| + if receiver.user_template_message_setting.present? + receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["Normal::Permission"] + end + end + return '', '', '' if receivers.blank? content = sys_notice.gsub('{repository}', project&.name).gsub('{role}', role) url = notification_url.gsub('{owner}', project&.owner&.login).gsub('{identifier}', project&.identifier) return receivers_string(receivers), content, url @@ -26,6 +32,9 @@ class MessageTemplate::ProjectRole < MessageTemplate end def self.get_email_message_content(receivers, project, role) + if receiver.user_template_message_setting.present? + return '', '', '' unless receiver.user_template_message_setting.email_body["Normal::Permission"] + end title = email_title title.gsub!('{repository}', project&.name) title.gsub!('{role}', role) diff --git a/app/models/message_template/project_setting_changed.rb b/app/models/message_template/project_setting_changed.rb index 3a8df5ff..31ac5f05 100644 --- a/app/models/message_template/project_setting_changed.rb +++ b/app/models/message_template/project_setting_changed.rb @@ -17,6 +17,12 @@ class MessageTemplate::ProjectSettingChanged < MessageTemplate # MessageTemplate::ProjectSettingChanged.get_message_content(User.where(login: 'yystopf'), User.last, Project.last, {description: '测试修改项目简介', category: '大数据', language: 'Ruby', permission: '公有', navbar: '易修, 合并请求'}) def self.get_message_content(receivers, operator, project, change_params) + receivers.each do |receiver| + if receiver.user_template_message_setting.present? + receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["ManageProject::SettingChanged"] + end + end + return '', '', '' if receivers.blank? return '', '', '' if change_params.blank? owner = project&.owner content = sys_notice.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name) @@ -141,6 +147,9 @@ class MessageTemplate::ProjectSettingChanged < MessageTemplate end def self.get_email_message_content(receiver, operator, project, change_params) + if receiver.user_template_message_setting.present? + return '', '', '' unless receiver.user_template_message_setting.email_body["ManageProject::SettingChanged"] + end return '', '', '' if change_params.blank? owner = project&.owner title = email_title diff --git a/app/models/message_template/pull_request_assigned.rb b/app/models/message_template/pull_request_assigned.rb index 54d51f3f..39939b6c 100644 --- a/app/models/message_template/pull_request_assigned.rb +++ b/app/models/message_template/pull_request_assigned.rb @@ -17,6 +17,12 @@ class MessageTemplate::PullRequestAssigned < MessageTemplate # MessageTemplate::PullRequestAssigned.get_message_content(User.where(login: 'yystopf'), User.last, PullRequest.last) def self.get_message_content(receivers, operator, pull_request) + receivers.each do |receiver| + if receiver.user_template_message_setting.present? + receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["CreateOrAssign::PullRequestAssigned"] + end + end + return '', '', '' if receivers.blank? project = pull_request&.project owner = project&.owner content = sys_notice.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub('{title}', pull_request&.title) @@ -28,6 +34,9 @@ class MessageTemplate::PullRequestAssigned < MessageTemplate end def self.get_email_message_content(receiver, operator, pull_request) + if receiver.user_template_message_setting.present? + return '', '', '' unless receiver.user_template_message_setting.email_body["CreateOrAssign::PullRequestAssigned"] + end project = pull_request&.project owner = project&.owner title = email_title diff --git a/app/models/template_message_setting/create_or_assign.rb b/app/models/template_message_setting/create_or_assign.rb index 65bf2642..2bdcffc8 100644 --- a/app/models/template_message_setting/create_or_assign.rb +++ b/app/models/template_message_setting/create_or_assign.rb @@ -22,8 +22,6 @@ class TemplateMessageSetting::CreateOrAssign < TemplateMessageSetting def self.build_init_data self.find_or_create_by(name: "易修被指派", key: "IssueAssigned") - self.find_or_create_by(name: "易修状态变更", key: "IssueChanged") self.find_or_create_by(name: "合并请求被指派", key: "PullRequestAssigned") - self.find_or_create_by(name: "合并请求状态变更", key: "PullRequestChanged") end end From 9157bc3eb9f4d11affe6840bc90e78c7ea2677c5 Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 18 Oct 2021 15:58:27 +0800 Subject: [PATCH 124/135] fix: api doc --- app/docs/slate/source/includes/_users.md | 24 ------------------------ public/docs/api.html | 24 ------------------------ 2 files changed, 48 deletions(-) diff --git a/app/docs/slate/source/includes/_users.md b/app/docs/slate/source/includes/_users.md index 4df28755..be2728d0 100644 --- a/app/docs/slate/source/includes/_users.md +++ b/app/docs/slate/source/includes/_users.md @@ -438,12 +438,6 @@ await octokit.request('GET /api/template_message_settings.json') "type_name": "我创建的或负责的", "total_settings_count": 4, "settings": [ - { - "name": "易修状态变更", - "key": "IssueChanged", - "notification_disabled": true, - "email_disabled": false - }, { "name": "易修被指派", "key": "IssueAssigned", @@ -455,12 +449,6 @@ await octokit.request('GET /api/template_message_settings.json') "key": "PullRequestAssigned", "notification_disabled": true, "email_disabled": false - }, - { - "name": "合并请求状态变更", - "key": "PullRequestAssigned", - "notification_disabled": true, - "email_disabled": false } ] }, @@ -539,10 +527,8 @@ await octokit.request('GET /api/uses/yystopf/template_message_settings.json') "image_url": "system/lets/letter_avatars/2/H/188_239_142/120.png" }, "notification_body": { - "CreateOrAssign::IssueChanged": true, "CreateOrAssign::IssueAssigned": true, "CreateOrAssign::PullRequestAssigned": true, - "CreateOrAssign::PullRequestChanged": true, "ManageProject::Issue": true, "ManageProject::PullRequest": true, "ManageProject::Member": true, @@ -552,10 +538,8 @@ await octokit.request('GET /api/uses/yystopf/template_message_settings.json') "Normal::Permission": true }, "email_body": { - "CreateOrAssign::IssueChanged": false, "CreateOrAssign::IssueAssigned": false, "CreateOrAssign::PullRequestAssigned": false, - "CreateOrAssign::PullRequestChanged": false, "ManageProject::Issue": false, "ManageProject::PullRequest": false, "ManageProject::Member": false, @@ -599,10 +583,8 @@ await octokit.request('POST /api/uses/yystopf/template_message_settings/update_s { "setting": { "notification_body": { - "CreateOrAssign::IssueChanged": true, "CreateOrAssign::IssueAssigned": true, "CreateOrAssign::PullRequestAssigned": true, - "CreateOrAssign::PullRequestChanged": true, "ManageProject::Issue": true, "ManageProject::PullRequest": true, "ManageProject::Member": true, @@ -612,10 +594,8 @@ await octokit.request('POST /api/uses/yystopf/template_message_settings/update_s "Normal::Permission": true }, "email_body": { - "CreateOrAssign::IssueChanged": false, "CreateOrAssign::IssueAssigned": false, "CreateOrAssign::PullRequestAssigned": false, - "CreateOrAssign::PullRequestChanged": false, "ManageProject::Issue": false, "ManageProject::PullRequest": false, "ManageProject::Member": false, @@ -649,10 +629,8 @@ await octokit.request('POST /api/uses/yystopf/template_message_settings/update_s "image_url": "system/lets/letter_avatars/2/H/188_239_142/120.png" }, "notification_body": { - "CreateOrAssign::IssueChanged": true, "CreateOrAssign::IssueAssigned": true, "CreateOrAssign::PullRequestAssigned": true, - "CreateOrAssign::PullRequestChanged": true, "ManageProject::Issue": true, "ManageProject::PullRequest": true, "ManageProject::Member": true, @@ -662,10 +640,8 @@ await octokit.request('POST /api/uses/yystopf/template_message_settings/update_s "Normal::Permission": true }, "email_body": { - "CreateOrAssign::IssueChanged": false, "CreateOrAssign::IssueAssigned": false, "CreateOrAssign::PullRequestAssigned": false, - "CreateOrAssign::PullRequestChanged": false, "ManageProject::Issue": false, "ManageProject::PullRequest": false, "ManageProject::Member": false, diff --git a/public/docs/api.html b/public/docs/api.html index e2a64202..5df230a2 100644 --- a/public/docs/api.html +++ b/public/docs/api.html @@ -1670,12 +1670,6 @@ Success — a happy kitten is an authenticated kitten! "type_name": "我创建的或负责的", "total_settings_count": 4, "settings": [ - { - "name": "易修状态变更", - "key": "IssueChanged", - "notification_disabled": true, - "email_disabled": false - }, { "name": "易修被指派", "key": "IssueAssigned", @@ -1687,12 +1681,6 @@ Success — a happy kitten is an authenticated kitten! "key": "PullRequestAssigned", "notification_disabled": true, "email_disabled": false - }, - { - "name": "合并请求状态变更", - "key": "PullRequestAssigned", - "notification_disabled": true, - "email_disabled": false } ] }, @@ -1777,10 +1765,8 @@ Success — a happy kitten is an authenticated kitten! "image_url": "system/lets/letter_avatars/2/H/188_239_142/120.png" }, "notification_body": { - "CreateOrAssign::IssueChanged": true, "CreateOrAssign::IssueAssigned": true, "CreateOrAssign::PullRequestAssigned": true, - "CreateOrAssign::PullRequestChanged": true, "ManageProject::Issue": true, "ManageProject::PullRequest": true, "ManageProject::Member": true, @@ -1790,10 +1776,8 @@ Success — a happy kitten is an authenticated kitten! "Normal::Permission": true }, "email_body": { - "CreateOrAssign::IssueChanged": false, "CreateOrAssign::IssueAssigned": false, "CreateOrAssign::PullRequestAssigned": false, - "CreateOrAssign::PullRequestChanged": false, "ManageProject::Issue": false, "ManageProject::PullRequest": false, "ManageProject::Member": false, @@ -1843,10 +1827,8 @@ Success — a happy kitten is an authenticated kitten!
    {
         "setting": {
             "notification_body": {
    -            "CreateOrAssign::IssueChanged": true,
                 "CreateOrAssign::IssueAssigned": true,
                 "CreateOrAssign::PullRequestAssigned": true,
    -            "CreateOrAssign::PullRequestChanged": true,
                 "ManageProject::Issue": true,
                 "ManageProject::PullRequest": true,
                 "ManageProject::Member": true,
    @@ -1856,10 +1838,8 @@ Success — a happy kitten is an authenticated kitten!
                 "Normal::Permission": true
             },
             "email_body": {
    -            "CreateOrAssign::IssueChanged": false,
                 "CreateOrAssign::IssueAssigned": false,
                 "CreateOrAssign::PullRequestAssigned": false,
    -            "CreateOrAssign::PullRequestChanged": false,
                 "ManageProject::Issue": false,
                 "ManageProject::PullRequest": false,
                 "ManageProject::Member": false,
    @@ -1904,10 +1884,8 @@ Success — a happy kitten is an authenticated kitten!
             "image_url": "system/lets/letter_avatars/2/H/188_239_142/120.png"
         },
         "notification_body": {
    -        "CreateOrAssign::IssueChanged": true,
             "CreateOrAssign::IssueAssigned": true,
             "CreateOrAssign::PullRequestAssigned": true,
    -        "CreateOrAssign::PullRequestChanged": true,
             "ManageProject::Issue": true,
             "ManageProject::PullRequest": true,
             "ManageProject::Member": true,
    @@ -1917,10 +1895,8 @@ Success — a happy kitten is an authenticated kitten!
             "Normal::Permission": true
         },
         "email_body": {
    -        "CreateOrAssign::IssueChanged": false,
             "CreateOrAssign::IssueAssigned": false,
             "CreateOrAssign::PullRequestAssigned": false,
    -        "CreateOrAssign::PullRequestChanged": false,
             "ManageProject::Issue": false,
             "ManageProject::PullRequest": false,
             "ManageProject::Member": false,
    
    From 7d98bd0bbe3dbb49094be68ccc9a3317c00b08e9 Mon Sep 17 00:00:00 2001
    From: yystopf 
    Date: Mon, 18 Oct 2021 16:02:31 +0800
    Subject: [PATCH 125/135] fix: template message settinng type order by order
     index
    
    ---
     app/models/template_message_setting/create_or_assign.rb | 4 ++++
     app/models/template_message_setting/manage_project.rb   | 4 ++++
     app/models/template_message_setting/normal.rb           | 4 ++++
     app/models/template_message_setting/watch_project.rb    | 4 ++++
     app/views/template_message_settings/index.json.jbuilder | 2 +-
     5 files changed, 17 insertions(+), 1 deletion(-)
    
    diff --git a/app/models/template_message_setting/create_or_assign.rb b/app/models/template_message_setting/create_or_assign.rb
    index 2bdcffc8..4de89906 100644
    --- a/app/models/template_message_setting/create_or_assign.rb
    +++ b/app/models/template_message_setting/create_or_assign.rb
    @@ -20,6 +20,10 @@ class TemplateMessageSetting::CreateOrAssign < TemplateMessageSetting
         "我创建的或负责的"
       end
     
    +  def self.order_index
    +    20
    +  end
    +
       def self.build_init_data
         self.find_or_create_by(name: "易修被指派", key: "IssueAssigned")
         self.find_or_create_by(name: "合并请求被指派", key: "PullRequestAssigned")
    diff --git a/app/models/template_message_setting/manage_project.rb b/app/models/template_message_setting/manage_project.rb
    index b1e69a5a..18defc6c 100644
    --- a/app/models/template_message_setting/manage_project.rb
    +++ b/app/models/template_message_setting/manage_project.rb
    @@ -20,6 +20,10 @@ class TemplateMessageSetting::ManageProject < TemplateMessageSetting
         "我管理的仓库"
       end
     
    +  def self.order_index 
    +    30
    +  end
    +
       def self.build_init_data
         self.find_or_create_by(name: "有新的易修", key: "Issue")
         self.find_or_create_by(name: "有新的合并请求", key: "PullRequest")
    diff --git a/app/models/template_message_setting/normal.rb b/app/models/template_message_setting/normal.rb
    index 789e35b6..b0495b8c 100644
    --- a/app/models/template_message_setting/normal.rb
    +++ b/app/models/template_message_setting/normal.rb
    @@ -19,6 +19,10 @@ class TemplateMessageSetting::Normal < TemplateMessageSetting
         ""
       end
     
    +  def self.order_index 
    +    10
    +  end
    +
       def self.build_init_data
         self.find_or_create_by(name: "被拉入或移出组织", key: "Organization")
         self.find_or_create_by(name: "被拉入或移出项目", key: "Project")
    diff --git a/app/models/template_message_setting/watch_project.rb b/app/models/template_message_setting/watch_project.rb
    index 169e68e8..35dfef6d 100644
    --- a/app/models/template_message_setting/watch_project.rb
    +++ b/app/models/template_message_setting/watch_project.rb
    @@ -20,6 +20,10 @@ class TemplateMessageSetting::WatchProject < TemplateMessageSetting
         "我关注的仓库"
       end
     
    +  def self.order_index
    +    40
    +  end
    +
       def self.build_init_data
       end
     end
    diff --git a/app/views/template_message_settings/index.json.jbuilder b/app/views/template_message_settings/index.json.jbuilder
    index eae5bb01..4f863ce0 100644
    --- a/app/views/template_message_settings/index.json.jbuilder
    +++ b/app/views/template_message_settings/index.json.jbuilder
    @@ -1,7 +1,7 @@
     json.partial! "commons/success"
     json.setting_types do 
     
    -  json.array! @group_settings.keys.sort_by{|i| i.constantize.type_name}.each do |k|
    +  json.array! @group_settings.keys.sort_by{|i| i.constantize.order_index}.each do |k|
         json.partial! "detail", type: k, count: @group_settings[k]
       end
     
    
    From bd9759a3ed0a8184dad71d95ca757a1b1af341bd Mon Sep 17 00:00:00 2001
    From: yystopf 
    Date: Mon, 18 Oct 2021 17:32:36 +0800
    Subject: [PATCH 126/135] fix: user template message setting init data
    
    ---
     app/models/user_template_message_setting.rb | 4 ----
     1 file changed, 4 deletions(-)
    
    diff --git a/app/models/user_template_message_setting.rb b/app/models/user_template_message_setting.rb
    index 5992adbb..1039b39d 100644
    --- a/app/models/user_template_message_setting.rb
    +++ b/app/models/user_template_message_setting.rb
    @@ -28,10 +28,8 @@ class UserTemplateMessageSetting < ApplicationRecord
     
       def self.init_notification_body 
         {
    -      "CreateOrAssign::IssueChanged": true,
           "CreateOrAssign::IssueAssigned": true,
           "CreateOrAssign::PullRequestAssigned": true,
    -      "CreateOrAssign::PullRequestChanged": true,
           "ManageProject::Issue": true,
           "ManageProject::PullRequest": true,
           "ManageProject::Member": true,
    @@ -44,10 +42,8 @@ class UserTemplateMessageSetting < ApplicationRecord
     
       def self.init_email_body 
         {
    -      "CreateOrAssign::IssueChanged": false,
           "CreateOrAssign::IssueAssigned": false,
           "CreateOrAssign::PullRequestAssigned": false,
    -      "CreateOrAssign::PullRequestChanged": false,
           "ManageProject::Issue": false,
           "ManageProject::PullRequest": false,
           "ManageProject::Member": false,
    
    From dbe47dbddfd19953a9b933634defc2135caf9a4a Mon Sep 17 00:00:00 2001
    From: yystopf 
    Date: Tue, 19 Oct 2021 14:39:15 +0800
    Subject: [PATCH 127/135] fix: change template message setting default value
    
    ---
     .../create_or_assign.rb                       |  3 +-
     app/models/template_message_setting/normal.rb |  6 ++--
     app/models/user_template_message_setting.rb   | 28 +++++++++----------
     3 files changed, 19 insertions(+), 18 deletions(-)
    
    diff --git a/app/models/template_message_setting/create_or_assign.rb b/app/models/template_message_setting/create_or_assign.rb
    index 4de89906..54f84240 100644
    --- a/app/models/template_message_setting/create_or_assign.rb
    +++ b/app/models/template_message_setting/create_or_assign.rb
    @@ -25,7 +25,6 @@ class TemplateMessageSetting::CreateOrAssign < TemplateMessageSetting
       end
     
       def self.build_init_data
    -    self.find_or_create_by(name: "易修被指派", key: "IssueAssigned")
    -    self.find_or_create_by(name: "合并请求被指派", key: "PullRequestAssigned")
    +
       end
     end
    diff --git a/app/models/template_message_setting/normal.rb b/app/models/template_message_setting/normal.rb
    index b0495b8c..2a1f5007 100644
    --- a/app/models/template_message_setting/normal.rb
    +++ b/app/models/template_message_setting/normal.rb
    @@ -16,7 +16,7 @@
     class TemplateMessageSetting::Normal < TemplateMessageSetting 
     
       def self.type_name 
    -    ""
    +    "我的状态"
       end
     
       def self.order_index 
    @@ -24,8 +24,10 @@ class TemplateMessageSetting::Normal < TemplateMessageSetting
       end
     
       def self.build_init_data
    +    self.find_or_create_by(name: "账号有权限变更", key: "Permission")
         self.find_or_create_by(name: "被拉入或移出组织", key: "Organization")
         self.find_or_create_by(name: "被拉入或移出项目", key: "Project")
    -    self.find_or_create_by(name: "有权限变更", key: "Permission")
    +    self.find_or_create_by(name: "易修被指派", key: "IssueAssigned")
    +    self.find_or_create_by(name: "合并请求被指派", key: "PullRequestAssigned")
       end
     end
    diff --git a/app/models/user_template_message_setting.rb b/app/models/user_template_message_setting.rb
    index 1039b39d..685eb1bf 100644
    --- a/app/models/user_template_message_setting.rb
    +++ b/app/models/user_template_message_setting.rb
    @@ -28,29 +28,29 @@ class UserTemplateMessageSetting < ApplicationRecord
     
       def self.init_notification_body 
         {
    -      "CreateOrAssign::IssueAssigned": true,
    -      "CreateOrAssign::PullRequestAssigned": true,
    +      "Normal::Permission": true,
    +      "Normal::Project": true,
    +      "Normal::Organization": true,
    +      "Normal::IssueAssigned": true,
    +      "Normal::PullRequestAssigned": true,
           "ManageProject::Issue": true,
           "ManageProject::PullRequest": true,
           "ManageProject::Member": true,
           "ManageProject::SettingChanged": true,
    -      "Normal::Organization": true,
    -      "Normal::Project": true,
    -      "Normal::Permission": true,
         }.stringify_keys!
       end
     
       def self.init_email_body 
         {
    -      "CreateOrAssign::IssueAssigned": false,
    -      "CreateOrAssign::PullRequestAssigned": false,
    -      "ManageProject::Issue": false,
    -      "ManageProject::PullRequest": false,
    -      "ManageProject::Member": false,
    -      "ManageProject::SettingChanged": false,
    -      "Normal::Organization": false,
    -      "Normal::Project": false,
    -      "Normal::Permission": false,
    +      "Normal::Permission": true,
    +      "Normal::Project": true,
    +      "Normal::Organization": true,
    +      "Normal::IssueAssigned": true,
    +      "Normal::PullRequestAssigned": true,
    +      "ManageProject::Issue": true,
    +      "ManageProject::PullRequest": true,
    +      "ManageProject::Member": true,
    +      "ManageProject::SettingChanged": true,
         }.stringify_keys!
       end
     
    
    From 3ce8723de2de4733e3cf7ec0f0480efc475ef97b Mon Sep 17 00:00:00 2001
    From: yystopf 
    Date: Tue, 19 Oct 2021 14:49:35 +0800
    Subject: [PATCH 128/135] fix
    
    ---
     app/models/template_message_setting/manage_project.rb | 2 +-
     app/models/template_message_setting/normal.rb         | 4 ++--
     2 files changed, 3 insertions(+), 3 deletions(-)
    
    diff --git a/app/models/template_message_setting/manage_project.rb b/app/models/template_message_setting/manage_project.rb
    index 18defc6c..2aa9e488 100644
    --- a/app/models/template_message_setting/manage_project.rb
    +++ b/app/models/template_message_setting/manage_project.rb
    @@ -28,6 +28,6 @@ class TemplateMessageSetting::ManageProject < TemplateMessageSetting
         self.find_or_create_by(name: "有新的易修", key: "Issue")
         self.find_or_create_by(name: "有新的合并请求", key: "PullRequest")
         self.find_or_create_by(name: "有成员变动", key: "Member")
    -    self.find_or_create_by(name: "设置更改", key: "SettingChanged")
    +    self.find_or_create_by(name: "仓库设置被更改", key: "SettingChanged")
       end
     end
    diff --git a/app/models/template_message_setting/normal.rb b/app/models/template_message_setting/normal.rb
    index 2a1f5007..9090196d 100644
    --- a/app/models/template_message_setting/normal.rb
    +++ b/app/models/template_message_setting/normal.rb
    @@ -27,7 +27,7 @@ class TemplateMessageSetting::Normal < TemplateMessageSetting
         self.find_or_create_by(name: "账号有权限变更", key: "Permission")
         self.find_or_create_by(name: "被拉入或移出组织", key: "Organization")
         self.find_or_create_by(name: "被拉入或移出项目", key: "Project")
    -    self.find_or_create_by(name: "易修被指派", key: "IssueAssigned")
    -    self.find_or_create_by(name: "合并请求被指派", key: "PullRequestAssigned")
    +    self.find_or_create_by(name: "有新的易修指派给我", key: "IssueAssigned")
    +    self.find_or_create_by(name: "有新的合并请求指派给我", key: "PullRequestAssigned")
       end
     end
    
    From c52f40adbd03f2bb57e7cc5281adcf7e37ea49ce Mon Sep 17 00:00:00 2001
    From: yystopf 
    Date: Tue, 19 Oct 2021 16:21:34 +0800
    Subject: [PATCH 129/135] fix
    
    ---
     app/jobs/send_template_message_job.rb                | 2 +-
     app/models/message_template/issue_assigned.rb        | 4 ++--
     app/models/message_template/project_issue.rb         | 2 +-
     app/models/message_template/project_role.rb          | 2 +-
     app/models/message_template/pull_request_assigned.rb | 4 ++--
     app/models/template_message_setting/normal.rb        | 2 +-
     app/models/user_template_message_setting.rb          | 4 ++--
     7 files changed, 10 insertions(+), 10 deletions(-)
    
    diff --git a/app/jobs/send_template_message_job.rb b/app/jobs/send_template_message_job.rb
    index 2c463d70..a5b1434c 100644
    --- a/app/jobs/send_template_message_job.rb
    +++ b/app/jobs/send_template_message_job.rb
    @@ -193,7 +193,7 @@ class SendTemplateMessageJob < ApplicationJob
           receivers_string, content, notification_url = MessageTemplate::ProjectRole.get_message_content(receivers, project, role)
           Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, user_id: user.id, project_id: project.id, role: role})
           receivers.find_each do |receiver|
    -        receivers_email_string, email_title, email_content = MessageTemplate::ProjectRole.get_email_message_content(receivers, project, role)
    +        receivers_email_string, email_title, email_content = MessageTemplate::ProjectRole.get_email_message_content(receiver, project, role)
             Notice::Write::EmailCreateService.call(receivers_email_string, email_title, email_content)
           end
         when 'ProjectSettingChanged'
    diff --git a/app/models/message_template/issue_assigned.rb b/app/models/message_template/issue_assigned.rb
    index 4ed58105..23632c3e 100644
    --- a/app/models/message_template/issue_assigned.rb
    +++ b/app/models/message_template/issue_assigned.rb
    @@ -19,7 +19,7 @@ class MessageTemplate::IssueAssigned < MessageTemplate
       def self.get_message_content(receivers, operator, issue)
         receivers.each do |receiver|
           if receiver.user_template_message_setting.present? 
    -        receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["CreateOrAssign::IssueAssigned"]
    +        receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["Normal::IssueAssigned"]
           end
         end
         return '', '', '' if receivers.blank?
    @@ -35,7 +35,7 @@ class MessageTemplate::IssueAssigned < MessageTemplate
     
       def self.get_email_message_content(receiver, operator, issue)
         if receiver.user_template_message_setting.present? 
    -      return '', '', '' unless receiver.user_template_message_setting.email_body["CreateOrAssign::IssueAssigned"]
    +      return '', '', '' unless receiver.user_template_message_setting.email_body["Normal::IssueAssigned"]
         end
         project = issue&.project
         owner = project&.owner 
    diff --git a/app/models/message_template/project_issue.rb b/app/models/message_template/project_issue.rb
    index 15548b21..9106bcc8 100644
    --- a/app/models/message_template/project_issue.rb
    +++ b/app/models/message_template/project_issue.rb
    @@ -22,10 +22,10 @@ class MessageTemplate::ProjectIssue < MessageTemplate
             managers = managers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["ManageProject::Issue"]
           end
         end
    -    return '', '', '' if receivers.blank?
         project = issue&.project 
         owner = project&.owner 
         receivers = managers + followers
    +    return '', '', '' if receivers.blank?
         content = sys_notice.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub('{title}', issue&.subject)
         url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s)
         
    diff --git a/app/models/message_template/project_role.rb b/app/models/message_template/project_role.rb
    index 340db2c9..6cb88ab8 100644
    --- a/app/models/message_template/project_role.rb
    +++ b/app/models/message_template/project_role.rb
    @@ -31,7 +31,7 @@ class MessageTemplate::ProjectRole < MessageTemplate
         return '', '', ''
       end
     
    -  def self.get_email_message_content(receivers, project, role)
    +  def self.get_email_message_content(receiver, project, role)
         if receiver.user_template_message_setting.present? 
           return '', '', '' unless receiver.user_template_message_setting.email_body["Normal::Permission"]
         end
    diff --git a/app/models/message_template/pull_request_assigned.rb b/app/models/message_template/pull_request_assigned.rb
    index 39939b6c..1101ca46 100644
    --- a/app/models/message_template/pull_request_assigned.rb
    +++ b/app/models/message_template/pull_request_assigned.rb
    @@ -19,7 +19,7 @@ class MessageTemplate::PullRequestAssigned < MessageTemplate
       def self.get_message_content(receivers, operator, pull_request)
         receivers.each do |receiver|
           if receiver.user_template_message_setting.present? 
    -        receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["CreateOrAssign::PullRequestAssigned"]
    +        receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["Normal::PullRequestAssigned"]
           end
         end
         return '', '', '' if receivers.blank?
    @@ -35,7 +35,7 @@ class MessageTemplate::PullRequestAssigned < MessageTemplate
     
       def self.get_email_message_content(receiver, operator, pull_request)
         if receiver.user_template_message_setting.present? 
    -      return '', '', '' unless receiver.user_template_message_setting.email_body["CreateOrAssign::PullRequestAssigned"]
    +      return '', '', '' unless receiver.user_template_message_setting.email_body["Normal::PullRequestAssigned"]
         end
         project = pull_request&.project
         owner = project&.owner 
    diff --git a/app/models/template_message_setting/normal.rb b/app/models/template_message_setting/normal.rb
    index 9090196d..44ed3561 100644
    --- a/app/models/template_message_setting/normal.rb
    +++ b/app/models/template_message_setting/normal.rb
    @@ -24,7 +24,7 @@ class TemplateMessageSetting::Normal < TemplateMessageSetting
       end
     
       def self.build_init_data
    -    self.find_or_create_by(name: "账号有权限变更", key: "Permission")
    +    # self.find_or_create_by(name: "账号有权限变更", key: "Permission")
         self.find_or_create_by(name: "被拉入或移出组织", key: "Organization")
         self.find_or_create_by(name: "被拉入或移出项目", key: "Project")
         self.find_or_create_by(name: "有新的易修指派给我", key: "IssueAssigned")
    diff --git a/app/models/user_template_message_setting.rb b/app/models/user_template_message_setting.rb
    index 685eb1bf..7b7f8cb8 100644
    --- a/app/models/user_template_message_setting.rb
    +++ b/app/models/user_template_message_setting.rb
    @@ -28,7 +28,7 @@ class UserTemplateMessageSetting < ApplicationRecord
     
       def self.init_notification_body 
         {
    -      "Normal::Permission": true,
    +      # "Normal::Permission": true,
           "Normal::Project": true,
           "Normal::Organization": true,
           "Normal::IssueAssigned": true,
    @@ -42,7 +42,7 @@ class UserTemplateMessageSetting < ApplicationRecord
     
       def self.init_email_body 
         {
    -      "Normal::Permission": true,
    +      # "Normal::Permission": true,
           "Normal::Project": true,
           "Normal::Organization": true,
           "Normal::IssueAssigned": true,
    
    From 748e8cc92ab6057106b74883c7dff87e1cfbcb68 Mon Sep 17 00:00:00 2001
    From: yystopf 
    Date: Wed, 20 Oct 2021 14:34:15 +0800
    Subject: [PATCH 130/135] add: send template message email supplement
    
    ---
     app/jobs/send_template_message_job.rb         |  24 ++-
     app/models/message_template.rb                |  29 +--
     app/models/message_template/issue_changed.rb  | 185 ++++++++++++++++++
     app/models/message_template/issue_deleted.rb  |  27 ++-
     app/models/message_template/project_role.rb   |   2 +
     .../message_template/pull_request_changed.rb  |  97 +++++++++
     .../message_template/pull_request_closed.rb   |  32 +++
     .../message_template/pull_request_merged.rb   |  32 +++
     .../create_or_assign.rb                       |   3 +-
     app/models/template_message_setting/normal.rb |   2 +-
     app/models/user_template_message_setting.rb   |   8 +-
     public/message_template/issue_changed.html    |  62 ++++++
     public/message_template/issue_deleted.html    |  52 +++++
     .../message_template/organization_role.html   |  52 +++++
     .../project_pull_request.html                 |   2 +-
     public/message_template/project_role.html     |  52 +++++
     .../pull_request_assigned.html                |   2 +-
     .../pull_request_changed.html                 |  56 ++++++
     .../message_template/pull_request_closed.html |  52 +++++
     .../message_template/pull_request_merged.html |  52 +++++
     20 files changed, 803 insertions(+), 20 deletions(-)
     create mode 100755 public/message_template/issue_changed.html
     create mode 100755 public/message_template/issue_deleted.html
     create mode 100755 public/message_template/organization_role.html
     create mode 100755 public/message_template/project_role.html
     create mode 100755 public/message_template/pull_request_changed.html
     create mode 100755 public/message_template/pull_request_closed.html
     create mode 100755 public/message_template/pull_request_merged.html
    
    diff --git a/app/jobs/send_template_message_job.rb b/app/jobs/send_template_message_job.rb
    index a5b1434c..a0191cee 100644
    --- a/app/jobs/send_template_message_job.rb
    +++ b/app/jobs/send_template_message_job.rb
    @@ -45,8 +45,12 @@ class SendTemplateMessageJob < ApplicationJob
           issue = Issue.find_by_id(issue_id)
           return unless operator.present? && issue.present?
           receivers = User.where(id: [issue&.assigned_to_id, issue&.author_id]).where.not(id: operator&.id)
    -      receivers_string, content, notification_url = MessageTemplate::IssueChanged.get_message_content(receivers, operator, issue, change_params)
    +      receivers_string, content, notification_url = MessageTemplate::IssueChanged.get_message_content(receivers, operator, issue, change_params.symbolize_keys)
           Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_id: issue.id, change_params: change_params.symbolize_keys})
    +      receivers.find_each do |receiver|
    +        receivers_email_string, email_title, email_content = MessageTemplate::IssueChanged.get_email_message_content(receiver, operator, issue, change_params)
    +        Notice::Write::EmailCreateService.call(receivers_email_string, email_title, email_content)
    +      end
         when 'IssueCreatorExpire'
           issue_id = args[0]
           issue = Issue.find_by_id(issue_id)
    @@ -61,6 +65,10 @@ class SendTemplateMessageJob < ApplicationJob
           receivers = User.where(id: [issue_assigned_to_id, issue_author_id]).where.not(id: operator&.id)
           receivers_string, content, notification_url = MessageTemplate::IssueDeleted.get_message_content(receivers, operator, issue_title)
           Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_title: issue_title})
    +      receivers.find_each do |receiver|
    +        receivers_email_string, email_title, email_content = MessageTemplate::IssueDeleted.get_email_message_content(receiver, operator, issue_title)
    +        Notice::Write::EmailCreateService.call(receivers_email_string, email_title, email_content)
    +      end
         when 'OrganizationJoined'
           user_id, organization_id = args[0], args[1]
           user = User.find_by_id(user_id)
    @@ -203,7 +211,7 @@ class SendTemplateMessageJob < ApplicationJob
           return unless operator.present? && project.present?
           receivers = project.all_managers.where.not(id: operator&.id)
           receivers_string, content, notification_url = MessageTemplate::ProjectSettingChanged.get_message_content(receivers, operator, project, change_params.symbolize_keys)
    -      Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, project_id: project.id, change_params: change_params})
    +      Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, project_id: project.id, change_params: change_params.symbolize_keys})
           receivers.find_each do |receiver|
             receivers_email_string, email_title, email_content = MessageTemplate::ProjectSettingChanged.get_email_message_content(receiver, operator, project, change_params.symbolize_keys)
             Notice::Write::EmailCreateService.call(receivers_email_string, email_title, email_content)
    @@ -238,6 +246,10 @@ class SendTemplateMessageJob < ApplicationJob
           receivers = User.where(id: [issue&.assigned_to_id, pull_request&.user_id]).where.not(id: operator&.id)
           receivers_string, content, notification_url = MessageTemplate::PullRequestChanged.get_message_content(receivers, operator, pull_request, change_params.symbolize_keys)
           Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, pull_request_id: pull_request.id, change_params: change_params})
    +      receivers.find_each do |receiver|
    +        receivers_email_string, email_title, email_content = MessageTemplate::PullRequestChanged.get_email_message_content(receiver, operator, pull_request, change_params.symbolize_keys)
    +        Notice::Write::EmailCreateService.call(receivers_email_string, email_title, email_content)
    +      end
         when 'PullRequestClosed'
           operator_id, pull_request_id = args[0], args[1]
           operator = User.find_by_id(operator_id)
    @@ -246,6 +258,10 @@ class SendTemplateMessageJob < ApplicationJob
           receivers = User.where(id: [pull_request&.issue&.assigned_to_id, pull_request&.user_id]).where.not(id: operator&.id)
           receivers_string, content, notification_url = MessageTemplate::PullRequestClosed.get_message_content(receivers, operator, pull_request)
           Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, pull_request_id: pull_request.id})
    +      receivers.find_each do |receiver|
    +        receivers_email_string, email_title, email_content = MessageTemplate::PullRequestClosed.get_email_message_content(receiver, operator, pull_request)
    +        Notice::Write::EmailCreateService.call(receivers_email_string, email_title, email_content)
    +      end
         when 'PullRequestMerged'
           operator_id, pull_request_id = args[0], args[1]
           operator = User.find_by_id(operator_id)
    @@ -254,6 +270,10 @@ class SendTemplateMessageJob < ApplicationJob
           receivers = User.where(id: [pull_request&.issue&.assigned_to_id, pull_request&.user_id]).where.not(id: operator&.id)
           receivers_string, content, notification_url = MessageTemplate::PullRequestMerged.get_message_content(receivers, operator, pull_request)
           Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, pull_request_id: pull_request.id})
    +      receivers.find_each do |receiver|
    +        receivers_email_string, email_title, email_content = MessageTemplate::PullRequestMerged.get_email_message_content(receiver, operator, pull_request)
    +        Notice::Write::EmailCreateService.call(receivers_email_string, email_title, email_content)
    +      end
         end
       end
     end
    \ No newline at end of file
    diff --git a/app/models/message_template.rb b/app/models/message_template.rb
    index 2c8c9686..8d3f622b 100644
    --- a/app/models/message_template.rb
    +++ b/app/models/message_template.rb
    @@ -20,16 +20,19 @@ class MessageTemplate < ApplicationRecord
         self.create(type: 'MessageTemplate::IssueAssigned', sys_notice: '{nickname1}在 {nickname2}/{repository} 指派给你一个易修:{title}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}', email: email_html, email_title: '{nickname1} 在 {nickname2}/{repository} 指派给你一个易修')
         self.create(type: 'MessageTemplate::IssueAssignerExpire', sys_notice: '您负责的易修 {title} 已临近截止日期,请尽快处理', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}')
         self.create(type: 'MessageTemplate::IssueAtme', sys_notice: '{nickname} 在易修 {title} 中@我', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}')
    -    self.create(type: 'MessageTemplate::IssueChanged', sys_notice: '在项目 {nickname2}/{repository} 的易修 {title} 中:{ifassigner}{nickname1}将负责人从 {assigner1} 修改为 {assigner2} {endassigner}{ifstatus}{nickname1}将状态从 {status1} 修改为 {status2} {endstatus}{iftracker}{nickname1}将类型从 {tracker1} 修改为 {tracker2} {endtracker}{ifpriority}{nickname1}将优先级从 {priority1} 修改为 {priority2} {endpriority}{ifmilestone}{nickname1}将里程碑从 {milestone1} 修改为 {milestone2} {endmilestone}{iftag}{nickname1}将标记从 {tag1} 修改为 {tag2} {endtag}{ifdoneratio}{nickname1}将完成度从 {doneratio1} 修改为 {doneratio2} {enddoneratio}{ifbranch}{nickname1}将指定分支从 {branch1} 修改为 {branch2} {endbranch}{ifstartdate}{nickname1}将开始日期从 {startdate1} 修改为 {startdate2} {endstartdate}{ifduedate}{nickname1}将结束日期从 {duedate1} 修改为 {duedate2} {endduedate}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}')
    +    email_html = File.read("#{email_template_html_dir}/issue_changed.html")
    +    self.create(type: 'MessageTemplate::IssueChanged', sys_notice: '在项目 {nickname2}/{repository} 的易修 {title} 中:{ifassigner}{nickname1}将负责人从 {assigner1} 修改为 {assigner2} {endassigner}{ifstatus}{nickname1}将状态从 {status1} 修改为 {status2} {endstatus}{iftracker}{nickname1}将类型从 {tracker1} 修改为 {tracker2} {endtracker}{ifpriority}{nickname1}将优先级从 {priority1} 修改为 {priority2} {endpriority}{ifmilestone}{nickname1}将里程碑从 {milestone1} 修改为 {milestone2} {endmilestone}{iftag}{nickname1}将标记从 {tag1} 修改为 {tag2} {endtag}{ifdoneratio}{nickname1}将完成度从 {doneratio1} 修改为 {doneratio2} {enddoneratio}{ifbranch}{nickname1}将指定分支从 {branch1} 修改为 {branch2} {endbranch}{ifstartdate}{nickname1}将开始日期从 {startdate1} 修改为 {startdate2} {endstartdate}{ifduedate}{nickname1}将结束日期从 {duedate1} 修改为 {duedate2} {endduedate}', email: email_html, email_title: '易修 {title} 有状态变更', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}')
         self.create(type: 'MessageTemplate::IssueCreatorExpire', sys_notice: '您发布的易修 {title} 已临近截止日期,请尽快处理', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}')
    -    self.create(type: 'MessageTemplate::IssueDeleted', sys_notice: '{nickname}已将易修 {title} 删除', notification_url: '')
    +    email_html = File.read("#{email_template_html_dir}/issue_deleted.html")
    +    self.create(type: 'MessageTemplate::IssueDeleted', sys_notice: '{nickname}已将易修 {title} 删除', email: email_html, email_title: '易修 {title} 有状态变更', notification_url: '')
         self.create(type: 'MessageTemplate::IssueJournal', sys_notice: '{nickname}评论易修{title}:{notes}', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}')
         self.create(type: 'MessageTemplate::LoginIpTip', sys_notice: '您的账号{nickname}于{login_time)在非常用的IP地址{ip}登录,如非本人操作,请立即修改密码', notification_url: '')
         email_html = File.read("#{email_template_html_dir}/organization_joined.html")
         self.create(type: 'MessageTemplate::OrganizationJoined', sys_notice: '你已加入 {organization} 组织', notification_url: '{baseurl}/{login}', email: email_html, email_title: '你已加入 {organization} 组织')
         email_html = File.read("#{email_template_html_dir}/organization_left.html")
         self.create(type: 'MessageTemplate::OrganizationLeft', sys_notice: '你已被移出 {organization} 组织', notification_url: '', email: email_html, email_title: '你已被移出 {organization} 组织')
    -    self.create(type: 'MessageTemplate::OrganizationRole', sys_notice: '组织 {organization} 已把你的角色改为 {role}', notification_url: '{baseurl}/{login}')
    +    email_html = File.read("#{email_template_html_dir}/organization_role.html")
    +    self.create(type: 'MessageTemplate::OrganizationRole', sys_notice: '组织 {organization} 已把你的角色改为 {role}', email: email_html, email_title: '在 {organization} 组织你的账号有权限变更', notification_url: '{baseurl}/{login}')
         self.create(type: 'MessageTemplate::ProjectDeleted', sys_notice: '你关注的仓库{nickname}/{repository}已被删除', notification_url: '')
         self.create(type: 'MessageTemplate::ProjectFollowed', sys_notice: '{nickname} 关注了你管理的仓库', notification_url: '{baseurl}/{login}')
         self.create(type: 'MessageTemplate::ProjectForked', sys_notice: '{nickname1} 复刻了你管理的仓库{nickname1}/{repository1}到{nickname2}/{repository2}', notification_url: '{baseurl}/{owner}/{identifier}')
    @@ -46,19 +49,23 @@ class MessageTemplate < ApplicationRecord
         self.create(type: 'MessageTemplate::ProjectMilestone', sys_notice: '{nickname1}在 {nickname2}/{repository} 创建了一个里程碑:{title}', notification_url: '{baseurl}/{owner}/{identifier}/milestones/{id}')
         self.create(type: 'MessageTemplate::ProjectPraised', sys_notice: '{nickname} 点赞了你管理的仓库', notification_url: '{baseurl}/{login}')
         email_html = File.read("#{email_template_html_dir}/project_pull_request.html")
    -    self.create(type: 'MessageTemplate::ProjectPullRequest', sys_notice: '{nickname1}在 {nickname2}/{repository} 提交了一个合并请求:{title}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount', email: email_html, email_title: '{nickname1} 在 {nickname2}/{repository} 提交了一个合并请求')
    -    self.create(type: 'MessageTemplate::ProjectRole', sys_notice: '仓库 {repository} 已把你的角色改为 {role}', notification_url: '{baseurl}/{owner}/{identifier}')
    +    self.create(type: 'MessageTemplate::ProjectPullRequest', sys_notice: '{nickname1}在 {nickname2}/{repository} 提交了一个合并请求:{title}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}', email: email_html, email_title: '{nickname1} 在 {nickname2}/{repository} 提交了一个合并请求')
    +    email_html = File.read("#{email_template_html_dir}/project_role.html")
    +    self.create(type: 'MessageTemplate::ProjectRole', sys_notice: '仓库 {nickname}/{repository} 已把你的角色改为 {role}', email: email_html, email_title: '在 {nickname}/{repository} 项目你的账号有权限变更', notification_url: '{baseurl}/{owner}/{identifier}')
         email_html = File.read("#{email_template_html_dir}/project_setting_changed.html")
         self.create(type: 'MessageTemplate::ProjectSettingChanged', sys_notice: '{nickname1}更改了 {nickname2}/{repository} 仓库设置:{ifname}更改项目名称为"{name}"{endname}{ifdescription}更改项目简介为"{description}"{enddescription}{ifcategory}更改项目类别为"{category}"{endcategory}{iflanguage}更改项目语言为"{language}"{endlanguage}{ifpermission}将仓库设为"{permission}"{endpermission}{ifnavbar}将项目导航更改为"{navbar}"{endnavbar}', notification_url: '{baseurl}/{owner}/{identifier}/settings', email: email_html, email_title: '您管理的仓库 {nickname2}/{repository} 仓库设置已被更改')
         self.create(type: 'MessageTemplate::ProjectTransfer', sys_notice: '你关注的仓库{nickname1}/{repository1}已被转移至{nickname2}/{repository2}', notification_url: '{baseurl}/{owner}/{identifier}')
         self.create(type: 'MessageTemplate::ProjectVersion', sys_notice: '{nickname1}在 {nickname2}/{repository} 创建了发行版:{title}', notification_url: '{baseurl}/{owner}/{identifier}/releases')
         email_html = File.read("#{email_template_html_dir}/pull_request_assigned.html")
    -    self.create(type: 'MessageTemplate::PullRequestAssigned', sys_notice: '{nickname1}在 {nickname2}/{repository} 指派给你一个合并请求:{title}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount', email: email_html, email_title: '{nickname1} 在 {nickname2}/{repository} 指派给你一个合并请求')
    -    self.create(type: 'MessageTemplate::PullRequestAtme', sys_notice: '{nickname} 在合并请求 {title} 中@我', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount')
    -    self.create(type: 'MessageTemplate::PullRequestChanged', sys_notice: '在项目{nickname2}/{repository}的合并请求 {title} 中:{ifassigner}{nickname1}将审查成员从 {assigner1} 修改为 {assigner2} {endassigner}{ifmilestone}{nickname1}将里程碑从 {milestone1} 修改为 {milestone2} {endmilestone}{iftag}{nickname1}将标记从 {tag1} 修改为 {tag2} {endtag}{ifpriority}{nickname1}将优先级从 {priority1} 修改为 {priority2} {endpriority}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount')
    -    self.create(type: 'MessageTemplate::PullRequestClosed', sys_notice: '你提交的合并请求:{title} 被拒绝', notification_url: '')
    -    self.create(type: 'MessageTemplate::PullRequestJournal', sys_notice: '{nickname}评论合并请求{title}:{notes}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount')
    -    self.create(type: 'MessageTemplate::PullRequestMerged', sys_notice: '你提交的合并请求:{title} 已通过', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}/Messagecount')
    +    self.create(type: 'MessageTemplate::PullRequestAssigned', sys_notice: '{nickname1}在 {nickname2}/{repository} 指派给你一个合并请求:{title}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}', email: email_html, email_title: '{nickname1} 在 {nickname2}/{repository} 指派给你一个合并请求')
    +    self.create(type: 'MessageTemplate::PullRequestAtme', sys_notice: '{nickname} 在合并请求 {title} 中@我', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}')
    +    email_html = File.read("#{email_template_html_dir}/pull_request_changed.html")
    +    self.create(type: 'MessageTemplate::PullRequestChanged', sys_notice: '在项目{nickname2}/{repository}的合并请求 {title} 中:{ifassigner}{nickname1}将审查成员从 {assigner1} 修改为 {assigner2} {endassigner}{ifmilestone}{nickname1}将里程碑从 {milestone1} 修改为 {milestone2} {endmilestone}{iftag}{nickname1}将标记从 {tag1} 修改为 {tag2} {endtag}{ifpriority}{nickname1}将优先级从 {priority1} 修改为 {priority2} {endpriority}', email: email_html, email_title: '合并请求 {title} 有状态变更', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}')
    +    email_html = File.read("#{email_template_html_dir}/pull_request_closed.html")
    +    self.create(type: 'MessageTemplate::PullRequestClosed', sys_notice: '你提交的合并请求:{title} 被拒绝', email: email_html, email_title: '合并请求 {title} 有状态变更', notification_url: '')
    +    self.create(type: 'MessageTemplate::PullRequestJournal', sys_notice: '{nickname}评论合并请求{title}:{notes}', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}')
    +    email_html = File.read("#{email_template_html_dir}/pull_request_merged.html")
    +    self.create(type: 'MessageTemplate::PullRequestMerged', sys_notice: '你提交的合并请求:{title} 已通过', email: email_html, email_title: '合并请求 {title} 有状态变更', notification_url: '{baseurl}/{owner}/{identifier}/pulls/{id}')
       end
     
       def self.sys_notice
    diff --git a/app/models/message_template/issue_changed.rb b/app/models/message_template/issue_changed.rb
    index 6b9e7976..7edc8f05 100644
    --- a/app/models/message_template/issue_changed.rb
    +++ b/app/models/message_template/issue_changed.rb
    @@ -17,6 +17,12 @@ class MessageTemplate::IssueChanged < MessageTemplate
     
       # MessageTemplate::IssueChanged.get_message_content(User.where(login: 'yystopf'), User.last, Issue.last, {status_id: [1, 2], assigned_to_id: [nil, 203], tracker_id: [4, 3], priority_id: [2, 4], fixed_version_id: [nil, 5], due_date: ['', '2021-09-11'], done_ratio: [0, 40], issue_tags_value: ["", "7"], branch_name: ["", "master"]})
       def self.get_message_content(receivers, operator, issue, change_params) 
    +    receivers.each do |receiver|
    +      if receiver.user_template_message_setting.present? 
    +        receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["CreateOrAssign::IssueChanged"]
    +      end
    +    end
    +    return '', '', '' if receivers.blank?
         return '', '', '' if change_params.blank?
         project = issue&.project 
         owner = project&.owner 
    @@ -180,4 +186,183 @@ class MessageTemplate::IssueChanged < MessageTemplate
         Rails.logger.info("MessageTemplate::IssueAssigned.get_message_content [ERROR] #{e}")
         return '', '', ''
       end
    +
    +  def self.get_email_message_content(receiver, operator, issue, change_params)
    +    if receiver.user_template_message_setting.present? 
    +      return '', '', '' unless receiver.user_template_message_setting.email_body["CreateOrAssign::IssueChanged"]
    +    end
    +    project = issue&.project
    +    owner = project&.owner 
    +    title = email_title
    +    title.gsub!('{title}', issue&.subject)
    +    content = email
    +    content.gsub!('{receiver}', receiver&.real_name)
    +    content.gsub!('{baseurl}', base_url)
    +    content.gsub!('{login1}', operator&.login)
    +    content.gsub!('{nickname1}', operator&.real_name)
    +    content.gsub!('{login2}', owner&.login)
    +    content.gsub!('{nickname2}', owner&.real_name)
    +    content.gsub!('{identifier}', project&.identifier)
    +    content.gsub!('{repository}', project&.name)
    +    content.gsub!('{title}', issue&.subject)
    +    content.gsub!('{id}', issue&.id.to_s)
    +    change_count = change_params.keys.size
    +    # 易修负责人修改
    +    if change_params[:assigned_to_id].present?
    +      assigner1 = User.find_by_id(change_params[:assigned_to_id][0])
    +      assigner2 = User.find_by_id(change_params[:assigned_to_id][1])
    +      if change_count > 1
    +        content.sub!('{ifassigner}', '
    ') + else + content.sub!('{ifassigner}', '') + end + content.sub!('{endassigner}', '') + content.gsub!('{assigner1}', assigner1.present? ? assigner1&.real_name : '未指派成员') + content.gsub!('{assigner2}', assigner2.present? ? assigner2&.real_name : '未指派成员') + else + content.gsub!(/({ifassigner})(.*)({endassigner})/, '') + end + # 易修状态修改 + if change_params[:status_id].present? + status1 = IssueStatus.find_by_id(change_params[:status_id][0]) + status2 = IssueStatus.find_by_id(change_params[:status_id][1]) + if change_count > 1 + content.sub!('{ifstatus}', '
    ') + else + content.sub!('{ifstatus}', '') + end + content.sub!('{endstatus}', '') + content.gsub!('{status1}', status1&.name) + content.gsub!('{status2}', status2&.name) + else + content.gsub!(/({ifstatus})(.*)({endstatus})/, '') + end + # 易修类型修改 + if change_params[:tracker_id].present? + tracker1 = Tracker.find_by_id(change_params[:tracker_id][0]) + tracker2 = Tracker.find_by_id(change_params[:tracker_id][1]) + if change_count > 1 + content.sub!('{iftracker}', '
    ') + else + content.sub!('{iftracker}', '') + end + content.sub!('{endtracker}', '') + content.gsub!('{tracker1}', tracker1&.name) + content.gsub!('{tracker2}', tracker2&.name) + else + content.gsub!(/({iftracker})(.*)({endtracker})/, '') + end + # 易修里程碑修改 + if change_params[:fixed_version_id].present? + fix_version1 = Version.find_by_id(change_params[:fixed_version_id][0]) + fix_version2 = Version.find_by_id(change_params[:fixed_version_id][1]) + if change_count > 1 + content.sub!('{ifmilestone}', '
    ') + else + content.sub!('{ifmilestone}', '') + end + content.sub!('{endmilestone}', '') + content.gsub!('{milestone1}', fix_version1.present? ? fix_version1&.name : '未选择里程碑') + content.gsub!('{milestone2}', fix_version2.present? ? fix_version2&.name : '未选择里程碑') + else + content.gsub!(/({ifmilestone})(.*)({endmilestone})/, '') + end + # 易修标记修改 + if change_params[:issue_tags_value].present? + issue_tags1 = IssueTag.where(id: change_params[:issue_tags_value][0]).distinct + issue_tags2 = IssueTag.where(id: change_params[:issue_tags_value][1]).distinct + tag1 = issue_tags1.pluck(:name).join(",").blank? ? '未选择标记' : issue_tags1.pluck(:name).join(",") + tag2 = issue_tags2.pluck(:name).join(",").blank? ? '未选择标记' : issue_tags2.pluck(:name).join(",") + if change_count > 1 + content.sub!('{iftag}', '
    ') + else + content.sub!('{iftag}', '') + end + content.sub!('{endtag}', '') + content.gsub!('{tag1}', tag1) + content.gsub!('{tag2}', tag2) + else + content.gsub!(/({iftag})(.*)({endtag})()/, '') + end + # 易修优先级修改 + if change_params[:priority_id].present? + priority1 = IssuePriority.find_by_id(change_params[:priority_id][0]) + priority2 = IssuePriority.find_by_id(change_params[:priority_id][1]) + if change_count > 1 + content.sub!('{ifpriority}', '
    ') + else + content.sub!('{ifpriority}', '') + end + content.sub!('{endpriority}', '') + content.gsub!('{priority1}', priority1&.name) + content.gsub!('{priority2}', priority2&.name) + else + content.gsub!(/({ifpriority})(.*)({endpriority})/, '') + end + # 易修完成度修改 + if change_params[:done_ratio].present? + doneratio1 = change_params[:done_ratio][0] + doneratio2 = change_params[:done_ratio][1] + if change_count > 1 + content.sub!('{ifdoneratio}', '
    ') + else + content.sub!('{ifdoneratio}', '') + end + content.sub!('{enddoneratio}', '') + content.gsub!('{doneratio1}', "#{doneratio1}%") + content.gsub!('{doneratio2}', "#{doneratio2}%") + else + content.gsub!(/({ifdoneratio})(.*)({enddoneratio})/, '') + end + # 易修指定分支修改 + if change_params[:branch_name].present? + branch1 = change_params[:branch_name][0].blank? ? '分支未指定' : change_params[:branch_name][0] + branch2 = change_params[:branch_name][1].blank? ? '分支未指定' : change_params[:branch_name][1] + if change_count > 1 + content.sub!('{ifbranch}', '
    ') + else + content.sub!('{ifbranch}', '') + end + content.sub!('{endbranch}', '') + content.gsub!('{branch1}', branch1) + content.gsub!('{branch2}', branch2) + else + content.gsub!(/({ifbranch})(.*)({endbranch})/, '') + end + # 易修开始日期修改 + if change_params[:start_date].present? + startdate1 = change_params[:start_date][0].blank? ? "未选择开始日期" : change_params[:start_date][0] + startdate2 = change_params[:start_date][1].blank? ? "未选择开始日期" : change_params[:start_date][1] + if change_count > 1 + content.sub!('{ifstartdate}', '
    ') + else + content.sub!('{ifstartdate}', '') + end + content.sub!('{endstartdate}', '') + content.gsub!('{startdate1}', startdate1 ) + content.gsub!('{startdate2}', startdate2) + else + content.gsub!(/({ifstartdate})(.*)({endstartdate})/, '') + end + # 易修结束日期修改 + if change_params[:due_date].present? + duedate1 = change_params[:due_date][0].blank? ? '未选择结束日期' : change_params[:due_date][0] + duedate2 = change_params[:due_date][1].blank? ? '未选择结束日期' : change_params[:due_date][1] + if change_count > 1 + content.sub!('{ifduedate}', '
    ') + else + content.sub!('{ifduedate}', '') + end + content.sub!('{endduedate}', '') + content.gsub!('{duedate1}', duedate1) + content.gsub!('{duedate2}', duedate2) + else + content.gsub!(/({ifduedate})(.*)({endduedate})/, '') + end + + return receiver&.mail, title, content + rescue => e + Rails.logger.info("MessageTemplate::IssueChanged.get_email_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/issue_deleted.rb b/app/models/message_template/issue_deleted.rb index 8c414571..c08ee043 100644 --- a/app/models/message_template/issue_deleted.rb +++ b/app/models/message_template/issue_deleted.rb @@ -17,10 +17,35 @@ class MessageTemplate::IssueDeleted < MessageTemplate # MessageTemplate::IssueDeleted.get_message_content(User.where(login: 'yystopf'), User.last, "hahah") def self.get_message_content(receivers, operator, issue_title) + receivers.each do |receiver| + if receiver.user_template_message_setting.present? + receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["CreateOrAssign::IssueChanged"] + end + end + return '', '', '' if receivers.blank? content = sys_notice.gsub('{nickname}', operator&.real_name).gsub('{title}', issue_title) return receivers_string(receivers), content, notification_url rescue => e - Rails.logger.info("MessageTemplate::IssueAtme.get_message_content [ERROR] #{e}") + Rails.logger.info("MessageTemplate::IssueDeleted.get_message_content [ERROR] #{e}") + return '', '', '' + end + + def self.get_email_message_content(receiver, operator, issue_title) + if receiver.user_template_message_setting.present? + return '', '', '' unless receiver.user_template_message_setting.email_body["CreateOrAssign::IssueChanged"] + end + title = email_title + title.gsub!('{title}', issue_title) + content = email + content.gsub!('{receiver}', receiver&.real_name) + content.gsub!('{nickname}', operator&.real_name) + content.gsub!('{login}', operator&.login) + content.gsub!('{baseurl}', base_url) + content.gsub!('{title}', issue_title) + + return receiver&.mail, title, content + rescue => e + Rails.logger.info("MessageTemplate::IssueDeleted.get_email_message_content [ERROR] #{e}") return '', '', '' end end diff --git a/app/models/message_template/project_role.rb b/app/models/message_template/project_role.rb index 6cb88ab8..e1ced084 100644 --- a/app/models/message_template/project_role.rb +++ b/app/models/message_template/project_role.rb @@ -38,10 +38,12 @@ class MessageTemplate::ProjectRole < MessageTemplate title = email_title title.gsub!('{repository}', project&.name) title.gsub!('{role}', role) + title.gsub!('{nickname}', project&.owner&.real_name) content = email content.gsub!('{receiver}', receiver&.real_name) content.gsub!('{baseurl}', base_url) content.gsub!('{login}', project&.owner&.login) + content.gsub!('{nickname}', project&.owner&.real_name) content.gsub!('{identifier}', project&.identifier) content.gsub!('{repository}', project&.name) content.gsub!('{role}', role) diff --git a/app/models/message_template/pull_request_changed.rb b/app/models/message_template/pull_request_changed.rb index 099607fb..729e1206 100644 --- a/app/models/message_template/pull_request_changed.rb +++ b/app/models/message_template/pull_request_changed.rb @@ -17,6 +17,12 @@ class MessageTemplate::PullRequestChanged < MessageTemplate # MessageTemplate::PullRequestChanged.get_message_content(User.where(login: 'yystopf'), User.last, PullRequest.last, {assigned_to_id: [nil, 203], priority_id: [2, 4], fixed_version_id: [nil, 5], issue_tags_value: ["", "7"]}) def self.get_message_content(receivers, operator, pull_request, change_params) + receivers.each do |receiver| + if receiver.user_template_message_setting.present? + receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["CreateOrAssign::PullRequestChanged"] + end + end + return '', '', '' if receivers.blank? return '', '', '' if change_params.blank? project = pull_request&.project owner = project&.owner @@ -92,4 +98,95 @@ class MessageTemplate::PullRequestChanged < MessageTemplate Rails.logger.info("MessageTemplate::PullRequestChanged.get_message_content [ERROR] #{e}") return '', '', '' end + + def self.get_email_message_content(receiver, operator, pull_request, change_params) + if receiver.user_template_message_setting.present? + return '', '', '' unless receiver.user_template_message_setting.email_body["CreateOrAssign::PullRequestChanged"] + end + project = pull_request&.project + owner = project&.owner + title = email_title + title.gsub!('{title}', pull_request&.title) + content = email + content.gsub!('{receiver}', receiver&.real_name) + content.gsub!('{nickname1}', operator&.real_name) + content.gsub!('{login1}', operator&.login) + content.gsub!('{nickname2}', owner&.real_name) + content.gsub!('{login2}', owner&.login) + content.gsub!('{identifier}', project&.identifier) + content.gsub!('{repository}', project&.name) + content.gsub!('{baseurl}', base_url) + content.gsub!('{title}', pull_request&.title) + content.gsub!('{id}', pull_request&.id.to_s) + + change_count = change_params.keys.size + # 合并请求审查成员修改 + if change_params[:assigned_to_id].present? + assigner1 = User.find_by_id(change_params[:assigned_to_id][0]) + assigner2 = User.find_by_id(change_params[:assigned_to_id][1]) + if change_count > 1 + content.sub!('{ifassigner}', '
    ') + else + content.sub!('{ifassigner}', '') + end + content.sub!('{endassigner}', '') + content.gsub!('{assigner1}', assigner1.present? ? assigner1&.real_name : '未指派成员') + content.gsub!('{assigner2}', assigner2.present? ? assigner2&.real_name : '未指派成员') + else + content.gsub!(/({ifassigner})(.*)({endassigner})/, '') + end + # 合并请求里程碑修改 + if change_params[:fixed_version_id].present? + fix_version1 = Version.find_by_id(change_params[:fixed_version_id][0]) + fix_version2 = Version.find_by_id(change_params[:fixed_version_id][1]) + if change_count > 1 + content.sub!('{ifmilestone}', '
    ') + else + content.sub!('{ifmilestone}', '') + end + content.sub!('{endmilestone}', '') + content.gsub!('{milestone1}', fix_version1.present? ? fix_version1&.name : '未选择里程碑') + content.gsub!('{milestone2}', fix_version2.present? ? fix_version2&.name : '未选择里程碑') + else + content.gsub!(/({ifmilestone})(.*)({endmilestone})/, '') + end + # 合并请求标记修改 + if change_params[:issue_tags_value].present? + issue_tags1 = IssueTag.where(id: change_params[:issue_tags_value][0]).distinct + issue_tags2 = IssueTag.where(id: change_params[:issue_tags_value][1]).distinct + tag1 = issue_tags1.pluck(:name).join(",").blank? ? '未选择标记' : issue_tags1.pluck(:name).join(",") + tag2 = issue_tags2.pluck(:name).join(",").blank? ? '未选择标记' : issue_tags2.pluck(:name).join(",") + if change_count > 1 + content.sub!('{iftag}', '
    ') + else + content.sub!('{iftag}', '') + end + content.sub!('{endtag}', '') + content.gsub!('{tag1}', tag1) + content.gsub!('{tag2}', tag2) + else + content.gsub!(/({iftag})(.*)({endtag})()/, '') + end + # 合并请求优先级修改 + if change_params[:priority_id].present? + priority1 = IssuePriority.find_by_id(change_params[:priority_id][0]) + priority2 = IssuePriority.find_by_id(change_params[:priority_id][1]) + if change_count > 1 + content.sub!('{ifpriority}', '
    ') + else + content.sub!('{ifpriority}', '') + end + content.sub!('{ifpriority}', '') + content.sub!('{endpriority}', '') + content.gsub!('{priority1}', priority1&.name) + content.gsub!('{priority2}', priority2&.name) + else + content.gsub!(/({ifpriority})(.*)({endpriority})/, '') + end + + return receiver&.mail, title, content + rescue => e + Rails.logger.info("MessageTemplate::PullRequestChanged.get_email_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/pull_request_closed.rb b/app/models/message_template/pull_request_closed.rb index 6ebb23a6..f160ebf2 100644 --- a/app/models/message_template/pull_request_closed.rb +++ b/app/models/message_template/pull_request_closed.rb @@ -17,6 +17,12 @@ class MessageTemplate::PullRequestClosed < MessageTemplate # MessageTemplate::PullRequestClosed.get_message_content(User.where(login: 'yystopf'), User.last, PullRequest.last) def self.get_message_content(receivers, operator, pull_request) + receivers.each do |receiver| + if receiver.user_template_message_setting.present? + receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["CreateOrAssign::PullRequestChanged"] + end + end + return '', '', '' if receivers.blank? project = pull_request&.project owner = project&.owner content = sys_notice.gsub('{title}', pull_request&.title) @@ -26,4 +32,30 @@ class MessageTemplate::PullRequestClosed < MessageTemplate Rails.logger.info("MessageTemplate::PullRequestClosed.get_message_content [ERROR] #{e}") return '', '', '' end + + def self.get_email_message_content(receiver, operator, pull_request) + if receiver.user_template_message_setting.present? + return '', '', '' unless receiver.user_template_message_setting.email_body["CreateOrAssign::PullRequestChanged"] + end + project = pull_request&.project + owner = project&.owner + title = email_title + title.gsub!('{title}', pull_request&.title) + content = email + content.gsub!('{receiver}', receiver&.real_name) + content.gsub!('{nickname1}', operator&.real_name) + content.gsub!('{login1}', operator&.login) + content.gsub!('{nickname2}', owner&.real_name) + content.gsub!('{login2}', owner&.login) + content.gsub!('{identifier}', project&.identifier) + content.gsub!('{repository}', project&.name) + content.gsub!('{baseurl}', base_url) + content.gsub!('{title}', pull_request&.title) + content.gsub!('{id}', pull_request&.id.to_s) + + return receiver&.mail, title, content + rescue => e + Rails.logger.info("MessageTemplate::PullRequestClosed.get_email_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/message_template/pull_request_merged.rb b/app/models/message_template/pull_request_merged.rb index 8df4255a..3dccffdd 100644 --- a/app/models/message_template/pull_request_merged.rb +++ b/app/models/message_template/pull_request_merged.rb @@ -17,6 +17,12 @@ class MessageTemplate::PullRequestMerged < MessageTemplate # MessageTemplate::PullRequestMerged.get_message_content(User.where(login: 'yystopf'), User.last, PullRequest.last) def self.get_message_content(receivers, operator, pull_request) + receivers.each do |receiver| + if receiver.user_template_message_setting.present? + receivers = receivers.where.not(id: receiver.id) unless receiver.user_template_message_setting.notification_body["CreateOrAssign::PullRequestChanged"] + end + end + return '', '', '' if receivers.blank? project = pull_request&.project owner = project&.owner content = sys_notice.gsub('{title}', pull_request&.title) @@ -26,4 +32,30 @@ class MessageTemplate::PullRequestMerged < MessageTemplate Rails.logger.info("MessageTemplate::PullRequestMerged.get_message_content [ERROR] #{e}") return '', '', '' end + + def self.get_email_message_content(receiver, operator, pull_request) + if receiver.user_template_message_setting.present? + return '', '', '' unless receiver.user_template_message_setting.email_body["CreateOrAssign::PullRequestChanged"] + end + project = pull_request&.project + owner = project&.owner + title = email_title + title.gsub!('{title}', pull_request&.title) + content = email + content.gsub!('{receiver}', receiver&.real_name) + content.gsub!('{nickname1}', operator&.real_name) + content.gsub!('{login1}', operator&.login) + content.gsub!('{nickname2}', owner&.real_name) + content.gsub!('{login2}', owner&.login) + content.gsub!('{identifier}', project&.identifier) + content.gsub!('{repository}', project&.name) + content.gsub!('{baseurl}', base_url) + content.gsub!('{title}', pull_request&.title) + content.gsub!('{id}', pull_request&.id.to_s) + + return receiver&.mail, title, content + rescue => e + Rails.logger.info("MessageTemplate::PullRequestMerged.get_email_message_content [ERROR] #{e}") + return '', '', '' + end end diff --git a/app/models/template_message_setting/create_or_assign.rb b/app/models/template_message_setting/create_or_assign.rb index 54f84240..2c9fa207 100644 --- a/app/models/template_message_setting/create_or_assign.rb +++ b/app/models/template_message_setting/create_or_assign.rb @@ -25,6 +25,7 @@ class TemplateMessageSetting::CreateOrAssign < TemplateMessageSetting end def self.build_init_data - + self.find_or_create_by(name: "易修状态变更", key: "IssueChanged") + self.find_or_create_by(name: "合并请求状态变更", key: "PullRequestChanged") end end diff --git a/app/models/template_message_setting/normal.rb b/app/models/template_message_setting/normal.rb index 44ed3561..9090196d 100644 --- a/app/models/template_message_setting/normal.rb +++ b/app/models/template_message_setting/normal.rb @@ -24,7 +24,7 @@ class TemplateMessageSetting::Normal < TemplateMessageSetting end def self.build_init_data - # self.find_or_create_by(name: "账号有权限变更", key: "Permission") + self.find_or_create_by(name: "账号有权限变更", key: "Permission") self.find_or_create_by(name: "被拉入或移出组织", key: "Organization") self.find_or_create_by(name: "被拉入或移出项目", key: "Project") self.find_or_create_by(name: "有新的易修指派给我", key: "IssueAssigned") diff --git a/app/models/user_template_message_setting.rb b/app/models/user_template_message_setting.rb index 7b7f8cb8..c581e626 100644 --- a/app/models/user_template_message_setting.rb +++ b/app/models/user_template_message_setting.rb @@ -28,11 +28,13 @@ class UserTemplateMessageSetting < ApplicationRecord def self.init_notification_body { - # "Normal::Permission": true, + "Normal::Permission": true, "Normal::Project": true, "Normal::Organization": true, "Normal::IssueAssigned": true, "Normal::PullRequestAssigned": true, + "CreateOrAssign::IssueChanged": true, + "CreateOrAssign::PullRequestChanged": true, "ManageProject::Issue": true, "ManageProject::PullRequest": true, "ManageProject::Member": true, @@ -42,11 +44,13 @@ class UserTemplateMessageSetting < ApplicationRecord def self.init_email_body { - # "Normal::Permission": true, + "Normal::Permission": true, "Normal::Project": true, "Normal::Organization": true, "Normal::IssueAssigned": true, "Normal::PullRequestAssigned": true, + "CreateOrAssign::IssueChanged": true, + "CreateOrAssign::PullRequestChanged": true, "ManageProject::Issue": true, "ManageProject::PullRequest": true, "ManageProject::Member": true, diff --git a/public/message_template/issue_changed.html b/public/message_template/issue_changed.html new file mode 100755 index 00000000..ed3bbbe5 --- /dev/null +++ b/public/message_template/issue_changed.html @@ -0,0 +1,62 @@ + + + 有新的易修指派给我 + + + + +
    +
    +
    + +

    确实让创新更美好

    +
    +
    +
    +

    + {receiver},您好!
    + 在项目 {nickname2}/{repository} 的易修 {title} 中: + {ifassigner}{nickname1}将负责人从 {assigner1} 修改为 {assigner2}{endassigner} + {ifstatus}{nickname1}将状态从 {status1} 修改为 {status2}{endstatus} + {iftracker}{nickname1}将类型从 {tracker1} 修改为 {tracker2}{endtracker} + {ifpriority}{nickname1}将优先级从 {priority1} 修改为 {priority2}{endpriority} + {ifmilestone}{nickname1}将里程碑从 {milestone1} 修改为 {milestone2}{endmilestone} + {iftag}{nickname1}将标记从 {tag1} 修改为 {tag2}{endtag} + {ifdoneratio}{nickname1}将完成度从 {doneratio1} 修改为 {doneratio2}{enddoneratio} + {ifbranch}{nickname1}将指定分支从 {branch1} 修改为 {branch2}{endbranch} + {ifstartdate}{nickname1}将开始日期从 {startdate1} 修改为 {startdate2}{endstartdate} + {ifduedate}{nickname1}将结束日期从 {duedate1} 修改为 {duedate2}{endduedate} +

    +
    + +

    + 扫一扫,关注trustie微信公众号,更方便获取平台动态,消息推送等提醒
    + 想了解更多信息,请访问 www.trustie.net +

    +
    +
    +

    如果您在使用中有任何的疑问和建议,欢迎您给我们反馈意见
    + QQ群:1071514693

    +

    Trustie团队

    +
    +
    +
    +
    + + \ No newline at end of file diff --git a/public/message_template/issue_deleted.html b/public/message_template/issue_deleted.html new file mode 100755 index 00000000..1eb40c81 --- /dev/null +++ b/public/message_template/issue_deleted.html @@ -0,0 +1,52 @@ + + + 易修状态改变 + + + + +
    +
    +
    + +

    确实让创新更美好

    +
    +
    +
    +

    + {receiver},您好!
    + {nickname}已将易修 {title} 删除 +

    +
    + +

    + 扫一扫,关注trustie微信公众号,更方便获取平台动态,消息推送等提醒
    + 想了解更多信息,请访问 www.trustie.net +

    +
    +
    +

    如果您在使用中有任何的疑问和建议,欢迎您给我们反馈意见
    + QQ群:1071514693

    +

    Trustie团队

    +
    +
    +
    +
    + + \ No newline at end of file diff --git a/public/message_template/organization_role.html b/public/message_template/organization_role.html new file mode 100755 index 00000000..661698b8 --- /dev/null +++ b/public/message_template/organization_role.html @@ -0,0 +1,52 @@ + + + 组织权限被更改 + + + + +
    +
    +
    + +

    确实让创新更美好

    +
    +
    +
    +

    + {receiver},您好!
    + 组织 {organization} 已把你的角色修改为 {role} +

    +
    + +

    + 扫一扫,关注trustie微信公众号,更方便获取平台动态,消息推送等提醒
    + 想了解更多信息,请访问 www.trustie.net +

    +
    +
    +

    如果您在使用中有任何的疑问和建议,欢迎您给我们反馈意见
    + QQ群:1071514693

    +

    Trustie团队

    +
    +
    +
    +
    + + \ No newline at end of file diff --git a/public/message_template/project_pull_request.html b/public/message_template/project_pull_request.html index 0f75e0b8..c342894b 100755 --- a/public/message_template/project_pull_request.html +++ b/public/message_template/project_pull_request.html @@ -31,7 +31,7 @@

    {receiver},您好!
    - {nickname1}在 {nickname2}/{repository} 提交了一个合并请求:{title}
    + {nickname1}在 {nickname2}/{repository} 提交了一个合并请求:{title}

    diff --git a/public/message_template/project_role.html b/public/message_template/project_role.html new file mode 100755 index 00000000..db64a4f7 --- /dev/null +++ b/public/message_template/project_role.html @@ -0,0 +1,52 @@ + + + 移出项目 + + + + +
    +
    +
    + +

    确实让创新更美好

    +
    +
    +
    +

    + {receiver},您好!
    + 项目 {nickname}/{repository} 已把你的角色修改为 {role} +

    +
    + +

    + 扫一扫,关注trustie微信公众号,更方便获取平台动态,消息推送等提醒
    + 想了解更多信息,请访问 www.trustie.net +

    +
    +
    +

    如果您在使用中有任何的疑问和建议,欢迎您给我们反馈意见
    + QQ群:1071514693

    +

    Trustie团队

    +
    +
    +
    +
    + + \ No newline at end of file diff --git a/public/message_template/pull_request_assigned.html b/public/message_template/pull_request_assigned.html index 3898336e..fe139ec1 100755 --- a/public/message_template/pull_request_assigned.html +++ b/public/message_template/pull_request_assigned.html @@ -31,7 +31,7 @@

    {receiver},您好!
    - {nickname1}在 {nickname2}/{repository} 指派给你一个合并请求:{title}
    + {nickname1}在 {nickname2}/{repository} 指派给你一个合并请求:{title}

    diff --git a/public/message_template/pull_request_changed.html b/public/message_template/pull_request_changed.html new file mode 100755 index 00000000..4e6e4eac --- /dev/null +++ b/public/message_template/pull_request_changed.html @@ -0,0 +1,56 @@ + + + 合并请求被更改 + + + + +
    +
    +
    + +

    确实让创新更美好

    +
    +
    +
    +

    + {receiver},您好!
    + 在项目 {nickname2}/{repository} 的合并请求 {title} 中: + {ifassigner}{nickname1}将负责人从 {assigner1} 修改为 {assigner2}{endassigner} + {ifmilestone}{nickname1}将里程碑从 {milestone1} 修改为 {milestone2}{endmilestone} + {iftag}{nickname1}将标记从 {tag1} 修改为 {tag2}{endtag} + {ifpriority}{nickname1}将优先级从 {priority1} 修改为 {priority2}{endpriority} +

    +
    + +

    + 扫一扫,关注trustie微信公众号,更方便获取平台动态,消息推送等提醒
    + 想了解更多信息,请访问 www.trustie.net +

    +
    +
    +

    如果您在使用中有任何的疑问和建议,欢迎您给我们反馈意见
    + QQ群:1071514693

    +

    Trustie团队

    +
    +
    +
    +
    + + \ No newline at end of file diff --git a/public/message_template/pull_request_closed.html b/public/message_template/pull_request_closed.html new file mode 100755 index 00000000..d0828c19 --- /dev/null +++ b/public/message_template/pull_request_closed.html @@ -0,0 +1,52 @@ + + + 合并请求被关闭 + + + + +
    +
    +
    + +

    确实让创新更美好

    +
    +
    +
    +

    + {receiver},您好!
    + 你提交的合并请求:{title} 被拒绝; +

    +
    + +

    + 扫一扫,关注trustie微信公众号,更方便获取平台动态,消息推送等提醒
    + 想了解更多信息,请访问 www.trustie.net +

    +
    +
    +

    如果您在使用中有任何的疑问和建议,欢迎您给我们反馈意见
    + QQ群:1071514693

    +

    Trustie团队

    +
    +
    +
    +
    + + \ No newline at end of file diff --git a/public/message_template/pull_request_merged.html b/public/message_template/pull_request_merged.html new file mode 100755 index 00000000..e1f028a7 --- /dev/null +++ b/public/message_template/pull_request_merged.html @@ -0,0 +1,52 @@ + + + 合并请求被合并 + + + + +
    +
    +
    + +

    确实让创新更美好

    +
    +
    +
    +

    + {receiver},您好!
    + 你提交的合并请求:{title} 已通过; +

    +
    + +

    + 扫一扫,关注trustie微信公众号,更方便获取平台动态,消息推送等提醒
    + 想了解更多信息,请访问 www.trustie.net +

    +
    +
    +

    如果您在使用中有任何的疑问和建议,欢迎您给我们反馈意见
    + QQ群:1071514693

    +

    Trustie团队

    +
    +
    +
    +
    + + \ No newline at end of file From 9ffe10bd5baa36e3d2801ce2aaf92fd5fe457cc3 Mon Sep 17 00:00:00 2001 From: jasder Date: Thu, 21 Oct 2021 10:48:14 +0800 Subject: [PATCH 131/135] =?UTF-8?q?FIX=20=E8=B0=83=E6=95=B4detail=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/services/repositories/detail_service.rb | 25 +++++---------------- app/views/repositories/detail.json.jbuilder | 24 ++------------------ 2 files changed, 8 insertions(+), 41 deletions(-) diff --git a/app/services/repositories/detail_service.rb b/app/services/repositories/detail_service.rb index 4b29d50a..b2e7a69e 100644 --- a/app/services/repositories/detail_service.rb +++ b/app/services/repositories/detail_service.rb @@ -10,11 +10,9 @@ class Repositories::DetailService < ApplicationService def call return { repo: repo_suitable, - release: release_suitable, - branch: branch_suitable, - tag: tag_suitable, contributor: contributor_suitable, - language: language_suitable + language: language_suitable, + branch_tag_total_count: branch_tag_total_count } rescue return { @@ -30,25 +28,14 @@ class Repositories::DetailService < ApplicationService end private + def branch_tag_total_count + Gitea::Repository::GetBranchAndTagTotalNumService.call(@owner.login, @repo.identifier, @owner.gitea_token) + end + def repo_suitable Gitea::Repository::GetService.call(@owner, @repo.identifier) end - def release_suitable - releases = Gitea::Versions::ListService.call(@owner.gitea_token, @owner.try(:login), @repo.try(:identifier), {page: 1, limit: 1}) - releases.is_a?(Hash) && releases[:status] == -1 ? [] : releases - end - - def branch_suitable - branches = Gitea::Repository::Branches::ListService.call(@owner, @repo.identifier) - branches.is_a?(Hash) && branches.key?(:status) ? [] : branches - end - - def tag_suitable - tags = Gitea::Repository::Tags::ListService.call(@owner&.gitea_token, @owner.login, @repo.identifier) - tags.is_a?(Hash) && tags[:status] == -1 ? [] : tags - end - def contributor_suitable contributors = Gitea::Repository::Contributors::GetService.call(@owner, @repo.identifier) contributors.is_a?(Hash) && contributors.key?(:status) ? [] : contributors diff --git a/app/views/repositories/detail.json.jbuilder b/app/views/repositories/detail.json.jbuilder index c0807708..c489cf47 100644 --- a/app/views/repositories/detail.json.jbuilder +++ b/app/views/repositories/detail.json.jbuilder @@ -51,28 +51,8 @@ if @result[:repo] json.private @result[:repo]['private'] end json.license_name @project.license_name -json.release_versions do - json.list @result[:release].each do |release| - forge_version = VersionRelease.find_by(version_gid: release["id"]) - json.id forge_version&.id - json.name release["name"] - json.tag_name release["tag_name"] - json.created_at format_time(release["created_at"].to_time) - end - json.total_count @repository&.version_releases.size -end -json.branches do - json.list @result[:branch].each do |branch| - json.name branch["name"] - end - json.total_count @result[:branch].size -end -json.tags do - json.list @result[:tag].each do |tag| - json.name tag["name"] - end - json.total_count @result[:tag].size -end +json.branches_count @result[:branch_tag_total_count]['branch_count'] || 0 +json.tags_count @result[:branch_tag_total_count]['tag_count'] || 0 json.contributors do total_count = @result[:contributor].size json.list @result[:contributor].each do |contributor| From 94d5565f5698e131c1220977e644f4caa80b91eb Mon Sep 17 00:00:00 2001 From: jasder Date: Thu, 21 Oct 2021 10:52:58 +0800 Subject: [PATCH 132/135] =?UTF-8?q?FIX=20=E8=B0=83=E6=95=B4detail=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E6=95=B0=E6=8D=AE[bug]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../get_branch_and_tag_total_num_service.rb | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 app/services/gitea/repository/get_branch_and_tag_total_num_service.rb diff --git a/app/services/gitea/repository/get_branch_and_tag_total_num_service.rb b/app/services/gitea/repository/get_branch_and_tag_total_num_service.rb new file mode 100644 index 00000000..0b8a5246 --- /dev/null +++ b/app/services/gitea/repository/get_branch_and_tag_total_num_service.rb @@ -0,0 +1,37 @@ + +module Gitea + module Repository + class GetBranchAndTagTotalNumService < Gitea::ClientService + attr_reader :owner, :repo, :token + + def initialize(owner, repo, token=nil) + @owner = owner + @repo = repo + @token = token + end + + def call + response = get(url, params) + render_result(response) + end + + private + def params + Hash.new.merge(token: token) + end + + def url + "/repos/#{owner}/#{repo}/branch_tag_count".freeze + end + + def render_result(response) + case response.status + when 200 + JSON.parse(response.body) + else + {} + end + end + end + end +end From fdcf450eab82052da1e864a75a3baedd6f782c1b Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 21 Oct 2021 11:17:11 +0800 Subject: [PATCH 133/135] fix --- app/models/message_template.rb | 2 +- app/models/message_template/project_role.rb | 2 +- .../message_template/project_setting_changed.rb | 12 ++++++++++++ public/message_template/issue_changed.html | 2 +- public/message_template/pull_request_changed.html | 2 +- 5 files changed, 16 insertions(+), 4 deletions(-) diff --git a/app/models/message_template.rb b/app/models/message_template.rb index 8d3f622b..6cef999a 100644 --- a/app/models/message_template.rb +++ b/app/models/message_template.rb @@ -53,7 +53,7 @@ class MessageTemplate < ApplicationRecord email_html = File.read("#{email_template_html_dir}/project_role.html") self.create(type: 'MessageTemplate::ProjectRole', sys_notice: '仓库 {nickname}/{repository} 已把你的角色改为 {role}', email: email_html, email_title: '在 {nickname}/{repository} 项目你的账号有权限变更', notification_url: '{baseurl}/{owner}/{identifier}') email_html = File.read("#{email_template_html_dir}/project_setting_changed.html") - self.create(type: 'MessageTemplate::ProjectSettingChanged', sys_notice: '{nickname1}更改了 {nickname2}/{repository} 仓库设置:{ifname}更改项目名称为"{name}"{endname}{ifdescription}更改项目简介为"{description}"{enddescription}{ifcategory}更改项目类别为"{category}"{endcategory}{iflanguage}更改项目语言为"{language}"{endlanguage}{ifpermission}将仓库设为"{permission}"{endpermission}{ifnavbar}将项目导航更改为"{navbar}"{endnavbar}', notification_url: '{baseurl}/{owner}/{identifier}/settings', email: email_html, email_title: '您管理的仓库 {nickname2}/{repository} 仓库设置已被更改') + self.create(type: 'MessageTemplate::ProjectSettingChanged', sys_notice: '{nickname1}更改了 {nickname2}/{repository} 仓库设置:{ifname}更改项目名称为"{name}"{endname}{ifidentifier}更改项目名称为"{identifier}"{endidentifier}{ifdescription}更改项目简介为"{description}"{enddescription}{ifcategory}更改项目类别为"{category}"{endcategory}{iflanguage}更改项目语言为"{language}"{endlanguage}{ifpermission}将仓库设为"{permission}"{endpermission}{ifnavbar}将项目导航更改为"{navbar}"{endnavbar}', notification_url: '{baseurl}/{owner}/{identifier}/settings', email: email_html, email_title: '您管理的仓库 {nickname2}/{repository} 仓库设置已被更改') self.create(type: 'MessageTemplate::ProjectTransfer', sys_notice: '你关注的仓库{nickname1}/{repository1}已被转移至{nickname2}/{repository2}', notification_url: '{baseurl}/{owner}/{identifier}') self.create(type: 'MessageTemplate::ProjectVersion', sys_notice: '{nickname1}在 {nickname2}/{repository} 创建了发行版:{title}', notification_url: '{baseurl}/{owner}/{identifier}/releases') email_html = File.read("#{email_template_html_dir}/pull_request_assigned.html") diff --git a/app/models/message_template/project_role.rb b/app/models/message_template/project_role.rb index e1ced084..e306f5c0 100644 --- a/app/models/message_template/project_role.rb +++ b/app/models/message_template/project_role.rb @@ -23,7 +23,7 @@ class MessageTemplate::ProjectRole < MessageTemplate end end return '', '', '' if receivers.blank? - content = sys_notice.gsub('{repository}', project&.name).gsub('{role}', role) + content = sys_notice.gsub('{nickname}', project&.owner&.real_name).gsub('{repository}', project&.name).gsub('{role}', role) url = notification_url.gsub('{owner}', project&.owner&.login).gsub('{identifier}', project&.identifier) return receivers_string(receivers), content, url rescue => e diff --git a/app/models/message_template/project_setting_changed.rb b/app/models/message_template/project_setting_changed.rb index 31ac5f05..260c284d 100644 --- a/app/models/message_template/project_setting_changed.rb +++ b/app/models/message_template/project_setting_changed.rb @@ -178,6 +178,18 @@ class MessageTemplate::ProjectSettingChanged < MessageTemplate else content.gsub!(/({ifname})(.*)({endname})/, '') end + # 项目标识更改 + if change_params[:identifier].present? + if change_count > 1 + content.sub!('{ifidentifier}', '
    ') + else + content.sub!('{ifidentifier}', '') + end + content.sub!('{endidentifier}', '') + content.gsub!('{identifier}', change_params[:identifier][1]) + else + content.gsub!(/({ifidentifier})(.*)({endidentifier})/, '') + end # 项目简介更改 if change_params[:description].present? if change_params[:description][1].blank? diff --git a/public/message_template/issue_changed.html b/public/message_template/issue_changed.html index ed3bbbe5..5f8d796b 100755 --- a/public/message_template/issue_changed.html +++ b/public/message_template/issue_changed.html @@ -31,7 +31,7 @@

    {receiver},您好!
    - 在项目 {nickname2}/{repository} 的易修 {title} 中: + 在项目 {nickname2}/{repository} 的易修 {title} 中: {ifassigner}{nickname1}将负责人从 {assigner1} 修改为 {assigner2}{endassigner} {ifstatus}{nickname1}将状态从 {status1} 修改为 {status2}{endstatus} {iftracker}{nickname1}将类型从 {tracker1} 修改为 {tracker2}{endtracker} diff --git a/public/message_template/pull_request_changed.html b/public/message_template/pull_request_changed.html index 4e6e4eac..5cafdc47 100755 --- a/public/message_template/pull_request_changed.html +++ b/public/message_template/pull_request_changed.html @@ -31,7 +31,7 @@

    {receiver},您好!
    - 在项目 {nickname2}/{repository} 的合并请求 {title} 中: + 在项目 {nickname2}/{repository} 的合并请求 {title} 中: {ifassigner}{nickname1}将负责人从 {assigner1} 修改为 {assigner2}{endassigner} {ifmilestone}{nickname1}将里程碑从 {milestone1} 修改为 {milestone2}{endmilestone} {iftag}{nickname1}将标记从 {tag1} 修改为 {tag2}{endtag} From 43d125100dd4033366062d8215f13936f2dd5088 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 21 Oct 2021 11:19:12 +0800 Subject: [PATCH 134/135] fix --- app/models/message_template.rb | 2 +- public/message_template/project_setting_changed.html | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/app/models/message_template.rb b/app/models/message_template.rb index 6cef999a..bd2c68bd 100644 --- a/app/models/message_template.rb +++ b/app/models/message_template.rb @@ -53,7 +53,7 @@ class MessageTemplate < ApplicationRecord email_html = File.read("#{email_template_html_dir}/project_role.html") self.create(type: 'MessageTemplate::ProjectRole', sys_notice: '仓库 {nickname}/{repository} 已把你的角色改为 {role}', email: email_html, email_title: '在 {nickname}/{repository} 项目你的账号有权限变更', notification_url: '{baseurl}/{owner}/{identifier}') email_html = File.read("#{email_template_html_dir}/project_setting_changed.html") - self.create(type: 'MessageTemplate::ProjectSettingChanged', sys_notice: '{nickname1}更改了 {nickname2}/{repository} 仓库设置:{ifname}更改项目名称为"{name}"{endname}{ifidentifier}更改项目名称为"{identifier}"{endidentifier}{ifdescription}更改项目简介为"{description}"{enddescription}{ifcategory}更改项目类别为"{category}"{endcategory}{iflanguage}更改项目语言为"{language}"{endlanguage}{ifpermission}将仓库设为"{permission}"{endpermission}{ifnavbar}将项目导航更改为"{navbar}"{endnavbar}', notification_url: '{baseurl}/{owner}/{identifier}/settings', email: email_html, email_title: '您管理的仓库 {nickname2}/{repository} 仓库设置已被更改') + self.create(type: 'MessageTemplate::ProjectSettingChanged', sys_notice: '{nickname1}更改了 {nickname2}/{repository} 仓库设置:{ifname}更改项目名称为"{name}"{endname}{ifidentifier}更改项目标识为"{identifier}"{endidentifier}{ifdescription}更改项目简介为"{description}"{enddescription}{ifcategory}更改项目类别为"{category}"{endcategory}{iflanguage}更改项目语言为"{language}"{endlanguage}{ifpermission}将仓库设为"{permission}"{endpermission}{ifnavbar}将项目导航更改为"{navbar}"{endnavbar}', notification_url: '{baseurl}/{owner}/{identifier}/settings', email: email_html, email_title: '您管理的仓库 {nickname2}/{repository} 仓库设置已被更改') self.create(type: 'MessageTemplate::ProjectTransfer', sys_notice: '你关注的仓库{nickname1}/{repository1}已被转移至{nickname2}/{repository2}', notification_url: '{baseurl}/{owner}/{identifier}') self.create(type: 'MessageTemplate::ProjectVersion', sys_notice: '{nickname1}在 {nickname2}/{repository} 创建了发行版:{title}', notification_url: '{baseurl}/{owner}/{identifier}/releases') email_html = File.read("#{email_template_html_dir}/pull_request_assigned.html") diff --git a/public/message_template/project_setting_changed.html b/public/message_template/project_setting_changed.html index ca51e262..ef5af71f 100755 --- a/public/message_template/project_setting_changed.html +++ b/public/message_template/project_setting_changed.html @@ -33,6 +33,7 @@ {receiver},您好!
    {nickname1} 更改 {nickname2}/{repository} 的仓库设置: {ifname}更改项目名称为"{name}"{endname} + {ifidentifier}更改项目标识为"{identifier}"{endidentifier} {ifdescription}更改项目简介为"{description}"{enddescription} {ifcategory}更改项目类别为"{category}"{endcategory} {iflanguage}更改项目语言为"{language}"{endlanguage} From 24ec0398954833ecf903cf12639e20991a7073a2 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 21 Oct 2021 11:23:12 +0800 Subject: [PATCH 135/135] fix --- app/controllers/projects_controller.rb | 2 +- .../message_template/project_setting_changed.rb | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index 3c5cb1f3..1c6e9868 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -145,7 +145,7 @@ class ProjectsController < ApplicationController gitea_repo = Gitea::Repository::UpdateService.call(@owner, @project&.repository&.identifier, gitea_params) @project.repository.update_attributes({hidden: gitea_repo["private"], identifier: gitea_repo["name"]}) end - SendTemplateMessageJob.perform_later('ProjectSettingChanged', current_user.id, @project&.id, @project.previous_changes.slice(:name, :description, :project_category_id, :project_language_id, :is_public)) if Site.has_notice_menu? + SendTemplateMessageJob.perform_later('ProjectSettingChanged', current_user.id, @project&.id, @project.previous_changes.slice(:name, :description, :project_category_id, :project_language_id, :is_public, :identifier)) if Site.has_notice_menu? end rescue Exception => e uid_logger_error(e.message) diff --git a/app/models/message_template/project_setting_changed.rb b/app/models/message_template/project_setting_changed.rb index 260c284d..457ab920 100644 --- a/app/models/message_template/project_setting_changed.rb +++ b/app/models/message_template/project_setting_changed.rb @@ -40,6 +40,18 @@ class MessageTemplate::ProjectSettingChanged < MessageTemplate else content.gsub!(/({ifname})(.*)({endname})/, '') end + # 项目标识更改 + if change_params[:identifier].present? + if change_count > 1 + content.sub!('{ifidentifier}', '
    ') + else + content.sub!('{ifidentifier}', '') + end + content.sub!('{endidentifier}', '') + content.gsub!('{identifier}', change_params[:identifier][1]) + else + content.gsub!(/({ifidentifier})(.*)({endidentifier})/, '') + end # 项目简介更改 if change_params[:description].present? if change_params[:description][1].blank?

    参数