Compare commits

...

3 Commits

Author SHA1 Message Date
chenyh 503e9229c5 update 2021-11-22 13:30:50 +08:00
chenyh 6dc07de1be update 2021-11-22 13:29:22 +08:00
chenyh 47daa70d8a update 2021-11-22 13:25:13 +08:00
510 changed files with 223658 additions and 14974 deletions

7
.gitignore vendored
View File

@ -36,12 +36,12 @@ public/react/yarn.lock
/.idea/*
# Ignore react node_modules
public/system/*
/public/react/.cache
/public/react/node_modules/
/public/react/config/stats.json
/public/react/stats.json
/public/react/.idea/*
/public/react/build/*
/public/h5build
/public/npm-debug.log
@ -72,7 +72,6 @@ vendor/bundle/
/log
/public/admin
/mysql_data
/public/repo/
.generators
@ -82,6 +81,4 @@ docker/
educoder.sql
redis_data/
Dockerfile
dump.rdb
.tags*
ceshi_user.xlsx
dump.rdb

View File

@ -1,35 +1,4 @@
# 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

View File

@ -1,6 +1,8 @@
source 'https://gems.ruby-china.com'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '2.3.7'
gem 'rails', '~> 5.2.0'
gem 'mysql2', '>= 0.4.4', '< 0.6.0'
gem 'puma', '~> 3.11'
@ -17,6 +19,8 @@ gem 'kaminari', '~> 1.1', '>= 1.1.1'
gem 'bootsnap', '>= 1.1.0', require: false
gem 'gitlab', path: 'lib/gitlab-cli'
gem 'chinese_pinyin'
gem 'rack-cors'
@ -70,7 +74,6 @@ group :development do
gem 'listen', '>= 3.0.5', '< 3.2'
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
gem "annotate", "~> 2.6.0"
end
group :test do
@ -100,7 +103,6 @@ gem 'rails-i18n', '~> 5.1'
# job
gem 'sidekiq'
gem 'sinatra'
gem "sidekiq-cron", "~> 1.1"
# batch insert
gem 'bulk_insert'
@ -126,5 +128,3 @@ gem 'request_store'
gem 'harmonious_dictionary', '~> 0.0.1'
gem 'parallel', '~> 1.19', '>= 1.19.1'
gem 'letter_avatar'

View File

@ -1,3 +1,10 @@
PATH
remote: lib/gitlab-cli
specs:
gitlab (3.2.0)
httparty
terminal-table
GEM
remote: https://gems.ruby-china.com/
specs:
@ -54,9 +61,6 @@ GEM
public_suffix (>= 2.0.2, < 5.0)
ancestry (3.0.7)
activerecord (>= 3.2.0)
annotate (2.6.5)
activerecord (>= 2.3.0)
rake (>= 0.8.7)
archive-zip (0.12.0)
io-like (~> 0.3.0)
arel (9.0.0)
@ -118,17 +122,12 @@ GEM
enumerize (2.3.1)
activesupport (>= 3.2)
erubi (1.9.0)
et-orbi (1.2.4)
tzinfo
execjs (2.7.0)
faraday (0.15.4)
multipart-post (>= 1.2, < 3)
ffi (1.12.2)
font-awesome-sass (4.7.0)
sass (>= 3.2)
fugit (1.4.1)
et-orbi (~> 1.1, >= 1.1.8)
raabro (~> 1.4)
globalid (0.4.2)
activesupport (>= 4.2.0)
grape-entity (0.7.1)
@ -139,6 +138,9 @@ GEM
harmonious_dictionary (0.0.1)
hashie (3.6.0)
htmlentities (4.3.4)
httparty (0.18.0)
mime-types (~> 3.0)
multi_xml (>= 0.5.2)
i18n (1.8.2)
concurrent-ruby (~> 1.0)
io-like (0.3.1)
@ -162,7 +164,6 @@ GEM
activerecord
kaminari-core (= 1.2.0)
kaminari-core (1.2.0)
letter_avatar (0.3.8)
listen (3.1.5)
rb-fsevent (~> 0.9, >= 0.9.4)
rb-inotify (~> 0.9, >= 0.9.7)
@ -176,9 +177,10 @@ GEM
mimemagic (~> 0.3.2)
maruku (0.7.3)
method_source (0.9.2)
mimemagic (0.3.10)
nokogiri (~> 1)
rake
mime-types (3.3.1)
mime-types-data (~> 3.2015)
mime-types-data (3.2019.1009)
mimemagic (0.3.4)
mini_mime (1.0.2)
mini_portile2 (2.4.0)
minitest (5.14.0)
@ -219,7 +221,6 @@ GEM
prettier (0.18.2)
public_suffix (4.0.3)
puma (3.12.2)
raabro (1.4.0)
rack (2.0.9)
rack-cors (1.1.1)
rack (>= 2.0.0)
@ -362,9 +363,6 @@ GEM
rack (< 2.1.0)
rack-protection (>= 1.5.0)
redis (>= 3.3.5, < 5)
sidekiq-cron (1.2.0)
fugit (~> 1.1)
sidekiq (>= 4.2.1)
simple_form (5.0.2)
actionpack (>= 5.0)
activemodel (>= 5.0)
@ -404,6 +402,8 @@ GEM
actionpack (>= 4.0)
activesupport (>= 4.0)
sprockets (>= 3.0.0)
terminal-table (1.8.0)
unicode-display_width (~> 1.1, >= 1.1.1)
thor (1.0.1)
thread_safe (0.3.6)
tilt (2.0.10)
@ -437,7 +437,6 @@ DEPENDENCIES
acts-as-taggable-on (~> 6.0)
acts_as_list
ancestry
annotate (~> 2.6.0)
awesome_print
axlsx (~> 3.0.0.pre)
axlsx_rails (~> 0.5.2)
@ -453,13 +452,13 @@ DEPENDENCIES
enumerize
faraday (~> 0.15.4)
font-awesome-sass (= 4.7.0)
gitlab!
grape-entity (~> 0.7.1)
groupdate (~> 4.1.0)
harmonious_dictionary (~> 0.0.1)
jbuilder (~> 2.5)
jquery-rails
kaminari (~> 1.1, >= 1.1.1)
letter_avatar
listen (>= 3.0.5, < 3.2)
mysql2 (>= 0.4.4, < 0.6.0)
oauth2
@ -490,7 +489,6 @@ DEPENDENCIES
searchkick
selenium-webdriver
sidekiq
sidekiq-cron (~> 1.1)
simple_form
simple_xlsx_reader
sinatra
@ -504,5 +502,8 @@ DEPENDENCIES
web-console (>= 3.3.0)
wkhtmltopdf-binary
RUBY VERSION
ruby 2.3.7p456
BUNDLED WITH
2.1.4

137
LICENSE
View File

@ -1,124 +1,21 @@
木兰宽松许可证, 第2版
MIT License
2020年1月 http://license.coscl.org.cn/MulanPSL2
Copyright (c) [year] [fullname]
您对“软件”的复制、使用、修改及分发受木兰宽松许可证第2版“本许可证”的如下条款的约束
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
0. 定义
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
“软件” 是指由“贡献”构成的许可在“本许可证”下的程序和相关文档的集合。
“贡献” 是指由任一“贡献者”许可在“本许可证”下的受版权法保护的作品。
“贡献者” 是指将受版权法保护的作品许可在“本许可证”下的自然人或“法人实体”。
“法人实体” 是指提交贡献的机构及其“关联实体”。
“关联实体” 是指对“本许可证”下的行为方而言控制、受控制或与其共同受控制的机构此处的控制是指有受控方或共同受控方至少50%直接或间接的投票权、资金或其他有价证券。
1. 授予版权许可
每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的版权许可,您可以复制、使用、修改、分发其“贡献”,不论修改与否。
2. 授予专利许可
每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的(根据本条规定撤销除外)专利许可,供您制造、委托制造、使用、许诺销售、销售、进口其“贡献”或以其他方式转移其“贡献”。前述专利许可仅限于“贡献者”现在或将来拥有或控制的其“贡献”本身或其“贡献”与许可“贡献”时的“软件”结合而将必然会侵犯的专利权利要求,不包括对“贡献”的修改或包含“贡献”的其他结合。如果您或您的“关联实体”直接或间接地,就“软件”或其中的“贡献”对任何人发起专利侵权诉讼(包括反诉或交叉诉讼)或其他专利维权行动,指控其侵犯专利权,则“本许可证”授予您对“软件”的专利许可自您提起诉讼或发起维权行动之日终止。
3. 无商标许可
“本许可证”不提供对“贡献者”的商品名称、商标、服务标志或产品名称的商标许可但您为满足第4条规定的声明义务而必须使用除外。
4. 分发限制
您可以在任何媒介中将“软件”以源程序形式或可执行形式重新分发,不论修改与否,但您必须向接收者提供“本许可证”的副本,并保留“软件”中的版权、商标、专利及免责声明。
5. 免责声明与责任限制
“软件”及其中的“贡献”在提供时不带任何明示或默示的担保。在任何情况下,“贡献者”或版权所有者不对任何人因使用“软件”或其中的“贡献”而引发的任何直接或间接损失承担责任,不论因何种原因导致或者基于何种法律理论,即使其曾被建议有此种损失的可能性。
6. 语言
“本许可证”以中英文双语表述,中英文版本具有同等法律效力。如果中英文版本存在任何冲突不一致,以中文版为准。
条款结束
如何将木兰宽松许可证第2版应用到您的软件
如果您希望将木兰宽松许可证第2版应用到您的新软件为了方便接收者查阅建议您完成如下三步
1 请您补充如下声明中的空白,包括软件名、软件的首次发表年份以及您作为版权人的名字;
2 请您在软件包的一级目录下创建以“LICENSE”为名的文件将整个许可证文本放入该文件中
3 请将如下声明文本放入每个源文件的头部注释中。
Copyright (c) [Year] [name of copyright holder]
[Software Name] is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
Mulan Permissive Software LicenseVersion 2
Mulan Permissive Software LicenseVersion 2 (Mulan PSL v2)
January 2020 http://license.coscl.org.cn/MulanPSL2
Your reproduction, use, modification and distribution of the Software shall be subject to Mulan PSL v2 (this License) with the following terms and conditions:
0. Definition
Software means the program and related documents which are licensed under this License and comprise all Contribution(s).
Contribution means the copyrightable work licensed by a particular Contributor under this License.
Contributor means the Individual or Legal Entity who licenses its copyrightable work under this License.
Legal Entity means the entity making a Contribution and all its Affiliates.
Affiliates means entities that control, are controlled by, or are under common control with the acting entity under this License, control means direct or indirect ownership of at least fifty percent (50%) of the voting power, capital or other securities of controlled or commonly controlled entity.
1. Grant of Copyright License
Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable copyright license to reproduce, use, modify, or distribute its Contribution, with modification or not.
2. Grant of Patent License
Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable (except for revocation under this Section) patent license to make, have made, use, offer for sale, sell, import or otherwise transfer its Contribution, where such patent license is only limited to the patent claims owned or controlled by such Contributor now or in future which will be necessarily infringed by its Contribution alone, or by combination of the Contribution with the Software to which the Contribution was contributed. The patent license shall not apply to any modification of the Contribution, and any other combination which includes the Contribution. If you or your Affiliates directly or indirectly institute patent litigation (including a cross claim or counterclaim in a litigation) or other patent enforcement activities against any individual or entity by alleging that the Software or any Contribution in it infringes patents, then any patent license granted to you under this License for the Software shall terminate as of the date such litigation or activity is filed or taken.
3. No Trademark License
No trademark license is granted to use the trade names, trademarks, service marks, or product names of Contributor, except as required to fulfill notice requirements in section 4.
4. Distribution Restriction
You may distribute the Software in any medium with or without modification, whether in source or executable forms, provided that you provide recipients with a copy of this License and retain copyright, patent, trademark and disclaimer statements in the Software.
5. Disclaimer of Warranty and Limitation of Liability
THE SOFTWARE AND CONTRIBUTION IN IT ARE PROVIDED WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED. IN NO EVENT SHALL ANY CONTRIBUTOR OR COPYRIGHT HOLDER BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE SOFTWARE OR THE CONTRIBUTION IN IT, NO MATTER HOW ITS CAUSED OR BASED ON WHICH LEGAL THEORY, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
6. Language
THIS LICENSE IS WRITTEN IN BOTH CHINESE AND ENGLISH, AND THE CHINESE VERSION AND ENGLISH VERSION SHALL HAVE THE SAME LEGAL EFFECT. IN THE CASE OF DIVERGENCE BETWEEN THE CHINESE AND ENGLISH VERSIONS, THE CHINESE VERSION SHALL PREVAIL.
END OF THE TERMS AND CONDITIONS
How to Apply the Mulan Permissive Software LicenseVersion 2 (Mulan PSL v2) to Your Software
To apply the Mulan PSL v2 to your work, for easy identification by recipients, you are suggested to complete following three steps:
Fill in the blanks in following statement, including insert your software name, the year of the first publication of your software, and your name identified as the copyright owner;
Create a file named "LICENSE" which contains the whole context of this License in the first directory of your software package;
Attach the statement to the appropriate annotated syntax at the beginning of each source file.
Copyright (c) [Year] [name of copyright holder]
[Software Name] is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

5171
README.md

File diff suppressed because it is too large Load Diff

View File

@ -51,51 +51,6 @@ http://localhost:3000/api/accounts/remote_register | jq
|-- token |string|用户token|
返回值
```json
{
"status": 0,
"message": "success",
"user": {
"id": 36400,
"token": "8c87a80d9cfacc92fcb2451845104f35119eda96"
}
}
```
---
#### 独立注册接口
```
POST accounts/register
```
*示例*
```bash
curl -X POST \
-d "login=2456233122@qq.com" \
-d "password=djs_D_00001" \
-d "namespace=16895620" \
-d "code=forge" \
http://localhost:3000/api/accounts/remote_register | jq
```
*请求参数说明:*
|参数名|必选|类型|说明|
|-|-|-|-|
|login |是|string |邮箱或者手机号 |
|namespace |是|string |登录名 |
|password |是|string |密码 |
|code |是|string |验证码 |
*返回参数说明:*
|参数名|类型|说明|
|-|-|-|
|user|json object |返回数据|
|-- id |int |用户id |
|-- token |string|用户token|
返回值
```json
{

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.8 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

View File

@ -99,38 +99,3 @@ $(document).on("turbolinks:before-cache", function () {
$(function () {
});
$(document).on('turbolinks:load', function() {
$('.logo-item-left').on("change", 'input[type="file"]', function () {
var $fileInput = $(this);
var file = this.files[0];
var imageType = /image.*/;
if (file && file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function () {
var $box = $fileInput.parent();
$box.find('img').attr('src', reader.result).css('display', 'block');
$box.addClass('has-img');
};
reader.readAsDataURL(file);
} else {
}
});
$('.attachment-item-left').on("change", 'input[type="file"]', function () {
var $fileInput = $(this);
var file = this.files[0];
var imageType = /image.*/;
if (file && file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function () {
var $box = $fileInput.parent();
$box.find('img').attr('src', reader.result).css('display', 'block');
$box.addClass('has-img');
};
reader.readAsDataURL(file);
} else {
}
});
})

View File

@ -1,7 +1,7 @@
$(document).on('turbolinks:load', function() {
if ($('body.admins-courses-index-page').length > 0) {
var searchContainer = $(".course-list-form");
var searchForm = $("form.search-form",searchContainer);
let searchContainer = $(".course-list-form");
let searchForm = $("form.search-form",searchContainer);
searchContainer.on('change', '.course-homepage-show', function(){
searchForm.find('input[type="submit"]').trigger('click');

View File

@ -0,0 +1,4 @@
$(document).on('turbolinks:load', function() {
var $addSectionModal = $('.admin-import-user-modal');
});

View File

@ -1,15 +1,7 @@
/*
* @Description: Do not edit
* @Date: 2021-07-16 11:58:16
* @LastEditors: viletyy
* @Author: viletyy
* @LastEditTime: 2021-08-31 14:48:59
* @FilePath: /forgeplus/app/assets/javascripts/admins/shixun_settings/index.js
*/
$(document).on('turbolinks:load', function() {
if ($('body.admins-shixun-settings-index-page').length > 0) {
var searchContainer = $(".shixun-settings-list-form");
var searchForm = $("form.search-form",searchContainer);
let searchContainer = $(".shixun-settings-list-form");
let searchForm = $("form.search-form",searchContainer);
searchContainer.on('change', '.shixun-settings-select', function(){
searchForm.find('input[type="submit"]').trigger('click');

View File

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

View File

@ -58,149 +58,3 @@ input.form-control {
position: absolute;
}
.logo-item {
display: flex;
&-img {
display: block;
width: 80px;
height: 80px;
background: #e9ecef;
}
&-upload {
cursor: pointer;
position: absolute;
top: 0;
width: 80px;
height: 80px;
background: #e9ecef;
border: 1px solid #ced4da;
&::before {
content: '';
position: absolute;
top: 27px;
left: 39px;
width: 2px;
height: 26px;
background: #495057;
}
&::after {
content: '';
position: absolute;
top: 39px;
left: 27px;
width: 26px;
height: 2px;
background: #495057;
}
}
&-left {
position: relative;
width: 80px;
height: 80px;
&.has-img {
.logo-item-upload {
display: none;
}
&:hover {
.logo-item-upload {
display: block;
background: rgba(145, 145, 145, 0.8);
}
}
}
}
&-right {
display: flex;
flex-direction: column;
justify-content: space-between;
color: #777777;
font-size: 0.8rem;
}
&-title {
color: #23272B;
font-size: 1rem;
}
}
.attachment-item {
display: flex;
&-img {
display: block;
width: 160px;
height: 160px;
background: #e9ecef;
}
&-upload {
cursor: pointer;
position: absolute;
top: 0;
width: 160px;
height: 160px;
background: #e9ecef;
border: 1px solid #ced4da;
&::before {
content: '';
position: absolute;
top: 54px;
left: 78px;
width: 2px;
height: 52px;
background: #495057;
}
&::after {
content: '';
position: absolute;
top: 78px;
left: 54px;
width: 52px;
height: 2px;
background: #495057;
}
}
&-left {
position: relative;
width: 160px;
height: 160px;
&.has-img {
.attachment-item-upload {
display: none;
}
&:hover {
.attachment-item-upload {
display: block;
background: rgba(145, 145, 145, 0.8);
}
}
}
}
&-right {
padding-top: 100px;
display: flex;
flex-direction: column;
justify-content: space-between;
color: #777777;
font-size: 0.8rem;
}
&-title {
color: #23272B;
font-size: 1rem;
}
}

View File

@ -0,0 +1,7 @@
// .admins-banned-users-index-page {
// .width240 {
// width: 240px;
// }
// .mr15{margin-right: 15px;}
// .mt2{margin-top: 2px;}
// }

View File

@ -0,0 +1,11 @@
.admins-forum-moderators-index-page {
.df{
display: flex;
}
.flex1 {
flex: 1;
}
.text-center {
text-align: center;
}
}

View File

@ -0,0 +1,128 @@
.admins-forum-sections-index-page {
.color-grey{color: #888;}
.grid-item-top {
display: grid;
grid-template-columns: max-content 1fr;
align-self: start;
}
.mt20{margin-top: 20px;}
.none{display: none;}
.color-red{color: red!important;}
.upload-image-100 {
height: 100px;
width: 100px;
border-radius: 8px;
text-align: center;
/* line-height: 100px; */
background: #f5f5f5;
color: #999;
position: relative;
}
.pointer {
cursor: pointer;
}
.avatar100{
height: 100px;
width: 100px;
border-radius: 8px;
}
.upload-image-100:hover .admin-show-again-upload{display: block;}
.admin-show-again-upload {
bottom: 0;
width: 100px;
height: 100%;
line-height: 100px;
/* top: 0; */
background: rgba(0,0,0,0.6);
color: #fff;
position: absolute;
border-radius: 8px;
}
.menu_operate {
position: relative;
cursor: pointer;
.operateList {
position: absolute;
right: -110px;
top: 9px;
background: #fff;
width: 100px;
color: #999;
box-shadow: 0px 0px 9px rgba(0,0,0,0.2);
z-index: 100;
display: none;
a {
display: block;
height: 30px;
line-height: 30px;
padding: 0px 10px;
}
}
.operateList.active {
display: block !important;
}
}
.color-grey-6 {
color: #666!important;
}
.set_l_submenu {
padding-left: 50px;
display: none;
width: 180px;
list-style-type: none;
li{
padding: 4px 0;
}
}
.set_l_submenu.active {
display: block;
}
.set_l_premenu {
position: relative;
display: flex;
height: 30px;
line-height: 30px;
cursor: pointer;
}
.df{
display: flex;
}
.flex1 {
flex: 1;
}
.text-center {
text-align: center;
}
.grid-item-left {
display: grid;
grid-template-columns:1fr max-content;
align-self: start;
}
.ml20{margin-left: 20px;}
.forum-moderators-items {
padding: 10px 30px;
max-height: 175px;
overflow-y: auto;
background: #F4FAFF;
margin-top: 20px;
}
.mr4 {margin-right: 4px;}
.blue-user-btn {
margin: 0 5px;
padding: 2px 8px;
background: #F4F8FA!important;
color: #fff!important;
border: 1px solid #4CACFF;
border-radius: 4px;
white-space: nowrap;
}
.mr5 {
margin-right: 5px;
}
.moderator-list-content{
display: inline-block;
margin: 5px 0;
}
}

View File

@ -0,0 +1,5 @@
.admins-memos-index-page {
.users-list-container {
text-align: center;
}
}

View File

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

View File

@ -1,5 +1,6 @@
class AccountsController < ApplicationController
include ApplicationHelper
#skip_before_action :check_account, :only => [:logout]
def index
render json: session
@ -8,7 +9,6 @@ class AccountsController < ApplicationController
# 其他平台同步注册的用户
def remote_register
username = params[:username]&.gsub(/\s+/, "")
tip_exception("无法使用以下关键词:#{username},请重新命名") if ReversedKeyword.check_exists?(username)
email = params[:email]&.gsub(/\s+/, "")
password = params[:password]
platform = (params[:platform] || 'forge')&.gsub(/\s+/, "")
@ -108,48 +108,63 @@ class AccountsController < ApplicationController
# 用户注册
# 注意:用户注册需要兼顾本地版,本地版是不需要验证码及激活码以及使用授权的,注册完成即可使用
# params[:login] 邮箱或者手机号
# params[:namespace] 登录名
# params[:code] 验证码
# code_type 1注册手机验证码 8邮箱注册验证码
# 本地forge注册入口需要重新更改逻辑
def register
# type只可能是1或者8
user = nil
begin
Register::Form.new(register_params).validate!
# 查询验证码是否正确;type只可能是1或者8
type = phone_mail_type(params[:login].strip)
code = params[:code].strip
user = Users::RegisterService.call(register_params)
password = register_params[:password].strip
# gitea用户注册, email, username, password
interactor = Gitea::RegisterInteractor.call({username: user.login, email: user.mail, password: password})
if interactor.success?
gitea_user = interactor.result
result = Gitea::User::GenerateTokenService.call(user.login, password)
user.gitea_token = result['sha1']
user.gitea_uid = gitea_user[:body]['id']
if user.save!
UserExtension.create!(user_id: user.id)
successful_authentication(user)
render_ok
end
if type == 1
uid_logger("start register by phone: type is #{type}")
pre = 'p'
email = nil
phone = params[:login]
verifi_code = VerificationCode.where(phone: phone, code: code, code_type: 1).last
else
tip_exception(-1, interactor.error)
uid_logger("start register by email: type is #{type}")
pre = 'm'
email = params[:login]
phone = nil
verifi_code = VerificationCode.where(email: email, code: code, code_type: 8).last
end
uid_logger("start register: verifi_code is #{verifi_code}, code is #{code}, time is #{Time.now.to_i - verifi_code.try(:created_at).to_i}")
# check_code = (verifi_code.try(:code) == code.strip && (Time.now.to_i - verifi_code.created_at.to_i) <= 10*60)
# todo 上线前请删除万能验证码"513231"
unless code == "513231" && request.subdomain == "test-newweb"
return normal_status(-2, "验证码不正确") if verifi_code.try(:code) != code.strip
return normal_status(-2, "验证码已失效") if !verifi_code&.effective?
end
return normal_status(-1, "8~16位密码支持字母数字和符号") unless params[:password] =~ CustomRegexp::PASSWORD
code = generate_identifier User, 8, pre
login = pre + code
@user = User.new(admin: false, login: login, mail: email, phone: phone, type: "User")
@user.password = params[:password]
# 现在因为是验证码,所以在注册的时候就可以激活
@user.activate
# 必须要用save操作密码的保存是在users中
if @user.save!
# todo user_extension
UserExtension.create!(user_id: @user.id)
# 注册完成手机号或邮箱想可以奖励500金币
# RewardGradeService.call(
# @user,
# container_id: @user.id,
# container_type: pre == 'p' ? 'Phone' : 'Mail',
# score: 500
# )
# 注册时,记录是否是引流用户
ip = request.remote_ip
ua = UserAgent.find_by_ip(ip)
ua.update_column(:agent_type, UserAgent::USER_REGISTER) if ua
successful_authentication(@user)
# session[:user_id] = @user.id
normal_status("注册成功")
end
rescue Register::BaseForm::EmailError => e
render_result(-2, e.message)
rescue Register::BaseForm::LoginError => e
render_result(-3, e.message)
rescue Register::BaseForm::PhoneError => e
render_result(-4, e.message)
rescue Register::BaseForm::PasswordFormatError => e
render_result(-5, e.message)
rescue Register::BaseForm::PasswordConfirmationError => e
render_result(-7, e.message)
rescue Register::BaseForm::VerifiCodeError => e
render_result(-6, e.message)
rescue Exception => e
Gitea::User::DeleteService.call(user.login) unless user.nil?
uid_logger_error(e.message)
tip_exception(-1, e.message)
end
@ -157,7 +172,6 @@ class AccountsController < ApplicationController
# 用户登录
def login
Users::LoginForm.new(login_params).validate!
@user = User.try_to_login(params[:login], params[:password])
return normal_status(-2, "错误的账号或密码") if @user.blank?
@ -184,49 +198,31 @@ class AccountsController < ApplicationController
# session[:user_id] = @user.id
end
def change_password
@user = User.find_by(login: params[:login])
return render_error("未找到相关用户!") if @user.blank?
return render_error("旧密码不正确") unless @user.check_password?(params[:old_password])
sync_params = {
password: params[:password].to_s,
email: @user.mail
}
interactor = Gitea::User::UpdateInteractor.call(@user.login, sync_params)
if interactor.success?
@user.update_attribute(:password, params[:password])
render_ok
else
render_error(interactor.error)
end
end
# 忘记密码
def reset_password
begin
Accounts::ResetPasswordForm.new(reset_password_params).validate!
code = params[:code]
login_type = phone_mail_type(params[:login].strip)
# 获取验证码
if login_type == 1
phone = params[:login]
verifi_code = VerificationCode.where(phone: phone, code: code, code_type: 2).last
user = User.find_by_phone(phone)
else
email = params[:login]
verifi_code = VerificationCode.where(email: email, code: code, code_type: 3).last
user = User.find_by_mail(email) #这里有问题应该是为email,而不是mail 6.13-hs
end
return normal_status(-2, "验证码不正确") if verifi_code.try(:code) != code.strip
return normal_status(-2, "验证码已失效") if !verifi_code&.effective?
return normal_status(-1, "8~16位密码支持字母数字和符号") unless params[:new_password] =~ CustomRegexp::PASSWORD
user = find_user
return render_error('未找到相关账号') if user.blank?
user = Accounts::ResetPasswordService.call(user, reset_password_params)
LimitForbidControl::UserLogin.new(user).clear if user.save!
render_ok
rescue Register::BaseForm::EmailError => e
render_result(-2, e.message)
rescue Register::BaseForm::PhoneError => e
render_result(-4, e.message)
rescue Register::BaseForm::PasswordFormatError => e
render_result(-5, e.message)
rescue Register::BaseForm::PasswordConfirmationError => e
render_result(-7, e.message)
rescue Register::BaseForm::VerifiCodeError => e
render_result(-6, e.message)
rescue ActiveRecord::Rollback => e
render_result(-1, "服务器异常")
user.password, user.password_confirmation = params[:new_password], params[:new_password_confirmation]
ActiveRecord::Base.transaction do
user.save!
LimitForbidControl::UserLogin.new(user).clear
end
sucess_status
rescue Exception => e
uid_logger_error(e.message)
tip_exception(e.message)
@ -283,7 +279,7 @@ class AccountsController < ApplicationController
# 发送验证码
# params[:login] 手机号或者邮箱号
# params[:type]为事件通知类型 1用户注册 2忘记密码 3: 绑定手机 4: 绑定邮箱, 5: 验收手机号有效 # 如果有新的继续后面加
# params[:type]为事件通知类型 1用户注册注册 2忘记密码 3: 绑定手机 4: 绑定邮箱, 5: 验收手机号有效 # 如果有新的继续后面加
# 发送验证码send_type 1注册手机验证码 2找回密码手机验证码 3找回密码邮箱验证码 4绑定手机 5绑定邮箱
# 6手机验证码登录 7邮箱验证码登录 8邮箱注册验证码 9: 验收手机号有效
def get_verification_code
@ -297,22 +293,19 @@ class AccountsController < ApplicationController
sign = Digest::MD5.hexdigest("#{OPENKEY}#{value}")
tip_exception(501, "请求不合理") if sign != params[:smscode]
logger.info "########### 验证码:#{verification_code}"
logger.info("########get_verification_code: login_type #{login_type} send_type#{send_type}, ")
# 记录验证码
check_verification_code(verification_code, send_type, value)
render_ok
sucess_status
end
# check user's login or email or phone is used
# params[:value] 手机号或者邮箱号或者登录名
# params[:type] 为事件类型 1登录名(login) 2email(邮箱) 3phone(手机号)
def check
Register::CheckColumnsForm.new(check_params).validate!
render_ok
# 1 手机类型0 邮箱类型
# 注意新版的login是自动名生成的
def phone_mail_type value
value =~ /^1\d{10}$/ ? 1 : 0
end
private
# type 事件类型 1用户注册 2忘记密码 3: 绑定手机 4: 绑定邮箱, 5: 验证手机号是否有效 # 如果有新的继续后面加
@ -355,25 +348,4 @@ class AccountsController < ApplicationController
params.require(:user).permit(:login, :email, :phone)
end
def login_params
params.require(:account).permit(:login, :password)
end
def check_params
params.permit(:type, :value)
end
def register_params
params.permit(:login, :namespace, :password, :password_confirmation, :code)
end
def reset_password_params
params.permit(:login, :password, :password_confirmation, :code)
end
def find_user
phone_or_mail = strip(reset_password_params[:login])
User.where("phone = :search OR mail = :search", search: phone_or_mail).last
end
end

View File

@ -0,0 +1,31 @@
class Admins::ApplyDestroyController < Admins::BaseController
def index
memos = Memo.where(destroy_status: 1).includes(:author).order("created_at desc")
@memos = paginate memos
respond_to do |format|
format.html
format.js
end
end
def confirm_apply_destroy
memo = Memo.find(params[:id])
apply_status = params[:confirm]
if apply_status == "delete"
memo.destroy
extra = "d_2"
Tiding.create!(:user_id => memo.author_id, :trigger_user_id => 0,
container_id: memo.id, container_type: 'Memo',
:viewed => 0, :tiding_type => "System", :extra => "d_2")
else
memo.common!
memo.save
extra = "d_3"
Tiding.create!(:user_id => memo.author_id, :trigger_user_id => 0,
container_id: memo.id, container_type: 'Memo',
:viewed => 0, :tiding_type => "System", :extra => "d_3")
end
@status = 1
@message = "操作成功"
end
end

View File

@ -32,7 +32,7 @@ class Admins::AuthSchoolsController < Admins::BaseController
def search_manager
school = School.find_by(id: params[:school_id])
user_ids = school&.ec_school_users&.pluck(:user_id)
@users = User.where.not(id: user_ids).where("CONCAT(lastname, firstname) like ? OR nickname like ?", "%#{params[:name].strip.to_s}%", "%#{params[:name].strip.to_s}%").limit(10)
@users = User.where.not(id: user_ids).where("concat(lastname, firstname) like ?", "%#{params[:name].strip.to_s}%").limit(10)
end
# 添加认证学校管理员

View File

@ -0,0 +1,66 @@
class Admins::BannedUsersController < Admins::BaseController
# include Admins::BaseHelper
def index
@menu_type = 8
@sub_type = 6
#被禁言的用户
all_banned_users = BannedForum.includes(:memo, :author, user: :user_extensions)
banned_true = all_banned_users.where(is_banned: true)
@banned_users_size = banned_true.size
@banned_type = params[:banned_type] || "banned"
@search_params = params[:search] || nil
if @banned_type == "banned"
banned_users = banned_true
else
banned_users = all_banned_users.where(is_banned: false)
end
if @search_params.present?
banned_users = banned_users.joins(:user).where("LOWER(users.login) LIKE ? or LOWER(concat(users.lastname, users.firstname)) LIKE ?", "%#{@search_params}%", "%#{@search_params}%")
end
banned_users = banned_users.order("updated_at desc")
@banned_users_count = banned_users.size
@banned_users = paginate banned_users
# page = (params[:page] || 1).to_i
# per_page = 15
# @banned_users_pages = Paginator.new @banned_users_count, per_page, page
# @banned_users = banned_users.limit(@banned_users_pages.per_page).offset(@banned_users_pages.offset).to_a
end
def confirm_banned
if params[:user_id].blank? || params[:id].blank?
@status = -1
@message = "参数缺失"
else
before_users_banned = BannedForum.where(user_id:params[:user_id])
banned_params = {
user_id: params[:user_id],
author_id: current_user.id,
memo_id: params[:id],
is_banned: false,
banned_count: before_users_banned.present? ? (before_users_banned.last.banned_count + 1) : 1
}
new_banned = BannedForum.new(banned_params)
if new_banned.save
before_users_banned&.update_all(is_banned: false) if before_users_banned.present?
@status = 1
@message = "取消禁言成功"
else
@status = -1
@message = "取消禁言失败,请稍后重试"
end
end
end
end

View File

@ -0,0 +1,89 @@
class Admins::ForumAppliesController < Admins::BaseController
# include Admins::BaseHelper
def index
@menu_type = 8
@sub_type = 7
all_forum_applies = ApplyForum.includes(:forum_section,:reviews, user: :user_extensions)
@select_type = params[:select_type] || "unconfirm"
@section_name = params[:section_name] || nil
@search_name = params[:user_name] || nil
if @select_type == "unconfirm"
forum_applies = all_forum_applies.where(is_confirm: 0)
else
forum_applies = all_forum_applies.where(is_confirm: [1,2])
end
if @section_name.present?
forum_applies = forum_applies.joins(:forum_section).where("forum_sections.title like ?", "%#{@section_name}%")
end
if @search_name.present?
forum_applies = forum_applies.joins(:user).where("LOWER(users.login) LIKE ? or LOWER(concat(users.lastname, users.firstname)) LIKE ?", "%#{@search_name}%", "%#{@search_name}%")
end
forum_applies = forum_applies.order("apply_forums.updated_at desc")
@forum_applies_count = forum_applies.size
@forum_applies = paginate forum_applies
# page = (params[:page] || 1).to_i
# per_page = 15
# @forum_applies_pages = Paginator.new @forum_applies_count, per_page, page
# @forum_applies = forum_applies.limit(@forum_applies_pages.per_page).offset(@forum_applies_pages.offset).to_a
end
def confirm_apply
@forum_apply = ApplyForum.find(params[:id])
@is_confirm = params[:is_confirm].to_i
review_result = params[:review_result].to_i
review_params = {
review_status: review_result,
reason: params[:reason].present? ? params[:reason] : nil,
user_id: current_user.id,
reviewable_type: "ApplyForum",
reviewable_id: params[:id],
source: "apply_forum"
}
if Review.exists?(reviewable_type: "ApplyForum", reviewable_id: params[:id], source: "apply_forum")
this_review = Review.where(reviewable_type: "ApplyForum", reviewable_id: params[:id], source: "apply_forum").first
if this_review.update_attributes(review_params)
@status = 1
@message = "操作成功"
else
@status = -1
@message = "操作失败"
end
else
review = Review.new(review_params)
if review.save
@status = 1
@message = "操作成功"
else
@status = -1
@message = "操作失败"
end
end
if @status > 0
@forum_apply.update_attributes(is_confirm: (review_result+1),deal_time: Time.now)
exists_moder = ForumModerator.where(user_id: @forum_apply.user_id,forum_section_id: @forum_apply.forum_section_id)
if review_result == 1
exists_moder.delete_all if exists_moder.exists?
elsif review_result == 0
unless exists_moder.exists?
ForumModerator.create(user_id: @forum_apply.user_id, forum_section_id: @forum_apply.forum_section_id,is_children: @forum_apply.forum_section.try(:parent_id).present?)
end
end
Tiding.where(container_type: "ForumSection", container_id: @forum_apply.forum_section_id, status: 0).update_all(status: 1)
Tiding.create(:user_id => @forum_apply.user_id, :trigger_user_id => 1,
container_id: @forum_apply.forum_section_id, container_type: 'ForumSection',
:parent_container_id => @forum_apply.id, :parent_container_type => "ApplyForum",
:viewed => 0,status: 1, :tiding_type => "System",extra: "4")
end
end
end

View File

@ -0,0 +1,59 @@
class Admins::ForumModeratorsController < Admins::BaseController
before_action :set_forum
def new
end
def create
user_ids = params[:member_ids]
is_children = @forum_section.parent_id.present?
if user_ids.present? && user_ids.size > 0
user_ids = user_ids.reject(&:blank?)
user_ids.each do |user_id|
unless ForumModerator.exists?(user_id: user_id, forum_section_id: @forum_section.id)
@forum_section.forum_moderators.create!(user_id: user_id, is_children: is_children)
end
unless is_children
children_forum_sections = @forum_section.children_forum
children_forum_sections.each do |children|
unless ForumModerator.exists?(user_id: user_id, forum_section_id: children.id)
children.forum_moderators.create!(user_id: user_id, is_children: true)
end
end
end
end
@forum_moderators = @forum_section.forum_moderators
@forum_status = 1
else
@forum_status = -1
end
end
def destroy
@forum_moderator = ForumModerator.find_by_id(params[:id])
@forum_moderator.destroy
end
def search_user
return_html = ""
user_name = params[:user_name].strip
if user_name.present?
users = User.where("( LOWER(login) LIKE ? or LOWER(concat(lastname, firstname)) LIKE ? or LOWER(mail) LIKE ? )",
"%#{user_name}%","%#{user_name}%","%#{user_name}%")
users.each do |u|
check_html = "<div class='search-user-check'><input id='check_user_#{u.login}' class='magic-checkbox mr4' type='checkbox' name='member_ids[]' value=""#{u.id}"" checked='false'><label for='check_user_#{u.login}'>#{u.try(:show_real_name)}</label></div>"
return_html << check_html
end
end
render json: {html: return_html }
end
private
def set_forum
@forum_section = ForumSection.find_by_id(params[:forum_section_id])
end
end

View File

@ -0,0 +1,153 @@
#论坛的板块设置
class Admins::ForumSectionsController < Admins::BaseController
before_action :set_forum, except: [:index, :new,:create]
def index
@menu_type = 8
@sub_type = 5
forum_sections = ForumSection.roots.includes(:forum_moderators).order("position desc")
@max_position = forum_sections&.maximum(:position).to_i
@min_position = forum_sections&.minimum(:position).to_i
@forum_sections_count = forum_sections.size
# page = (params[:page] || 1).to_i
# per_page = 15
# @forum_sections_pages = Paginator.new @forum_sections_count, per_page, page
# @forum_sections = forum_sections.limit(@forum_sections_pages.per_page).offset(@forum_sections_pages.offset).to_a
@forum_sections = paginate forum_sections
respond_to do |format|
format.html
format.js
end
end
def new
@parent_id = params[:parent_id]
@forum_section = ForumSection.new
respond_to do |format|
format.js
end
end
def create
attachment_id = params[:attachments]&.first
positions = ForumSection.pluck(:position).select { |a| a.is_a? Integer }
positions = positions.max.to_i
if params[:forum_section][:parent_id].present?
@parent_forum = ForumSection.find_by_id(params[:forum_section][:parent_id])
end
if params[:forum_section][:title].blank?
forum_status = 0
forum_msg = "标题不能为空"
elsif params[:forum_section][:title].strip.length > 20
forum_status = 0
forum_msg = "不能超过最大限制20个字符"
elsif ForumSection.exists?(title: params[:forum_section][:title].strip)
forum_status = 0
forum_msg = "不能重名"
else
forum_section_params = {
user_id: current_user.id,
title: params[:forum_section][:title].strip,
position: positions + 1,
parent_id: params[:forum_section][:parent_id],
is_recommend: false,
description: params[:forum_section][:description].to_s.truncate(200)
}
@forum_section = ForumSection.new(forum_section_params)
if @forum_section.save
if attachment_id.present?
attachment = Attachment.find(attachment_id)
attachment.container = @forum_section
attachment.save
@forum_section.attachment_id = attachment_id
@forum_section.save
end
forum_status = 1
forum_msg = "创建成功"
else
forum_status = -1
forum_msg = "创建失败,请重试"
end
end
@forum_status = {status: forum_status, msg: forum_msg}
end
def edit
@children_forum = params[:children_forum]
@attachment = @forum_section.image_attachment
end
def update
attachment_id = params[:attachments]&.first
if params[:forum_section][:title].blank?
forum_status = 0
forum_msg = "名称不能为空"
elsif params[:forum_section][:title].strip.length > 20
forum_status = 0
forum_msg = "不能超过最大限制20个字符"
elsif params[:forum_section][:title].strip != @forum_section.title && ForumSection.exists?(title: params[:forum_section][:title].strip)
forum_status = 0
forum_msg = "不能重名"
else
if @forum_section.update_attributes(title: params[:forum_section][:title].strip, description: params[:forum_section][:description].to_s.truncate(200))
unless attachment_id.blank? || @forum_section.attachment_id.to_i == attachment_id.to_i
Attachment.where(id: @forum_section.attachment_id.to_i).destroy_all if @forum_section.attachment_id.present?
attachment = Attachment.find(attachment_id)
attachment.container = @forum_section
attachment.save
@forum_section.attachment_id = attachment_id
@forum_section.save
end
forum_status = 1
forum_msg = "更新成功"
else
forum_status = -1
forum_msg = "更新失败,请重试"
end
end
@edit_forum_status = {status: forum_status, msg: forum_msg}
end
def destroy
if @forum_section.destroy
delete_status = 1
delete_msg = "删除成功"
else
delete_status = -1
delete_msg = "删除失败,请稍后重试"
end
@delete_status = {status: delete_status, msg: delete_msg}
end
def order_forums
@children_forums = @forum_section.get_children_section("asc")
end
def recommend_forums
@forum_section.update_attribute(:is_recommend, params[:is_recommend])
end
def move
cate_opt = params[:opr]
cate_position = @forum_section.position.to_i
move_status = up_and_down(cate_opt,@forum_section,cate_position,"forum_section")
if move_status == 0
@c_msg = "移动成功"
else
@c_msg = "移动失败"
end
redirect_to admins_forum_sections_path
end
private
def set_forum
@forum_section = ForumSection.find_by_id(params[:id])
end
end

View File

@ -33,7 +33,7 @@ class Admins::LaboratoriesController < Admins::BaseController
keyword = params[:keyword].to_s.strip
if keyword.present?
like_sql = 'shixuns.name LIKE :keyword OR CONCAT(users.lastname, users.firstname) LIKE :keyword '\
'users.nickname LIKE :keyword OR mirror_repositories.name LIKE :keyword'
'OR mirror_repositories.name LIKE :keyword'
shixuns = shixuns.joins(:user, :mirror_repositories).where(like_sql, keyword: "%#{keyword}%")
end
@ -48,7 +48,7 @@ class Admins::LaboratoriesController < Admins::BaseController
keyword = params[:keyword].to_s.strip
if keyword.present?
like_sql = 'subjects.name LIKE :keyword OR CONCAT(users.lastname, users.firstname) LIKE :keyword OR users.nickname LIKE :keyword'
like_sql = 'subjects.name LIKE :keyword OR CONCAT(users.lastname, users.firstname) LIKE :keyword'
subjects = subjects.joins(:user).where(like_sql, keyword: "%#{keyword}%")
end

View File

@ -0,0 +1,16 @@
class Admins::MemoReplyListsController < Admins::BaseController
def index
@memo_hidden_type = params[:hidden] || ""
memos = Memo.where("parent_id is not null").includes(:author, :parent)
if @memo_hidden_type.present?
memos = memos.where(hidden: @memo_hidden_type.to_s == "hidden")
end
memos = memos.order("created_at desc")
@memos = paginate memos
respond_to do |format|
format.html
format.js
end
end
end

View File

@ -0,0 +1,79 @@
class Admins::MemosController < Admins::BaseController
# include Admins::BaseHelper
# 帖子
def index
@memo_hidden_type = params[:hidden] || ""
memos = Memo.where(parent_id: nil).includes(:author)
if @memo_hidden_type.present?
memos = memos.where(hidden: @memo_hidden_type.to_s == "hidden")
end
memos = memos.order("created_at desc")
@memos = paginate memos
respond_to do |format|
format.html
format.js
end
end
def memo_homepage_show
memo = Memo.find params[:id]
memo.update_column(:homepage_show, params[:checked]) unless memo.hidden?
render :json => {status: 1, message: "设置成功!"}
end
def memo_hidden
memo = Memo.find params[:id]
if params[:checked].to_s == 'true'
publish_time = Time.now
action_type = "passed"
extra = "1"
else
publish_time = nil
action_type = "refuse"
extra = "2"
end
memo.update_attributes(hidden: !(params[:checked].to_s == 'true'), published_at: publish_time) # 勾选代表不隐藏,所以要取反
CheckedAction.create!(user_id: current_user.id,checkable_type: "Memo",checkable_id: params[:id], action_type: action_type, action_at: Time.now)
if !memo.hidden? && memo.parent_id.present? && !memo.tidings.exists?(user_id: memo.parent.author_id,trigger_user_id: memo.author_id, extra: "3")
Tiding.create(:user_id => memo.parent.author_id, :trigger_user_id => memo.author_id,
container_id: memo.id, container_type: 'Memo',
:parent_container_id => memo.root_id, :parent_container_type => "Memo",
:viewed => 0, :tiding_type => "Comment", :extra => "3")
elsif !memo.hidden? && memo.parent_id.blank?
Tiding.create(:user_id => memo.author_id, :trigger_user_id => current_user.id,
container_id: memo.id, container_type: 'Memo',
:viewed => 0, :tiding_type => "Comment",:extra => extra)
end
render :json => {status: 1, message: "设置成功!"}
end
def delete_memo
memo = Memo.find params[:id]
memo.destroy if memo.hidden?
redirect_to memo.parent_id.present? ? admins_memo_reply_lists_path : admins_memos_path
end
# def memo_reply_list
# @menu_type = 8
# @sub_type = 4
# @memo_hidden_type = params[:hidden] || ""
# Rails.logger.info("======================sub_type==================#@sub_type")
# memos = Memo.where("parent_id is not null").includes(:author, :parent)
# if @memo_hidden_type.present?
# memos = memos.where(hidden: @memo_hidden_type.to_s == "hidden")
# end
# memos = memos.order("created_at desc")
# @memos = paginate memos
# respond_to do |format|
# format.html
# format.js
# end
# end
end

View File

@ -3,8 +3,8 @@ class Admins::ProjectCategoriesController < Admins::BaseController
before_action :validate_names, only: [:create, :update]
def index
sort_by = ProjectCategory.column_names.include?(params[:sort_by]) ? params[:sort_by] : 'created_at'
sort_direction = %w(desc asc).include?(params[:sort_direction]) ? params[:sort_direction] : 'desc'
sort_by = params[:sort_by] ||= 'created_at'
sort_direction = params[:sort_direction] ||= 'desc'
q = ProjectCategory.ransack(name_cont: params[:name])
project_categories = q.result(distinct: true).order("#{sort_by} #{sort_direction}")
@project_categories = paginate(project_categories)
@ -22,7 +22,7 @@ class Admins::ProjectCategoriesController < Admins::BaseController
max_position_items = ProjectCategory.select(:id, :position).pluck(:position).reject!(&:blank?)
max_position = max_position_items.present? ? max_position_items.max.to_i : 0
@project_category = ProjectCategory.new(name: @name,position: max_position, pinned_index: params[:project_category][:pinned_index].to_i)
@project_category = ProjectCategory.new(name: @name,position: max_position)
if @project_category.save
redirect_to admins_project_categories_path
flash[:success] = '创建成功'
@ -33,18 +33,17 @@ class Admins::ProjectCategoriesController < Admins::BaseController
end
def update
if @project_category.update_attributes({name: @name, pinned_index: params[:project_category][:pinned_index].to_i})
save_image_file(params[:logo], 'logo')
if @project_category.update_attribute(:name, @name)
redirect_to admins_project_categories_path
flash[:success] = '更新成功'
else
redirect_to admins_project_categories_path
flash[:danger] = '更新失败'
flash[:success] = '更新失败'
end
end
def destroy
if @project_category.destroy
if @project_language.destroy
redirect_to admins_project_categories_path
flash[:success] = "删除成功"
else
@ -81,12 +80,4 @@ class Admins::ProjectCategoriesController < Admins::BaseController
flash[:danger] = '分类已存在'
end
end
def save_image_file(file, type)
return unless file.present? && file.is_a?(ActionDispatch::Http::UploadedFile)
file_path = Util::FileManage.source_disk_filename(@project_category, type)
File.delete(file_path) if File.exist?(file_path) # 删除之前的文件
Util.write_file(file, file_path)
end
end

View File

@ -3,8 +3,8 @@ class Admins::ProjectIgnoresController < Admins::BaseController
before_action :validate_params, only: [:create, :update]
def index
sort_by = Ignore.column_names.include?(params[:sort_by]) ? params[:sort_by] : 'created_at'
sort_direction = %w(desc asc).include?(params[:sort_direction]) ? params[:sort_direction] : 'desc'
sort_by = params[:sort_by] ||= 'created_at'
sort_direction = params[:sort_direction] ||= 'desc'
q = Ignore.ransack(name_cont: params[:search])
project_ignores = q.result(distinct: true).order("#{sort_by} #{sort_direction}")
@project_ignores = paginate(project_ignores)

View File

@ -3,8 +3,8 @@ class Admins::ProjectLanguagesController < Admins::BaseController
before_action :validate_names, only: [:create, :update]
def index
sort_by = ProjectLanguage.column_names.include?(params[:sort_by]) ? params[:sort_by] : 'created_at'
sort_direction = %w(desc asc).include?(params[:sort_direction]) ? params[:sort_direction] : 'desc'
sort_by = params[:sort_by] ||= 'created_at'
sort_direction = params[:sort_direction] ||= 'desc'
q = ProjectLanguage.ransack(name_cont: params[:search])
project_languages = q.result(distinct: true).order("#{sort_by} #{sort_direction}")
@project_languages = paginate(project_languages)

View File

@ -3,8 +3,8 @@ class Admins::ProjectLicensesController < Admins::BaseController
before_action :validate_params, only: [:create, :update]
def index
sort_by = License.column_names.include?(params[:sort_by]) ? params[:sort_by] : 'created_at'
sort_direction = %w(desc asc).include?(params[:sort_direction]) ? params[:sort_direction] : 'desc'
sort_by = params[:sort_by] ||= 'created_at'
sort_direction = params[:sort_direction] ||= 'desc'
q = License.ransack(name_cont: params[:search])
project_licenses = q.result(distinct: true).order("#{sort_by} #{sort_direction}")
@project_licenses = paginate(project_licenses)

View File

@ -1,34 +1,14 @@
class Admins::ProjectsController < Admins::BaseController
before_action :find_project, only: [:edit, :update]
def index
sort_by = Project.column_names.include?(params[:sort_by]) ? params[:sort_by] : 'created_on'
sort_direction = %w(desc asc).include?(params[:sort_direction]) ? params[:sort_direction] : 'desc'
sort_by = params[:sort_by] ||= 'created_on'
sort_direction = params[:sort_direction] ||= 'desc'
search = params[:search].to_s.strip
projects = Project.where("name like ?", "%#{search}%").order("#{sort_by} #{sort_direction}")
@projects = paginate projects.includes(:owner, :members, :issues, :versions, :attachments, :project_score)
end
def edit ;end
def update
respond_to do |format|
if @project.update_attributes(project_update_params)
format.html do
redirect_to admins_projects_path
flash[:sucess] = "更新成功"
end
format.js {render_ok}
else
format.html do
redirect_to admins_projects_path
flash[:danger] = "更新失败"
end
format.js {render_js_error}
end
end
end
def destroy
project = Project.find_by!(id: params[:id])
ActiveRecord::Base.transaction do
@ -42,13 +22,4 @@ class Admins::ProjectsController < Admins::BaseController
redirect_to admins_projects_path
flash[:danger] = "删除失败"
end
private
def find_project
@project = Project.find_by_id(params[:id])
end
def project_update_params
params.require(:project).permit(:is_pinned, :recommend, :recommend_index)
end
end

View File

@ -1,6 +1,4 @@
class Admins::UsersController < Admins::BaseController
before_action :finder_user, except: [:index]
def index
params[:sort_by] = params[:sort_by].presence || 'created_on'
params[:sort_direction] = params[:sort_direction].presence || 'desc'
@ -10,9 +8,12 @@ class Admins::UsersController < Admins::BaseController
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
Admins::UpdateUserService.call(@user, update_params)
flash[:success] = '保存成功'
redirect_to edit_admins_user_path(@user)
@ -25,47 +26,43 @@ class Admins::UsersController < Admins::BaseController
end
def destroy
@user.destroy!
Gitea::User::DeleteService.call(@user.login)
User.find(params[:id]).destroy!
render_delete_success
end
def lock
@user.lock!
User.find(params[:id]).lock!
render_ok
end
def unlock
@user.activate!
User.find(params[:id]).activate!
render_ok
end
def reward_grade
user = User.find(params[:user_id])
return render_unprocessable_entity('金币数量必须大于0') if params[:grade].to_i <= 0
RewardGradeService.call(@user, container_id: @user.id, container_type: 'Feedback', score: params[:grade].to_i, not_unique: true)
RewardGradeService.call(user, container_id: user.id, container_type: 'Feedback', score: params[:grade].to_i, not_unique: true)
render_ok(grade: @user.grade)
render_ok(grade: user.grade)
end
def reset_login_times
@user.reset_login_times!
User.find(params[:id]).reset_login_times!
render_ok
end
private
def finder_user
@user = User.find(params[:id])
end
def update_params
params.require(:user).permit(%i[lastname nickname gender identity technical_title student_id is_shixun_marker
mail phone location location_city school_id department_id admin business is_test
password professional_certification authentication login])
password professional_certification authentication])
end
end

View File

@ -26,10 +26,9 @@ class ApplicationController < ActionController::Base
end
DCODES = %W(2 3 4 5 6 7 8 9 a b c f e f g h i j k l m n o p q r s t u v w x y z)
OPENKEY = Rails.application.config_for(:configuration)['sign_key'] || "79e33abd4b6588941ab7622aed1e67e8"
OPENKEY = "79e33abd4b6588941ab7622aed1e67e8"
helper_method :current_user, :base_url
helper_method :current_user
# 所有请求必须合法签名
def check_sign
@ -71,11 +70,49 @@ class ApplicationController < ActionController::Base
(current_user.professional_certification && (ue.teacher? || ue.professional?))
end
def shixun_marker
unless current_user.is_shixun_marker? || current_user.admin_or_business?
tip_exception(403, "..")
end
end
# 实训的访问权限
def shixun_access_allowed
if !current_user.shixun_permission(@shixun)
tip_exception(403, "..")
end
end
def admin_or_business?
User.current.admin? || User.current.business?
end
# 访问课堂时没权限直接弹加入课堂的弹框 409
def user_course_identity
@user_course_identity = current_user.course_identity(@course)
if @user_course_identity > Course::STUDENT && @course.is_public == 0
tip_exception(401, "..") unless User.current.logged?
check_account
tip_exception(@course.excellent ? 410 : 409, "您没有权限进入")
end
if @user_course_identity > Course::CREATOR && @user_course_identity <= Course::STUDENT && @course.tea_id != current_user.id
# 实名认证和职业认证的身份判断
tip_exception(411, "你的实名认证和职业认证审核未通过") if @course.authentication &&
@course.professional_certification && (!current_user.authentication && !current_user.professional_certification)
tip_exception(411, "你的实名认证审核未通过") if @course.authentication && !current_user.authentication
tip_exception(411, "你的职业认证审核未通过") if @course.professional_certification && !current_user.professional_certification
end
uid_logger("###############user_course_identity:#{@user_course_identity}")
end
# 题库的访问权限
def bank_visit_auth
tip_exception(-2,"未通过职业认证") if current_user.is_teacher? && !current_user.certification_teacher? && !current_user.admin_or_business? && @bank.user_id != current_user.id && @bank.is_public
tip_exception(403, "无权限") unless @bank.user_id == current_user.id || current_user.admin_or_business? ||
(current_user.certification_teacher? && @bank.is_public)
end
# 判断用户的邮箱或者手机是否可用
# params[:type] 1: 注册2忘记密码3绑定
def check_mail_and_phone_valid login, type
@ -83,16 +120,16 @@ class ApplicationController < ActionController::Base
login =~ /^[a-zA-Z0-9]+([._\\]*[a-zA-Z0-9])$/
tip_exception(-2, "请输入正确的手机号或邮箱")
end
user_exist = Owner.exists?(phone: login) || Owner.exists?(mail: login)
if user_exist && type.to_i == 1
# 考虑到安全参数问题多一次查询去掉Union
user = User.where(phone: login).first || User.where(mail: login).first
if type.to_i == 1 && !user.nil?
tip_exception(-2, "该手机号码或邮箱已被注册")
elsif type.to_i == 2 && !user_exist
elsif type.to_i == 2 && user.nil?
tip_exception(-2, "该手机号码或邮箱未注册")
elsif type.to_i == 3 && user_exist
elsif type.to_i == 3 && user.present?
tip_exception(-2, "该手机号码或邮箱已绑定")
end
render_ok
sucess_status
end
# 发送及记录激活码
@ -103,7 +140,7 @@ class ApplicationController < ActionController::Base
when 1, 2, 4, 9
# 手机类型的发送
sigle_para = {phone: value}
status = Gitlink::Sms.send(mobile: value, code: code)
status = Educoder::Sms.send(mobile: value, code: code)
tip_exception(-2, code_msg(status)) if status != 0
when 8, 3, 5
# 邮箱类型的发送
@ -149,6 +186,26 @@ class ApplicationController < ActionController::Base
end
end
def find_course
return normal_status(2, '缺少course_id参数') if params[:course_id].blank?
@course = Course.find(params[:course_id])
tip_exception(404, "") if @course.is_delete == 1 && !current_user.admin_or_business?
rescue Exception => e
tip_exception(e.message)
end
def course_manager
return normal_status(403, '只有课堂管理员才有权限') if @user_course_identity > Course::CREATOR
end
def find_board
return normal_status(2, "缺少board_id参数") if params[:board_id].blank?
@board = Board.find(params[:board_id])
rescue Exception => e
uid_logger_error(e.message)
tip_exception(e.message)
end
def validate_type(object_type)
normal_status(2, "参数") if params.has_key?(:sort_type) && !SORT_TYPE.include?(params[:sort_type].strip)
end
@ -158,6 +215,21 @@ class ApplicationController < ActionController::Base
@page_size = params[:page_size] || 15
end
# 课堂教师权限
def teacher_allowed
logger.info("#####identity: #{current_user.course_identity(@course)}")
unless current_user.course_identity(@course) < Course::STUDENT
normal_status(403, "")
end
end
# 课堂教师、课堂管理员、超级管理员的权限(不包含助教)
def teacher_or_admin_allowed
unless current_user.course_identity(@course) < Course::ASSISTANT_PROFESSOR
normal_status(403, "")
end
end
def require_admin
normal_status(403, "") unless User.current.admin?
end
@ -174,17 +246,9 @@ class ApplicationController < ActionController::Base
tip_exception(401, "请登录后再操作") unless User.current.logged?
end
def require_profile_completed
tip_exception(411, "请完善资料后再操作") unless User.current.profile_is_completed?
end
def require_user_profile_completed(user)
tip_exception(412, "请用户完善资料后再操作") unless user.profile_is_completed?
end
# 异常提醒
def tip_exception(status = -1, message)
raise Gitlink::TipException.new(status, message)
raise Educoder::TipException.new(status, message)
end
def missing_template
@ -193,7 +257,7 @@ class ApplicationController < ActionController::Base
# 弹框提醒
def tip_show_exception(status = -2, message)
raise Gitlink::TipException.new(status, message)
raise Educoder::TipException.new(status, message)
end
def normal_status(status = 0, message)
@ -208,7 +272,7 @@ class ApplicationController < ActionController::Base
# 资料是否完善
def check_account
if !current_user. profile_is_completed?
if !current_user.profile_completed?
#info_url = '/account/profile'
tip_exception(402, nil)
end
@ -265,6 +329,7 @@ class ApplicationController < ActionController::Base
User.current = user
end
end
# if !User.current.logged? && Rails.env.development?
# User.current = User.find 1
# end
@ -272,18 +337,17 @@ class ApplicationController < ActionController::Base
# 测试版前端需求
logger.info("subdomain:#{request.subdomain}")
# if request.subdomain != "www"
# if params[:debug] == 'teacher' #todo 为了测试,记得讲debug删除
# User.current = User.find 81403
# elsif params[:debug] == 'student'
# User.current = User.find 8686
# elsif params[:debug] == 'admin'
# logger.info "@@@@@@@@@@@@@@@@@@@@@@ debug mode....."
# user = User.find 36480
# User.current = user
# cookies.signed[:user_id] = user.id
# end
# end
if request.subdomain != "www"
if params[:debug] == 'teacher' #todo 为了测试,记得讲debug删除
User.current = User.find 81403
elsif params[:debug] == 'student'
User.current = User.find 8686
elsif params[:debug] == 'admin'
user = User.find 1
User.current = user
cookies.signed[:user_id] = user.id
end
end
# User.current = User.find 81403
end
@ -320,7 +384,11 @@ class ApplicationController < ActionController::Base
end
def current_user
User.current
if Rails.env.development?
User.current = User.find 1
else
User.current
end
end
## 默认输出json
@ -336,6 +404,11 @@ class ApplicationController < ActionController::Base
@message = message
end
# 实训等对应的仓库地址
def repo_ip_url(repo_path)
"#{edu_setting('git_address_ip')}/#{repo_path}"
end
def repo_url(repo_path)
"#{edu_setting('git_address_domain')}/#{repo_path}"
end
@ -368,7 +441,7 @@ class ApplicationController < ActionController::Base
JSON.parse(res)
rescue Exception => e
uid_logger_error("--uri_exec: exception #{e.message}")
raise Gitlink::TipException.new("实训平台繁忙繁忙等级84")
raise Educoder::TipException.new("实训平台繁忙繁忙等级84")
end
end
@ -387,7 +460,7 @@ class ApplicationController < ActionController::Base
end
rescue Exception => e
uid_logger("--uri_exec: exception #{e.message}")
raise Gitlink::TipException.new(message)
raise Educoder::TipException.new(message)
end
end
@ -411,7 +484,7 @@ class ApplicationController < ActionController::Base
end
rescue Exception => e
uid_logger("--uri_exec: exception #{e.message}")
raise Gitlink::TipException.new("服务器繁忙")
raise Educoder::TipException.new("服务器繁忙")
end
end
@ -545,8 +618,8 @@ class ApplicationController < ActionController::Base
end
# 排序
rorder = UserExtension.column_names.include?(option[:order]) ? option[:order] : "updated_at"
b_order = %w(desc asc).include?(option[:b_order]) ? option[:b_order] : "desc"
rorder = option[:order] || "updated_at"
b_order = option[:b_order] || "desc"
if rorder == "created_at" || rorder == "work_score"
work_list = work_list.order("graduation_works.#{rorder} #{b_order}")
elsif rorder == "student_id"
@ -583,8 +656,8 @@ class ApplicationController < ActionController::Base
# 获取Oauth Client
def get_client(site)
client_id = Rails.configuration.Gitlink['client_id']
client_secret = Rails.configuration.Gitlink['client_secret']
client_id = Rails.configuration.educoder['client_id']
client_secret = Rails.configuration.educoder['client_secret']
OAuth2::Client.new(client_id, client_secret, site: site)
end
@ -604,20 +677,12 @@ class ApplicationController < ActionController::Base
def kaminari_paginate(relation)
limit = params[:limit] || params[:per_page]
limit = (limit.to_i.zero? || limit.to_i > 20) ? 20 : limit.to_i
limit = (limit.to_i.zero? || limit.to_i > 15) ? 15 : limit.to_i
page = params[:page].to_i.zero? ? 1 : params[:page].to_i
relation.page(page).per(limit)
end
def kaminari_array_paginate(relation)
limit = params[:limit] || params[:per_page]
limit = (limit.to_i.zero? || limit.to_i > 20) ? 20 : limit.to_i
page = params[:page].to_i.zero? ? 1 : params[:page].to_i
Kaminari.paginate_array(relation).page(page).per(limit)
end
def strf_time(time)
time.blank? ? '' : time.strftime("%Y-%m-%d %H:%M:%S")
end
@ -679,15 +744,15 @@ class ApplicationController < ActionController::Base
namespace = params[:owner]
id = params[:repo] || params[:id]
@project, @owner = Project.find_with_namespace(namespace, id)
@project = Project.find_with_namespace(namespace, id)
if @project and current_user.can_read_project?(@project)
logger.info "########### has project and can read project"
@project
# elsif @project && current_user.is_a?(AnonymousUser)
# logger.info "###########This is AnonymousUser"
# @project = nil if !@project.is_public?
# render_forbidden and return
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
@ -697,34 +762,9 @@ class ApplicationController < ActionController::Base
end
def load_repository
@repository ||= load_project&.repository
@repository ||= load_project.repository
end
def base_url
Rails.application.config_for(:configuration)['platform_url'] || request.base_url
end
def convert_image!
@image = params[:image]
@image = @image.nil? && params[:user].present? ? params[:user][:image] : @image
return unless @image.present?
max_size = EduSetting.get('upload_avatar_max_size') || 2 * 1024 * 1024 # 2M
if @image.class == ActionDispatch::Http::UploadedFile
render_error('请上传文件') if @image.size.zero?
render_error('文件大小超过限制') if @image.size > max_size.to_i
else
image = @image.to_s.strip
return render_error('请上传正确的图片') if image.blank?
@image = Util.convert_base64_image(image, max_size: max_size.to_i)
end
rescue Base64ImageConverter::Error => ex
render_error(ex.message)
end
def avatar_path(object)
ApplicationController.helpers.disk_filename(object.class, object.id)
end
private
def object_not_found
uid_logger("Missing template or cant't find record, responding with 404")
@ -737,10 +777,37 @@ class ApplicationController < ActionController::Base
render json: exception.tip_json
end
def render_parameter_missing
render json: { status: -1, message: '参数缺失' }
end
def set_export_cookies
cookies[:fileDownload] = true
end
# 149课程的评审用户数据创建包含创建课堂学生
def open_class_user
user = User.find_by(login: "OpenClassUser")
unless user
ActiveRecord::Base.transaction do
user_params = {status: 1, login: "OpenClassUser", lastname: "开放课程",
nickname: "开放课程", professional_certification: 1, certification: 1, grade: 0,
password: "12345678", phone: "11122223333", profile_completed: 1}
user = User.create!(user_params)
UserExtension.create!(user_id: user.id, gender: 0, school_id: 3396, :identity => 1, :student_id => "openclassuser") # 3396
subject = Subject.find_by(id: 149)
if subject
subject.courses.each do |course|
CourseMember.create!(course_id: course.id, role: 3, user_id: user.id) if !course.course_members.exists?(user_id: user.id)
end
end
end
end
user
end
# 记录热门搜索关键字
def record_search_keyword
keyword = params[:keyword].to_s.strip
@ -750,8 +817,4 @@ class ApplicationController < ActionController::Base
HotSearchKeyword.add(keyword)
end
def find_atme_receivers
@atme_receivers = User.where(login: params[:receivers_login])
end
end

View File

@ -28,21 +28,12 @@ class AttachmentsController < ApplicationController
update_downloads(@file)
end
def get_file
def get_file
normal_status(-1, "参数缺失") if params[:download_url].blank?
url = URI.encode(params[:download_url].to_s.gsub("http:", "https:"))
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
response = Faraday.get(url)
filename = params[:download_url].to_s.split("/").pop()
send_data(response.body.force_encoding("UTF-8"), filename: filename, type: "application/octet-stream", disposition: 'attachment')
end
@ -54,7 +45,7 @@ class AttachmentsController < ApplicationController
uid_logger("#########################file_params####{params["#{params[:file_param_name]}"]}")
raise "未上传文件" unless upload_file
folder = file_storage_directory
folder = edu_setting('attachment_folder')
raise "存储目录未定义" unless folder.present?
month_folder = current_month_folder
@ -117,7 +108,7 @@ class AttachmentsController < ApplicationController
end
# 附件为视频时,点击播放
def preview_attachment
def preview_attachment
attachment = Attachment.find_by(id: params[:id])
dir_path = "#{Rails.root}/public/preview"
Dir.mkdir(dir_path) unless Dir.exist?(dir_path)
@ -127,10 +118,10 @@ class AttachmentsController < ApplicationController
else
normal_status(-1, "出现错误,请稍后重试")
end
else
else
if system("rm -rf #{dir_path}/#{attachment.disk_filename}")
normal_status(1, "操作成功")
else
else
normal_status(-1, "出现错误,请稍后重试")
end
end
@ -196,7 +187,7 @@ class AttachmentsController < ApplicationController
end
def file_save_to_ucloud(path, file, content_type)
ufile = Gitlink::Ufile.new(
ufile = Educoder::Ufile.new(
ucloud_public_key: edu_setting('public_key'),
ucloud_private_key: edu_setting('private_key'),
ucloud_public_read: true,

View File

@ -0,0 +1,36 @@
# encoding=utf-8
class CategoriesController < ApplicationController
before_action :require_login, :except => [:all]
include ApplicationHelper
# 所有类型,通过参数过滤
def all
render_react
end
def guide
render_react
end
def techShare
render_react
end
def show
render_react
end
def shixun_discuss
render_react
end
# 我的发布
def my_published
end
private
def render_react
render "/common/index", :layout => false
end
end

View File

@ -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, "在这些分支之间的合并请求已存在:<a href='/#{@owner.login}/#{@project.identifier}/pulls/#{@exist_pullrequest.id}'>#{@exist_pullrequest.try(:title)}</a>"
return -2, "在这些分支之间的合并请求已存在:<a href='/projects/#{@owner.login}/#{@project.identifier}/pulls/#{@exist_pullrequest.id}/Messagecount'>#{@exist_pullrequest.try(:title)}</a>"
else
if @compare_result["Commits"].blank? && @compare_result["Diff"].blank?
return -2, "分支内容相同,无需创建合并请求"

View File

@ -3,12 +3,13 @@ class ComposesController < ApplicationController
before_action :find_compose, except: [:index, :new,:create]
def index
@order_type = params[:order] || "created_at"
@search_name = params[:search]
composes = Compose.compose_includes
if @search_name.present?
composes = composes.where("title like ?", "%#{@search_name}%")
end
composes = composes.order("#{order_type} desc")
composes = composes.order("#{@order_type} desc")
@page = params[:page] || 1
@limit = params[:limit] || 15
@composes_size = composes.size
@ -95,8 +96,4 @@ class ComposesController < ApplicationController
end
end
def order_type
Compose.column_names.include?(params[:order_type]) ? params[:order_type] : 'created_at'
end
end

View File

@ -20,7 +20,7 @@ module ControllerRescueHandler
end
# rescue_from ActionView::MissingTemplate, with: :object_not_found
# rescue_from ActiveRecord::RecordNotFound, with: :object_not_found
rescue_from Gitlink::TipException, with: :tip_show
rescue_from Educoder::TipException, with: :tip_show
rescue_from ::ActionView::MissingTemplate, with: :missing_template
rescue_from ActiveRecord::RecordNotFound, with: :object_not_found
rescue_from ActionController::ParameterMissing, with: :render_parameter_missing

View File

@ -36,10 +36,10 @@ module GitCommon
begin
@commits = GitService.commits(repo_path: @repo_path)
logger.info("git first commit is #{@commits.try(:first)}")
raise Gitlink::TipException.new("请先创建版本库") if @commits.nil?
raise Educoder::TipException.new("请先创建版本库") if @commits.nil?
rescue Exception => e
uid_logger_error(e.message)
raise Gitlink::TipException.new("提交记录异常")
raise Educoder::TipException.new("提交记录异常")
end
end

View File

@ -34,7 +34,7 @@ module GitHelper
rescue Exception => e
Rails.logger.error(e.message)
raise Gitlink::TipException.new("文档内容获取异常")
raise Educoder::TipException.new("文档内容获取异常")
end
end
@ -64,7 +64,7 @@ module GitHelper
# 版本库Fork功能
def project_fork(container, original_rep_path, username)
raise Gitlink::TipException.new("fork源路径为空,fork失败!") if original_rep_path.blank?
raise Educoder::TipException.new("fork源路径为空,fork失败!") if original_rep_path.blank?
# 将要生成的仓库名字
new_repo_name = "#{username.try(:strip)}/#{container.try(:identifier)}#{ Time.now.strftime("%Y%m%d%H%M%S")}"
# uid_logger("start fork container: repo_name is #{new_repo_name}")

View File

@ -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: Rails.application.config_for(:configuration)['platform_url'],
default_url: "https://www.trustie.net/",
tiding_url: "https://www.trustie.net/users/#{current_user.try(:login)}/user_messages",
register_url: "https://www.trustie.net/login?login=false"
}

View File

@ -127,8 +127,6 @@ module LoginHelper
token = config[:sync_token]
api_host = config[:sync_url]
return if api_host.blank?
url = "#{api_host}/api/v1/users/sync_user_token"
sync_json = {
"token": token,

View File

@ -1,14 +1,12 @@
module PaginateHelper
def paginate(objs, **opts)
page = params[:page].to_i <= 0 ? 1 : params[:page].to_i
per_page = params[:per_page].to_i > 0 && params[:per_page].to_i < 50 ? params[:per_page].to_i : opts[:per_page] || 20
def paginate(relation)
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
if relation.is_a?(Array)
Kaminari.paginate_array(relation).page(page).per(limit)
if objs.is_a?(Array)
Kaminari.paginate_array(objs).page(page).per(per_page)
else
relation.page(page).per(limit)
objs.page(page).per(per_page)
end
end
end

View File

@ -1,26 +1,20 @@
module RegisterHelper
extend ActiveSupport::Concern
def autologin_register(username, email, password, platform= 'forge', need_edit_info = false)
def autologin_register(username, email, password, platform= '')
result = {message: nil, user: nil}
user = User.new(admin: false, login: username, mail: email, type: "User")
user.password = password
user.platform = platform
if need_edit_info
user.need_edit_info
else
user.activate
end
return unless user.valid?
user.activate
interactor = Gitea::RegisterInteractor.call({username: username, email: email, password: password})
if interactor.success?
gitea_user = interactor.result
result = Gitea::User::GenerateTokenService.call(username, password)
result = Gitea::User::GenerateTokenService.new(username, password).call
user.gitea_token = result['sha1']
user.gitea_uid = gitea_user[:body]['id']
user.gitea_uid = gitea_user['id']
if user.save!
UserExtension.create!(user_id: user.id)
result[:user] = {id: user.id, token: user.gitea_token}
@ -31,31 +25,4 @@ module RegisterHelper
result
end
def autosync_register_trustie(username, password, email, lastname="")
config = Rails.application.config_for(:configuration).symbolize_keys!
api_host = config[:sync_url]
return if api_host.blank?
url = "#{api_host}/api/v1/users/common"
sync_json = {
"mail": email,
"password": password,
"login": username,
"lastname": lastname
}.compact
uri = URI.parse(url)
if api_host
http = Net::HTTP.new(uri.hostname, uri.port)
if api_host.include?("https://")
http.use_ssl = true
end
http.send_request('POST', uri.path, sync_json.to_json, {'Content-Type' => 'application/json'})
end
end
end

View File

@ -28,8 +28,4 @@ module RenderHelper
def render_result(status=1, message='success')
render json: { status: status, message: message }
end
def render_parameter_missing
render json: { status: -1, message: '参数缺失' }
end
end

View File

@ -0,0 +1,11 @@
class CustomersController < ApplicationController
def show
targets = UsersService.new.user_info params, current_user
render json: targets
end
def edit_brief
targets = UsersService.new.edit_brief params, current_user
render json: targets
end
end

View File

@ -29,8 +29,10 @@ 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
@ -41,8 +43,10 @@ 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
@ -53,6 +57,7 @@ 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

View File

@ -1,6 +1,5 @@
class ForksController < ApplicationController
before_action :require_login
before_action :require_profile_completed, only: [:create]
before_action :load_project
before_action :authenticate_project!, :authenticate_user!

View File

@ -0,0 +1,101 @@
class ForumSectionsController < ApplicationController
def index
targets = ForumSectionsService.new.index params
render json: targets
end
def select_sections
targets = ForumSectionsService.new.select_sections
render json: targets
end
def user_apply
targets = ForumSectionsService.new.user_apply params, current_user, current_user_ip
render json: targets
end
def edit_notice
targets = ForumSectionsService.new.edit_notice params
render json: targets
end
def forum_section_header
targets = ForumSectionsService.new.forum_section_header params, current_user
render json: targets
end
def create
targets = ForumSectionsService.new.create params, current_user
render json: targets
end
def rename
targets = ForumSectionsService.new.rename params, current_user
render json: targets
end
def destroy_forum
targets = ForumSectionsService.new.destroy params, current_user
render json: targets
end
def order_forums
targets = ForumSectionsService.new.order_forums params, current_user
render json: targets
end
def search_users
targets = ForumSectionsService.new.search_users params, current_user
render json: targets
end
def add_users
targets = ForumSectionsService.new.add_users params, current_user
render json: targets
end
def managements
targets = ForumSectionsService.new.managements params, current_user
render json: targets
end
def applied_forums
targets = ForumSectionsService.new.applied_forums params, current_user
render json: targets
end
def deal_applies
targets = ForumSectionsService.new.deal_applies params, current_user
render json: targets
end
def destroy_moderator
targets = ForumSectionsService.new.destroy_moderator params, current_user
render json: targets
end
def unchecked_memos
targets = ForumSectionsService.new.unchecked_memos params, current_user
render json: targets
end
def unchecked_replies
targets = ForumSectionsService.new.unchecked_replies params, current_user
render json: targets
end
def checked_memos
targets = ForumSectionsService.new.checked_memos params, current_user
render json: targets
end
private
def current_user_ip
env['REMOTE_ADDR']
end
end

View File

@ -0,0 +1,434 @@
# encoding=utf-8
# For react
class ForumsController < ApplicationController
before_action :require_login, :only => [:new, :edit]
include ApplicationHelper
def show
render_react
end
def new
render_react
end
def index
render_react
end
def edit
render_react
end
def shixun_discuss
render_react
end
def manage
render_react
end
def detail
render_react
end
def theme
render_react
end
private
def render_react
render file: 'public/react/build/index.html', :layout => false
end
end
# # encoding: utf-8
# # added by fq
# class ForumsController < ApplicationController
# layout "users_base"
# include ApplicationHelper
# # GET /forums
# # GET /forums.json
# before_action :find_forum_if_available
# before_action :authenticate_user_edit, :only => [:edit, :update]
# before_action :authenticate_user_destroy, :only => [:destroy]
# before_action :require_login, :only => [:new, :create,:destroy,:update,:edit]
# before_action :check_authentication
#
# helper :sort
# include SortHelper
#
# PageLimit = 20
# def create_feedback
# if User.current.logged?
# #@memo = Memo.new(params[:memo])
# #@memo.forum_id = "1"
# #@memo.author_id = User.current.id
# #@forum = @memo.forum
# cs = CommentService.new
# @memo,message = cs.create_feedback params,User.current
# respond_to do |format|
# if !@memo.new_record?
# if params[:direct]
# format.html { redirect_to forums_path() }
# else
# format.html { redirect_to forum_path(@memo.forum) }
# end
# # format.html { redirect_to forum_path(@memo.forum) }
# else
# sort_init 'updated_at', 'desc'
# sort_update 'created_at' => "#{Memo.table_name}.created_at",
# 'replies' => "#{Memo.table_name}.replies_count",
# 'updated_at' => "COALESCE (last_replies_memos.created_at, #{Memo.table_name}.created_at)"
#
# @topic_count = @forum.topics.count
# @topic_pages = Paginator.new @topic_count, per_page_option, params['page']
# @memos = @forum.topics.
# reorder("#{Memo.table_name}.sticky DESC").
# includes(:last_reply).
# limit(@topic_pages.per_page).
# offset(@topic_pages.offset).
# order(sort_clause).
# preload(:author, {:last_reply => :author}).
# all
#
# flash.now[:error] = "#{l :label_memo_create_fail}: #{@memo.errors.full_messages[0]}"
# # back_error_page = @memo.parent_id.nil? ? forum_path(@forum) : forum_memo_path(@forum, @memo.parent_id)
# format.html { render action: :show, layout: 'base_forums' }#, error: "#{l :label_memo_create_fail}: #{@memo.errors.full_messages[0]}" }
# format.json { render json: @memo.errors, status: :unprocessable_entity }
# end
# end
# else
# respond_to do |format|
# format.html { redirect_to signin_path }
# end
# end
# end
#
# def mail_feedback
# @user = User.where(:id => params[:user_id]).first
# unless @user.nil?
# cs = CommentService.new
# @memo, message = cs.create_feedback params, @user
# end
# respond_to do |format|
# format.js
# end
# end
#
# def forum_create_memo
# @memo = Memo.new
# @my_forums_count = Forum.where(:creator_id => User.current.id).count
# @my_memos_count = Memo.where(:author_id => User.current.id).count
# @forums = Forum.reorder("topic_count desc,updated_at desc")
# respond_to do |format|
# format.js
# format.html {render layout: 'base_new_forum'}
# end
# end
#
# def create_memo
# @memo = Memo.new(params[:memo])
# @memo.forum_id = @forum.id
# @memo.author_id = User.current.id
#
# @memo.save_attachments(params[:attachments] || (params[:memo] && params[:memo][:uploads]))
#
# respond_to do |format|
# if @memo.save
# if params[:asset_id]
# ids = params[:asset_id].split(',')
# update_kindeditor_assets_owner ids ,@memo.id,OwnerTypeHelper::MEMO
# end
# #end
# format.html { redirect_to (forum_memo_url(@forum, (@memo.parent_id.nil? ? @memo : @memo.parent_id))), notice: "#{l :label_memo_create_succ}" }
# format.json { render json: @memo, status: :created, location: @memo }
# else
# sort_init 'updated_at', 'desc'
# sort_update 'created_at' => "#{Memo.table_name}.created_at",
# 'replies' => "#{Memo.table_name}.replies_count",
# 'updated_at' => "COALESCE (last_replies_memos.created_at, #{Memo.table_name}.created_at)"
#
# @topic_count = @forum.topics.count
# @topic_pages = Paginator.new @topic_count, per_page_option, params['page']
# @memos = @forum.topics.
# reorder("#{Memo.table_name}.sticky DESC").
# includes(:last_reply).
# limit(@topic_pages.per_page).
# offset(@topic_pages.offset).
# order(sort_clause).
# preload(:author, {:last_reply => :author}).
# all
# @memos
# flash.now[:error] = "#{l :label_memo_create_fail}: #{@memo.errors.full_messages[0]}"
# # back_error_page = @memo.parent_id.nil? ? forum_path(@forum) : forum_memo_path(@forum, @memo.parent_id)
# format.html { render action: :show, layout: 'base_forums' }#, error: "#{l :label_memo_create_fail}: #{@memo.errors.full_messages[0]}" }
# format.json { render json: @memo.errors, status: :unprocessable_entity }
# end
# end
# end
#
# # id: 1 问题反馈 3 操作指南 5 技术分享
# def index
#
# render "/common/index", :layout => false
# end
#
# # GET /forums/1
# # GET /forums/1.json
# def show
# # sort_init 'updated_at', 'desc'
# # sort_update 'created_at' => "#{Memo.table_name}.created_at",
# # 'replies' => "#{Memo.table_name}.replies_count",
# # 'updated_at' => "COALESCE (last_replies_memos.created_at, #{Memo.table_name}.created_at)"
# order = ""
# @order_str = ""
# if(params[:reorder_complex])
# order = "#{Memo.table_name}.sticky desc, last_replies_memos.created_at #{params[:reorder_complex]}, #{Memo.table_name}.created_at #{params[:reorder_complex]}"
# @order_str = "reorder_complex="+params[:reorder_complex]
# elsif(params[:reorder_popu])
# order = "#{Memo.table_name}.sticky desc, replies_count #{params[:reorder_popu]}"
# @order_str = "reorder_popu="+params[:reorder_popu]
# elsif(params[:reorder_time])
# order = "#{Memo.table_name}.sticky desc, #{Memo.table_name}.updated_at #{params[:reorder_time]}"
# @order_str = "reorder_time="+params[:reorder_time]
# else
# order = "#{Memo.table_name}.sticky desc, #{Memo.table_name}.updated_at desc"
# @order_str = "reorder_time=desc"
# end
# @memo = Memo.new(:forum => @forum)
# @topic_count = @forum.topics.count
# @limit = 20
# @is_remote = true
# @topic_pages = Paginator.new @topic_count, @limit, params['page'] || 1
# @memos = paginateHelper @forum.topics.includes(:last_reply).reorder(order).preload(:author, {:last_reply => :author}), @limit
# @my_topic_count = Memo.where("forum_id = #{@memo.forum_id} and parent_id is null").count
# @my_replies_count = Memo.where("forum_id = #{@memo.forum_id} and parent_id is not null").count
# @errors = params[:errors]
# # 推荐贴吧
# @forums = Forum.where("id !=?", @forum.id).reorder("topic_count desc,updated_at desc").first(3)
# respond_to do |format|
# format.js
# format.html {
# render :layout => 'base_new_forum'
# }# show.html.erb
# format.json { render json: @forum }
# end
# end
#
# # GET /forums/new
# # GET /forums/new.json
# def new
# @forum = Forum.new
# respond_to do |format|
# format.html # new.html.erb
# format.js
# format.json { render json: @forum }
# end
# end
#
# # GET /forums/1/edit
# def edit
# @forum = Forum.find(params[:id])
# respond_to do |format|
# format.html
# format.js
# end
# end
#
# # POST /forums
# # POST /forums.json
# def create
# @forum = Forum.new(params[:forum])
# @forum.creator_id = User.current.id
# if @forum.save
# # Time 2015-03-24 17:07:05
# # Author lizanle
# # Description after save后需要进行资源记录的更新
# # owner_type = 2 对应的是 forum
# @save_flag = true
# if params[:asset_id]
# ids = params[:asset_id].split(',')
# update_kindeditor_assets_owner ids, @forum.id, OwnerTypeHelper::FORUM
# end
# #end
# respond_to do |format|
# format.js{ redirect_to forums_path, notice: l(:label_forum_create_succ)}
# format.html { redirect_to @forum, notice: l(:label_forum_create_succ) }
# format.json { render json: @forum, status: :created, location: @forum }
# end
# else
# @save_flag=false
# respond_to do |format|
# flash.now[:error] = "#{l :label_forum_create_fail}: #{@forum.errors.full_messages[0]}"
# format.js
# format.html { render action: "new" }
# format.json { render json: @forum.errors, status: :unprocessable_entity }
# end
# end
# end
#
# # PUT /forums/1
# # PUT /forums/1.json
# def update
# @forum = Forum.find(params[:id])
# respond_to do |format|
# if @forum.update_attributes(params[:forum])
# format.js
# format.html { redirect_to @forum, notice: l(:label_forum_update_succ) }
# format.json { head :no_content }
# else
# flash.now[:error] = "#{l :label_forum_update_fail}: #{@forum.errors.full_messages[0]}"
# format.js
# format.html { render action: "edit" }
# format.json { render json: @forum.errors, status: :unprocessable_entity }
# end
# end
# end
#
# # DELETE /forums/1
# # DELETE /forums/1.json
# def destroy
# @forum = Forum.find(params[:id])
# @forum.destroy
#
# respond_to do |format|
# format.html { redirect_to forums_url }
# format.json { head :no_content }
# end
# end
#
# # 更新贴吧描述
# def update_memo_description
# @forum = Forum.find(params[:id])
# if @forum.blank?
# result = { :result => false }
# else
# forum_decription = params[:forum][:description]
# @forum.update_attributes(:description => forum_decription )
# result = { :result => true }
# end
# render :json => result
# end
#
# def search_forum
# # @forums = paginateHelper Forum.where("name LIKE '%#{params[:name]}%'")
# q = "%#{params[:name].strip}%"
# (redirect_to forums_url, :notice => l(:label_sumbit_empty);return) if params[:name].blank?
# @offset, @limit = api_offset_and_limit({:limit => 10})
# @forums_all = Forum.where("name LIKE ?", q)
# @forums_count = @forums_all.count
# @forums_pages = Paginator.new @forums_count, @limit, params['page']
#
# @offset ||= @forums_pages.offset
# @forums = @forums_all.offset(@offset).limit(@limit).all
# respond_to do |format|
# format.html {
# render 'index'
# }
# format.json { render json: @forums }
# end
# end
#
# def search_memo
# q = "%#{params[:name].strip}%"
#
# limit = PageLimit
# @memo = Memo.new
# @offset, @limit = api_offset_and_limit({:limit => limit})
# @forum = Forum.find(params[:id])
# @memos_all = @forum.topics.where("subject LIKE ?", q)
# @topic_count = @memos_all.count
# @topic_pages = Paginator.new @topic_count, @limit, params['page']
#
# @offset ||= @topic_pages.offset
# @memos = @memos_all.offset(@offset).limit(@limit).all
# respond_to do |format|
# format.html {
# render 'show', :layout => 'base_forums'
# }
# format.json { render json: @forum }
# end
# end
#
# #检查forum的名字
# def check_forum_name
# begin
# forum_name = params[:forum_name]
# if params[:forum_id]
# result = Forum.where("name = '#{forum_name}' and id != #{params[:forum_id]}").first.blank? ? {:result => true} : {:result => false}
# else
# result = Forum.where(:name => forum_name).first.blank? ? {:result => true} : {:result => false}
# end
# rescue Exception => e
# puts e
# end
# render :json => result
# # if params[:forum_id]
# # forum_name_exist = Forum.where("name = '#{params[:forum_name]}' and id != #{params[:forum_id]}").count >= 1 ? true : false
# # else
# # forum_name_exist = Forum.where("name = '#{params[:forum_name]}' ").count >= 1 ? true : false
# # end
# # render :text => forum_name_exist
# end
#
#
#
#
# #添加论坛tag
# def add_forum_tag
# @forum = Forum.find(params[:id])
# unless @forum.nil?
# @forum.tag_list.add(params[:tag_str].split(','))
# @forum.save
# end
# respond_to do |format|
# format.js {render :delete_forum_tag}
# end
# end
#
# #删除forum的tag
# def delete_forum_tag
# @tag_id = (ActsAsTaggableOn::Tag.find_by_name(params[:tag_name])).id
# #forum的taggable_type = 5
# @taggings = ActsAsTaggableOn::Tagging.find_by_tag_id_and_taggable_id_and_taggable_type(@tag_id,params[:id],'Forum')
#
# unless @taggings.nil?
# @taggings.delete
# end
#
# # 是否还有其他记录 引用了 tag_id
# @tagging = ActsAsTaggableOn::Tagging.find_by_tag_id(@tag_id)
# # 如果taggings表中记录已经不存在 那么检查tags表 作删除动作
# if @tagging.nil?
# @tag = ActsAsTaggableOn::Tag.find_by_id(@tag_id)
# @tag.delete unless @tag.nil?
# end
# @forum = Forum.find(params[:id])
# respond_to do |format|
# format.js
# end
# end
#
# private
#
# def find_forum_if_available
# @forum = Forum.find(params[:id]) if params[:id]
# rescue ActiveRecord::RecordNotFound
# render_404
# nil
# end
#
# def authenticate_user_edit
# find_forum_if_available
# render_403 unless @forum.editable_by? User.current
# end
#
# def authenticate_user_destroy
# find_forum_if_available
# render_403 unless @forum.destroyable_by? User.current
# end
# end

View File

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

View File

@ -7,7 +7,10 @@ class IssueTagsController < ApplicationController
def index
issue_tags = @project.issue_tags.reorder("#{order_name} #{order_type}")
order_name = params[:order_name] || "created_at"
order_type = params[:order_type] || "desc"
issue_tags = @project.issue_tags.order("#{order_name} #{order_type}")
@user_admin_or_member = current_user.present? && (current_user.admin || @project.member?(current_user))
@page = params[:page] || 1
@limit = params[:limit] || 15
@ -135,14 +138,4 @@ class IssueTagsController < ApplicationController
end
end
private
def order_name
IssueTag.column_names.include?(params[:order_name]) ? params[:order_name] : 'created_at'
end
def order_type
%w(desc asc).include?(params[:order_type]) ? params[:order_type] : 'desc'
end
end

View File

@ -1,33 +1,26 @@
class IssuesController < ApplicationController
before_action :require_login, except: [:index, :show, :index_chosen]
before_action :require_profile_completed, only: [:create]
before_action :load_project
before_action :set_user
before_action :check_menu_authorize, except: [:index_chosen]
before_action :check_issue_permission
before_action :operate_issue_permission, only:[:create, :update, :destroy, :clean, :series_update, :copy]
before_action :check_project_public, only: [:index ,:show, :copy, :index_chosen, :close_issue]
before_action :set_issue, only: [:edit, :update, :destroy, :show, :copy, :close_issue, :lock_issue]
before_action :check_token_enough, :find_atme_receivers, only: [:create, :update]
before_action :get_branches, only: [:new, :edit]
include ApplicationHelper
include TagChosenHelper
def index
@user_admin_or_member = current_user.present? && current_user.logged? && (current_user.admin || @project.member?(current_user) || @project.is_public?)
@user_admin_or_member = current_user.present? && current_user.logged? && (current_user.admin || @project.member?(current_user))
issues = @project.issues.issue_issue.issue_index_includes
issues = issues.where(is_private: false) unless @user_admin_or_member
@all_issues = issues
@filter_issues = @all_issues
@filter_issues = @filter_issues.where.not(status_id: IssueStatus::CLOSED) if params[:status_type].to_i == IssueStatus::ADD
@filter_issues = @filter_issues.where(status_id: IssueStatus::CLOSED) if params[:status_type].to_i == IssueStatus::SOLVING
@filter_issues = @filter_issues.where("subject LIKE ? OR description LIKE ? ", "%#{params[:search]}%", "%#{params[:search]}%") if params[:search].present?
@open_issues = @all_issues.where.not(status_id: IssueStatus::CLOSED)
@close_issues = @all_issues.where(status_id: IssueStatus::CLOSED)
@assign_to_me = @filter_issues.where(assigned_to_id: current_user&.id)
@my_published = @filter_issues.where(author_id: current_user&.id)
@all_issues_size = issues.size
@open_issues_size = issues.where.not(status_id: 5).size
@close_issues_size = issues.where(status_id: 5).size
@assign_to_me_size = issues.where(assigned_to_id: current_user&.id).size
@my_published_size = issues.where(author_id: current_user&.id).size
scopes = Issues::ListQueryService.call(issues,params.delete_if{|k,v| v.blank?}, "Issue")
@issues_size = scopes.size
@issues = paginate(scopes)
@ -103,18 +96,80 @@ class IssuesController < ApplicationController
end
def new
@issue_chosen = get_associated_data(@project)
@all_branches = get_branches
@issue_chosen = issue_left_chosen(@project, nil)
end
def create
issue_params = issue_send_params(params)
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 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|
if params[:subject].blank?
normal_status(-1, "标题不能为空")
elsif params[:subject].to_s.size > 255
normal_status(-1, "标题不能超过255个字符")
elsif (params[:issue_type].to_s == "2")
return normal_status(-1, "悬赏的奖金必须大于0") if params[:token].to_i == 0
else
issue_params = issue_send_params(params)
@issue = Issue.new(issue_params)
if @issue.save!
if params[:attachment_ids].present?
params[:attachment_ids].each do |id|
attachment = Attachment.select(:id, :container_id, :container_type)&.find_by_id(id)
unless attachment.blank?
attachment.container = @issue
attachment.author_id = current_user.id
attachment.description = ""
attachment.save
end
end
end
if params[:issue_tag_ids].present?
params[:issue_tag_ids].each do |tag|
IssueTagsRelate.create!(issue_id: @issue.id, issue_tag_id: tag)
end
end
if params[:assigned_to_id].present?
Tiding.create!(user_id: params[:assigned_to_id], trigger_user_id: current_user.id,
container_id: @issue.id, container_type: 'Issue',
parent_container_id: @project.id, parent_container_type: "Project",
tiding_type: 'issue', status: 0)
end
@issue.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: "create")
# normal_status(0, "创建成功",)
render :json => { status: 0, message: "创建成功", id: @issue.id}
else
normal_status(-1, "创建失败")
end
end
end
def edit
# @all_branches = get_branches
# @issue_chosen = issue_left_chosen(@project, @issue.id)
@issue_attachments = @issue.attachments
end
def update
issue_params = issue_send_params(params).except(:issue_classify, :author_id, :project_id)
return normal_status(-1, "您没有权限修改token") if @issue.will_save_change_to_token? && @issue.user_id != current_user&.id
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|
IssueTagsRelate.create(issue_id: @issue.id, issue_tag_id: tag)
end
end
if @issue.update_attributes(issue_params)
issue_files = params[:attachment_ids]
change_files = false
issue_file_ids = []
if issue_files.present?
change_files = true
issue_files.each do |id|
attachment = Attachment.select(:id, :container_id, :container_type)&.find_by_id(id)
unless attachment.blank?
attachment.container = @issue
@ -124,70 +179,6 @@ class IssuesController < ApplicationController
end
end
end
if params[:issue_tag_ids].present?
params[:issue_tag_ids].each do |tag|
IssueTagsRelate.create!(issue_id: @issue.id, issue_tag_id: tag)
end
end
if params[:assigned_to_id].present?
Tiding.create!(user_id: params[:assigned_to_id], trigger_user_id: current_user.id,
container_id: @issue.id, container_type: 'Issue',
parent_container_id: @project.id, parent_container_type: "Project",
tiding_type: 'issue', status: 0)
end
#为悬赏任务时, 扣除当前用户的积分
if params[:issue_type].to_s == "2"
post_to_chain("minus", params[:token].to_i, current_user.try(:login))
end
@issue.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: "create")
Rails.logger.info "[ATME] maybe to at such users: #{@atme_receivers.pluck(:login)}"
AtmeService.call(current_user, @atme_receivers, @issue) if @atme_receivers.size > 0
render json: {status: 0, message: "创建成", id: @issue.id}
else
normal_status(-1, "创建失败")
end
rescue Exception => exception
puts exception.message
normal_status(-1, exception.message)
end
def edit
# @issue_chosen = issue_left_chosen(@project, @issue.id)
@cannot_edit_tags = @issue.issue_type=="2" && @issue.status_id == 5 #悬赏任务已解决且关闭的状态下,不能修改
@issue_attachments = @issue.attachments
end
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|
IssueTagsRelate.create(issue_id: @issue.id, issue_tag_id: tag)
end
end
issue_files = params[:attachment_ids]
change_files = false
issue_file_ids = []
if issue_files.present?
change_files = true
issue_files.each do |id|
attachment = Attachment.select(:id, :container_id, :container_type)&.find_by_id(id)
unless attachment.blank?
attachment.container = @issue
attachment.author_id = current_user.id
attachment.description = ""
attachment.save
end
end
end
# if params[:issue_tag_ids].present?
# issue_current_tags = @issue&.issue_tags&.select(:id)&.pluck(:id)
@ -203,67 +194,21 @@ class IssuesController < ApplicationController
# end
# end
if @issue.issue_type.to_s == "2" && params[:status_id].to_i == 5 && @issue.author_id != current_user.try(:id)
normal_status(-1, "不允许修改为关闭状态")
else
issue_params = issue_send_params(params).except(:issue_classify, :author_id, :project_id)
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)) 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?
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
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) 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?
end
if params[:status_id].to_i == 5 #任务由非关闭状态到关闭状态时
@issue.issue_times.update_all(end_time: Time.now)
@issue.update_closed_issues_count_in_project!
if @issue.issue_type.to_s == "2" && last_status_id != 5
if @issue.assigned_to_id.present? && last_status_id == 3 #只有当用户完成100%时才给token
post_to_chain("add", @issue.token, @issue.get_assign_user.try(:login))
else
post_to_chain("add", @issue.token, @issue.user.try(:login))
end
end
end
if @issue.issue_type.to_s == "2" && @issue.status_id != 5 && @issue.saved_change_to_attribute("token")
#表示修改token值
change_token = last_token - @issue.token
change_type = change_token > 0 ? "add" : "minus"
post_to_chain(change_type, change_token.abs, current_user.try(:login))
end
@issue.create_journal_detail(change_files, issue_files, issue_file_ids, current_user&.id) if @issue.previous_changes.present?
Rails.logger.info "[ATME] maybe to at such users: #{@atme_receivers.pluck(:login)}"
AtmeService.call(current_user, @atme_receivers, @issue) if @atme_receivers.size > 0
normal_status(0, "更新成功")
else
normal_status(-1, "更新失败")
if params[:status_id].to_i == 5
@issue.issue_times.update_all(end_time: Time.now)
# @issue.update_closed_issues_count_in_project! #已经有after_update方法了这里就不需要了
end
@issue.create_journal_detail(change_files, issue_files, issue_file_ids, current_user&.id)
normal_status(0, "更新成功")
else
normal_status(-1, "更新失败")
end
rescue Exception => exception
puts exception.message
normal_status(-1, exception.message)
end
def show
@user_permission = current_user.present? && current_user.logged? && (@project.member?(current_user) || current_user.admin? || @issue.user == current_user)
@user_permission = current_user.present? && current_user.logged? && (!@issue.is_lock || @project.member?(current_user) || current_user.admin? || @issue.user == current_user)
@issue_attachments = @issue.attachments
@issue_user = @issue.user
@issue_assign_to = @issue.get_assign_user
@ -279,37 +224,17 @@ class IssuesController < ApplicationController
end
def destroy
begin
issue_type = @issue.issue_type
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 Site.has_notice_menu?
if @issue.destroy
if issue_type == "2" && status_id != 5
post_to_chain("add", token, login)
end
normal_status(0, "删除成功")
else
normal_status(-1, "删除失败")
end
rescue => exception
Rails.logger.info("#########_______exception.message_________##########{exception.message}")
normal_status(-1, "删除失败")
if @issue.destroy
normal_status(0, "删除成功")
else
normal_status(-1, "删除失败")
end
end
def clean
#批量删除,暂时只能删除未悬赏的
issue_ids = params[:ids]
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) if Site.has_notice_menu?
end
if issues.destroy_all
if issue_ids.present?
if Issue.where(id: issue_ids).destroy_all
normal_status(0, "删除成功")
else
normal_status(-1, "删除失败")
@ -339,28 +264,9 @@ class IssuesController < ApplicationController
# update_hash = params[:issue]
issue_ids = params[:ids]
if issue_ids.present?
issues = Issue.where(id: issue_ids)
if update_hash.blank?
normal_status(-1, "请选择批量更新内容")
elsif issues&.update(update_hash)
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
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) 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?
end
elsif Issue.where(id: issue_ids).update_all(update_hash)
normal_status(0, "批量更新成功")
else
normal_status(-1, "批量更新失败")
@ -372,10 +278,7 @@ class IssuesController < ApplicationController
def copy
@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) 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|
@ -403,9 +306,6 @@ class IssuesController < ApplicationController
if type == 5
@issue&.project_trends&.update_all(action_type: "close")
@issue.issue_times.update_all(end_time: Time.now)
if @issue.issue_type.to_s == "2"
post_to_chain("add", @issue.token, @issue.get_assign_user.try(:login))
end
if @issue.issue_classify.to_s == "pull_request"
@issue&.pull_request&.update_attribute(:status, 2)
end
@ -453,29 +353,25 @@ class IssuesController < ApplicationController
def check_project_public
unless @project.is_public || @project.member?(current_user) || current_user.admin? || (@project.user_id == current_user.id)
return render_forbidden
normal_status(-1, "您没有权限")
end
end
def set_issue
@issue = Issue.find_by_id(params[:id])
if @issue.blank?
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
normal_status(-1, "标签不存在")
elsif @issue.is_lock &&!(@project.member?(current_user) || current_user.admin?)
normal_status(-1, "您没有权限")
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)))
return render_forbidden
normal_status(-1, "您没有权限")
end
end
def operate_issue_permission
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)
@table_columns = %w(ID 类型 标题 描述 状态 指派给 优先级 标签 发布人 创建时间 里程碑 开始时间 截止时间 完成度 分类 金额 属于)
@export_issues = []
@ -503,6 +399,17 @@ class IssuesController < ApplicationController
tracker_array
end
def get_branches
all_branches = []
get_all_branches = Gitea::Repository::Branches::ListService.new(@user, @project&.repository.try(:identifier)).call
if get_all_branches && get_all_branches.size > 0
get_all_branches.each do |b|
all_branches.push(b["name"])
end
end
all_branches
end
def issue_send_params(params)
{
subject: params[:subject],
@ -527,36 +434,4 @@ class IssuesController < ApplicationController
project_id: @project.id
}
end
def post_to_chain(type, amount,login)
change_params = {
type: type,
chain_params: {
amount: amount,
reponame: @project.try(:identifier),
username: login
}
}
PostChainJob.perform_later(change_params)
end
def check_token_enough
if params[:issue_type].to_s == "2" && (@issue.blank? || (@issue.present? && @issue.author_id == current_user.try(:id)))
return normal_status(-1, "悬赏的奖金必须大于0") if params[:token].to_i == 0
query_params = {
type: "query",
chain_params: {
reponame: @project.try(:identifier),
username: current_user.try(:login)
}
}
response = Gitea::Chain::ChainGetService.new(query_params).call
return normal_status(-1, "获取token失败请稍后重试") if response.status != 200
return normal_status(-1, "您的token值不足") if JSON.parse(response.body)["balance"].to_i < params[:token].to_i
end
end
def check_menu_authorize
return render_not_found unless @project.has_menu_permission("issues")
end
end

View File

@ -1,6 +1,5 @@
class JournalsController < ApplicationController
before_action :require_login, except: [:index, :get_children_journals]
before_action :require_profile_completed, :find_atme_receivers, only: [:create]
before_action :set_issue
before_action :check_issue_permission
before_action :set_journal, only: [:destroy, :edit, :update]
@ -22,35 +21,32 @@ class JournalsController < ApplicationController
if notes.blank?
normal_status(-1, "评论内容不能为空")
else
ActiveRecord::Base.transaction do
journal_params = {
journalized_id: @issue.id ,
journalized_type: "Issue",
user_id: current_user.id ,
notes: notes.to_s.strip,
parent_id: params[:parent_id]
}
journal = Journal.new journal_params
if journal.save
if params[:attachment_ids].present?
params[:attachment_ids].each do |id|
attachment = Attachment.select(:id, :container_id, :container_type)&.find_by_id(id)
unless attachment.blank?
attachment.container = journal
attachment.author_id = current_user.id
attachment.description = ""
attachment.save
end
journal_params = {
journalized_id: @issue.id ,
journalized_type: "Issue",
user_id: current_user.id ,
notes: notes.to_s.strip,
parent_id: params[:parent_id]
}
journal = Journal.new journal_params
if journal.save
if params[:attachment_ids].present?
params[:attachment_ids].each do |id|
attachment = Attachment.select(:id, :container_id, :container_type)&.find_by_id(id)
unless attachment.blank?
attachment.container = journal
attachment.author_id = current_user.id
attachment.description = ""
attachment.save
end
end
Rails.logger.info "[ATME] maybe to at such users: #{@atme_receivers.pluck(:login)}"
AtmeService.call(current_user, @atme_receivers, journal) if @atme_receivers.size > 0
# @issue.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: "journal")
render :json => { status: 0, message: "评论成功", id: journal.id}
# normal_status(0, "评论成功")
else
normal_status(-1, "评论失败")
end
# @issue.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: "journal")
render :json => { status: 0, message: "评论成功", id: journal.id}
# normal_status(0, "评论成功")
else
normal_status(-1, "评论失败")
end
end
end

View File

@ -2,7 +2,7 @@ class MainController < ApplicationController
protect_from_forgery except: :index
skip_before_action :check_sign
skip_before_action :user_setup
skip_before_action :setup_laboratory
# skip_before_action :setup_laboratory
def first_stamp
render :json => { status: 0, message: Time.now.to_i }
@ -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, :content_type=> 'text/html'
render file: 'public/h5educoderbuild/index.html', :layout => false
else
render file: 'public/react/build/index.html', :layout => false, :content_type=> 'text/html'
render file: 'public/react/build/index.html', :layout => false
end
end

View File

@ -2,15 +2,12 @@ class MembersController < ApplicationController
before_action :require_login
before_action :load_project
before_action :find_user_with_id, only: %i[create remove change_role]
before_action :check_user_profile_completed, only: [:create]
before_action :operate!, except: %i[index]
before_action :check_member_exists!, only: %i[create]
before_action :check_member_not_exists!, only: %i[remove change_role]
def create
interactor = Projects::AddMemberInteractor.call(@project.owner, @project, @user)
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)
@ -21,7 +18,7 @@ class MembersController < ApplicationController
scope = @project.members.includes(:roles, user: :user_extension)
search = params[:search].to_s.downcase
role = params[:role].to_s
scope = scope.joins(:user).merge(User.like(search))
scope = scope.joins(:user).where("LOWER(concat(users.lastname, users.firstname, users.login, users.mail)) LIKE ?", "%#{search.split(" ").join('|')}%") if search.present?
scope = scope.joins(:roles).where("roles.name LIKE ?", "%#{role}%") if role.present?
@total_count = scope.size
@ -30,8 +27,6 @@ class MembersController < ApplicationController
def remove
interactor = Projects::DeleteMemberInteractor.call(@project.owner, @project, @user)
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 +35,6 @@ 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) if Site.has_notice_menu?
render_response(interactor)
rescue Exception => e
uid_logger_error(e.message)
@ -53,7 +47,7 @@ class MembersController < ApplicationController
end
def member_exists?
@project.members.exists?(user_id: params[:user_id])
@project.member?(params[:user_id])
end
def operate!
@ -61,24 +55,10 @@ class MembersController < ApplicationController
end
def check_member_exists!
return render_error("user_id为#{params[:user_id]}的用户已经是项目成员") if member_exists?
return render_result(1, "user_id为#{params[:user_id]}的用户已经是项目成员") if member_exists?
end
def check_member_not_exists!
return render_error("user_id为#{params[:user_id]}的用户还不是项目成员") unless member_exists?
end
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
return render_result(1, "user_id为#{params[:user_id]}的用户还不是项目成员") unless member_exists?
end
end

View File

@ -0,0 +1,109 @@
class MemosController < ApplicationController
before_action :require_login, only: [:create, :edit, :update, :watch_memo]
def index
memos = MemosService.new.index params, current_user
render json: memos
end
def related_memos
targets = MemosService.new.related_memos params, current_user
render json: targets
end
def edit
targets = MemosService.new.edit params, current_user
render json: targets
end
def update
targets = MemosService.new.update params, current_user
render json: targets
end
def create
params.permit!
targets = MemosService.new.create params, current_user
render json: targets
end
def show
targets = MemosService.new.show params, current_user
render json: targets
end
def watch_memo
targets = MemosService.new.watch_memo params, current_user
render json: targets
end
def hidden
Memo.find(params[:id]).update_attribute(:hidden, true)
{status: 0, message: "隐藏成功"}
end
def memo_hidden
targets = MemosService.new.memo_hidden params, current_user
render json: targets
end
def reply
targets = MemosService.new.reply params, current_user
render json: targets
end
def destroy
targets = MemosService.new.destroy params, current_user
render json: targets
end
def set_top_or_down
targets = MemosService.new.set_top_or_down params, current_user
render json: targets
end
def is_fine
targets = MemosService.new.is_fine params, current_user
render json: targets
end
def banned_user
targets = MemosService.new.banned_user params, current_user
render json: targets
end
def more_reply
targets = MemosService.new.more_reply params, current_user
render json: targets
end
def forum_memos
targets = MemosService.new.forum_memos params, current_user
render json: targets
end
def forum_memos_head
targets = MemosService.new.forum_memos_head params, current_user
render json: targets
end
def forum_memos_right
targets = MemosService.new.forum_memos_right params, current_user
render json: targets
end
def is_watch
targets = MemosService.new.is_watch params, current_user
render json: targets
end
def confirm_delete
targets = MemosService.new.confirm_delete params, current_user
render json: targets
end
def plus
targets = MemosService.new.plus params, current_user
render json: targets
end
end

View File

@ -0,0 +1,22 @@
class MyMemosController < ApplicationController
def index
targets = MyMemosService.new.index params, current_user
render json: targets
end
def my_interested
targets = MyMemosService.new.my_interested params, current_user
render json: targets
end
def replies_memos
targets = MyMemosService.new.replies_memos params,current_user
render json: targets
end
def recommend_memos
targets = MyMemosService.new.recommend_memos current_user
render json: targets
end
end

View File

@ -2,7 +2,6 @@ class Oauth::BaseController < ActionController::Base
include RenderHelper
include LoginHelper
include ControllerRescueHandler
include LoggerHelper
# include LaboratoryHelper
skip_before_action :verify_authenticity_token
@ -12,18 +11,6 @@ class Oauth::BaseController < ActionController::Base
end
private
def tip_exception(status = -1, message)
raise Educoder::TipException.new(status, message)
end
def tip_show_exception(status = -2, message)
raise Educoder::TipException.new(status, message)
end
def tip_show(exception)
uid_logger("Tip show status is #{exception.status}, message is #{exception.message}")
render json: exception.tip_json
end
def session_user_id
# session[:user_id]
@ -61,13 +48,4 @@ class Oauth::BaseController < ActionController::Base
Rails.logger.info("[wechat] set session unionid: #{unionid}")
session[:unionid] = unionid
end
def session_edulogin
session[:edulogin]
end
def set_session_edulogin(login)
Rails.logger.info("[educoder] set sesstion edulogin: #{login}")
session[:edulogin] = login
end
end

View File

@ -1,6 +1,4 @@
class Oauth::EducoderController < Oauth::BaseController
include RegisterHelper
def bind
begin
login = params[:login]
@ -34,41 +32,4 @@ class Oauth::EducoderController < Oauth::BaseController
render_error(ex.message)
end
end
# 需要educoder那边设置回调地址
def create
begin
code = params['code'].to_s.strip
tip_exception("code不能为空") if code.blank?
new_user = false
result = EducoderOauth::Service.access_token(code)
result = EducoderOauth::Service.user_info(result[:access_token])
# 存在该用户
open_user = OpenUsers::Educoder.find_by(uid: result['login'])
if open_user.present? && open_user.user.present?
successful_authentication(open_user.user)
else
if current_user.blank? || !current_user.logged?
new_user = true
login = User.generate_login('E')
reg_result = autologin_register(login,"#{login}@forge.com", "Ec#{login}2021#", 'educoder', true)
if reg_result[:message].blank?
open_user = OpenUsers::Educoder.create!(user_id: reg_result[:user][:id], uid: result['login'], extra: result)
autosync_register_trustie(login, "Ec#{login}2021#", "#{login}@forge.com")
successful_authentication(open_user.user)
else
render_error(reg_result[:message])
end
else
OpenUsers::Educoder.create!(user: current_user, uid: result['login'], extra: result)
end
end
redirect_to root_path(new_user: new_user)
rescue Exception => ex
render_error(ex.message)
end
end
end

View File

@ -61,7 +61,6 @@ class OauthController < ApplicationController
login = params[:login]
email = params[:mail]
password = params[:password]
lastname = params[:lastname]
callback_url = params[:callback_url]
platform = params[:plathform] || 'educoder'
@ -73,11 +72,8 @@ class OauthController < ApplicationController
if result[:message].blank?
logger.info "[Oauth educoer] ====auto_register success"
user = User.find result[:user][:id]
user.update_column(:lastname, params[:lastname])
autosync_register_trustie(login, password, email, lastname)
OpenUsers::Educoder.create!(user: user, uid: user.login)
successful_authentication(user)
OpenUsers::Educoder.create!(user: user, uid: user.login)
render json: { callback_url: callback_url }
# redirect_to callback_url

View File

@ -22,12 +22,11 @@ class Organizations::OrganizationsController < Organizations::BaseController
@can_create_project = @organization.can_create_project?(current_user.id)
@is_admin = can_edit_org?
@is_member = @organization.is_member?(current_user.id)
Cache::V2::OwnerCommonService.new(@organization.id).read
end
def create
ActiveRecord::Base.transaction do
tip_exception("无法使用以下关键词:#{organization_params[:name]},请重新命名") if ReversedKeyword.check_exists?(organization_params[:name])
tip_exception("无法使用以下关键词:#{organization_params[:name]},请重新命名") if ReversedKeyword.is_reversed(organization_params[:name]).present?
Organizations::CreateForm.new(organization_params).validate!
@organization = Organizations::CreateService.call(current_user, organization_params)
Util.write_file(@image, avatar_path(@organization)) if params[:image].present?
@ -69,7 +68,8 @@ class Organizations::OrganizationsController < Organizations::BaseController
def recommend
recommend = %W(xuos Huawei_Technology openatom_foundation pkecosystem TensorLayer)
@organizations = Organization.includes(:organization_extension).where(organization_extensions: {recommend: true}).to_a.each_slice(group_size).to_a
@organizations = Organization.with_visibility(%w(common))
.where(login: recommend).select(:id, :login, :firstname, :lastname, :nickname)
end
private
@ -80,10 +80,6 @@ class Organizations::OrganizationsController < Organizations::BaseController
:max_repo_creation, :nickname)
end
def group_size
params.fetch(:group_size, 4).to_i
end
def password
params.fetch(:password, "")
end

View File

@ -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) if Site.has_notice_menu?
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

View File

@ -0,0 +1,30 @@
class PlatesController < ApplicationController
def index
render_react
end
def show
render_react
end
def all
render_react
end
def is_fine
render_react
end
def my_memos
render_react
end
def my_topics
render_react
end
private
def render_react
render "/common/index", :layout => false
end
end

View File

@ -1,6 +1,5 @@
class PraiseTreadController < ApplicationController
before_action :require_login, except: %i[index]
before_action :require_profile_completed, only: [:like]
before_action :find_project_with_id
def index
@ -41,5 +40,8 @@ class PraiseTreadController < ApplicationController
end
private
def render_result
end
end

View File

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

View File

@ -3,7 +3,7 @@ class ProjectTrendsController < ApplicationController
before_action :check_project_public
def index
project_trends = @project.project_trends.preload(:user, trend: :user)
project_trends = @project.project_trends.includes(:user, trend: :user)
check_time = params[:time] #时间的筛选
check_type = params[:type] #动态类型的筛选,目前已知的有 Issue, PullRequest, Version
@ -14,25 +14,20 @@ 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_trends.where(trend_type: "Issue", action_type: "create").size
@project_open_issues_count = @project_issues_count - @project_close_issues_count
@project_issues_count = @project_open_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_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?
project_trends = project_trends.where(trend_type: check_type.to_s.strip)
end
if check_status.present?
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")
project_trends = project_trends.where(action_type: check_status.to_s.strip)
end
project_trends = project_trends.order("created_at desc")

View File

@ -4,7 +4,4 @@ class Projects::BaseController < ApplicationController
before_action :load_project
before_action :load_repository
def require_manager!
return render_forbidden('你没有权限操作') unless current_user.admin? || @project.manager?(current_user)
end
end

View File

@ -1,5 +1,4 @@
class Projects::ProjectAppliesController < Projects::BaseController
before_action :require_profile_completed, only: [:create]
def create
project = Projects::ApplyJoinService.call(current_user, create_params)
render_ok(project_id: project.id)

View File

@ -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) if Site.has_notice_menu?
SendTemplateMessageJob.perform_later('ProjectSettingChanged', current_user.id, @project&.id, {navbar: true}) unless before_units.eql?(after_units)
render_ok
end
else

View File

@ -2,46 +2,16 @@ class ProjectsController < ApplicationController
include ApplicationHelper
include OperateProjectAbilityAble
include ProjectsHelper
include Acceleratorable
before_action :require_login, except: %i[index branches branches_slice group_type_list simple show fork_users praise_users watch_users recommend banner_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 banner_recommend]
before_action :require_login, except: %i[index branches group_type_list simple show fork_users praise_users watch_users recommend about]
before_action :load_project, except: %i[index group_type_list migrate create recommend]
before_action :authorizate_user_can_edit_project!, only: %i[update]
before_action :project_public?, only: %i[fork_users praise_users watch_users]
def menu_list
menu = []
menu.append(menu_hash_by_name("home"))
menu.append(menu_hash_by_name("code")) if @project.has_menu_permission("code")
menu.append(menu_hash_by_name("issues")) if @project.has_menu_permission("issues")
menu.append(menu_hash_by_name("pulls")) if @project.has_menu_permission("pulls")
menu.append(menu_hash_by_name("wiki")) if @project.has_menu_permission("wiki")
menu.append(menu_hash_by_name("devops")) if @project.has_menu_permission("devops")
menu.append(menu_hash_by_name("versions")) if @project.has_menu_permission("versions")
menu.append(menu_hash_by_name("resources")) if @project.has_menu_permission("resources")
menu.append(menu_hash_by_name("activity"))
menu.append(menu_hash_by_name("settings")) if current_user.admin? || @project.manager?(current_user)
render json: menu
end
def index
scope = current_user.logged? ? Projects::ListQuery.call(params, current_user.id) : Projects::ListQuery.call(params)
scope = Projects::ListQuery.call(params)
@projects = kaminari_paginate(scope.includes(:project_category, :project_language, :repository, :project_educoder, :owner, :project_units))
# @projects = paginate scope.includes(:project_category, :project_language, :repository, :project_educoder, :owner, :project_units)
category_id = params[:category_id]
@total_count =
if category_id.blank?
ps = ProjectStatistic.first
ps.common_projects_count + ps.mirror_projects_count unless ps.blank?
else
cate = ProjectCategory.find_by(id: category_id)
cate&.projects_count || 0
end
@projects = kaminari_paginate(scope)
@total_count = @projects.total_count
end
def create
@ -57,95 +27,36 @@ class ProjectsController < ApplicationController
def migrate
Projects::MigrateForm.new(mirror_params).validate!
@project =
if enable_accelerator?(mirror_params[:clone_addr])
source_clone_url = mirror_params[:clone_addr]
uid_logger("########## 已动加速器 ##########")
result = Gitea::Accelerator::MigrateService.call(mirror_params)
if result[:status] == :success
Rails.logger.info "########## 加速镜像成功 ########## "
Projects::MigrateService.call(current_user,
mirror_params.merge(source_clone_url: source_clone_url,
clone_addr: accelerator_url(mirror_params[:repository_name])))
else
Projects::MigrateService.call(current_user, mirror_params)
end
else
Projects::MigrateService.call(current_user, mirror_params)
end
@project = Projects::MigrateService.new(current_user, mirror_params).call
rescue Exception => e
uid_logger_error(e.message)
tip_exception(e.message)
end
def branches
return @branches = [] unless @project.forge?
result = Gitea::Repository::Branches::ListService.call(@owner, @project.identifier)
@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
@branches = Gitea::Repository::Branches::ListService.new(@project.owner, @project.identifier).call
end
def group_type_list
project_statics = ProjectStatistic.first
@project_statics_list = [
{
project_type: 'common',
name: '开源托管项目',
projects_count: project_statics&.common_projects_count || 0
},
{
project_type: 'mirror',
name: '开源镜像项目',
projects_count: project_statics&.mirror_projects_count || 0
}
]
# projects = Project.no_anomory_projects.visible
# @project_group_list = projects.group(:project_type).size
# if current_user&.logged?
# projects = Project.list_user_projects(current_user.id)
# else
# projects = Project.visible
# end
projects = Project.no_anomory_projects.visible
@project_group_list = projects.group(:project_type).size
end
def update
ActiveRecord::Base.transaction do
# TODO:
# 临时特殊处理修改website、lesson_url操作方法
if project_params.has_key?("website")
@project.update(project_params)
elsif project_params.has_key?("default_branch")
@project.update(project_params)
gitea_params = {
default_branch: @project.default_branch
}
Gitea::Repository::UpdateService.call(@owner, @project.identifier, gitea_params)
else
validate_params = project_params.slice(:name, :description,
:project_category_id, :project_language_id, :private, :identifier)
Projects::UpdateForm.new(validate_params.merge(user_id: @project.user_id, project_identifier: @project.identifier)).validate!
private = @project.forked_from_project.present? ? !@project.forked_from_project.is_public : params[:private] || false
new_project_params = project_params.except(:private).merge(is_public: !private)
@project.update_attributes!(new_project_params)
@project.forked_projects.update_all(is_public: @project.is_public)
gitea_params = {
private: private,
default_branch: @project.default_branch,
website: @project.website,
name: @project.identifier
}
gitea_repo = Gitea::Repository::UpdateService.call(@owner, @project&.repository&.identifier, gitea_params)
@project.repository.update_attributes({hidden: gitea_repo["private"], identifier: gitea_repo["name"]})
# Projects::CreateForm.new(project_params).validate!
private = params[:private]
if [true, false].include? private
new_project_params = project_params.merge(is_public: !private)
Gitea::Repository::UpdateService.new(@project.owner, @project.repository.identifier, {private: private}).call
@project.repository.update_column(:hidden, private)
end
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?
@project.update_attributes!(new_project_params)
end
rescue Exception => e
uid_logger_error(e.message)
@ -156,11 +67,10 @@ class ProjectsController < ApplicationController
end
def destroy
if current_user.admin? || @project.manager?(current_user)
if current_user.admin? || @project.owner?(current_user)
ActiveRecord::Base.transaction do
Gitea::Repository::DeleteService.new(@project.owner, @project.identifier).call
@project.destroy!
@project.forked_projects.update_all(forked_from_project_id: nil)
render_ok
end
else
@ -190,17 +100,11 @@ class ProjectsController < ApplicationController
end
def simple
# 为了缓存活跃项目的基本信息,后续删除
Cache::V2::ProjectCommonService.new(@project.id).read
json_response(@project, current_user)
json_response(@project)
end
def recommend
@projects = Project.recommend.includes(:repository, :project_category, :owner).order(visits: :desc)
end
def banner_recommend
@projects = Project.recommend.where.not(recommend_index: 0).includes(:project_category, :owner, :project_language).order(recommend_index: :desc)
@projects = Project.recommend.includes(:repository, :project_category, owner: :user_extension).limit(5)
end
def about
@ -234,8 +138,8 @@ class ProjectsController < ApplicationController
private
def project_params
params.permit(:user_id, :name, :description, :repository_name, :website, :lesson_url, :default_branch, :identifier,
:project_category_id, :project_language_id, :license_id, :ignore_id, :private)
params.permit(:user_id, :name, :description, :repository_name,
:project_category_id, :project_language_id, :license_id, :ignore_id)
end
def mirror_params

View File

@ -1,11 +1,9 @@
class PullRequestsController < ApplicationController
before_action :require_login, except: [:index, :show, :files, :commits]
before_action :require_profile_completed, only: [:create]
before_action :require_login, except: [:index, :show]
before_action :load_repository
before_action :check_menu_authorize
before_action :find_pull_request, except: [:index, :new, :create, :check_can_merge,:get_branches,:create_merge_infos, :files, :commits]
before_action :load_pull_request, only: [:files, :commits]
before_action :find_atme_receivers, only: [:create, :update]
before_action :set_user, only: [:new, :get_branches]
before_action :find_pull_request, except: [:index, :new, :create, :check_can_merge,:get_branches,:create_merge_infos]
# before_action :get_relatived, only: [:edit]
include TagChosenHelper
include ApplicationHelper
@ -14,14 +12,11 @@ class PullRequestsController < ApplicationController
# @issues = Gitea::PullRequest::ListService.new(@user,@repository.try(:identifier)).call #通过gitea获取
issues = @project.issues.issue_pull_request.issue_index_includes.includes(pull_request: :user)
issues = issues.where(is_private: false) unless current_user.present? && (current_user.admin? || @project.member?(current_user))
@all_issues = issues.distinct
@filter_issues = @all_issues
@filter_issues = @filter_issues.where("subject LIKE ? OR description LIKE ? ", "%#{params[:search]}%", "%#{params[:search]}%") if params[:search].present?
@open_issues = @filter_issues.joins(:pull_request).where(pull_requests: {status: PullRequest::OPEN})
@close_issues = @filter_issues.joins(:pull_request).where(pull_requests: {status: PullRequest::CLOSED})
@merged_issues = @filter_issues.joins(:pull_request).where(pull_requests: {status: PullRequest::MERGED})
@all_issues_size = issues.size
@open_issues_size = issues.joins(:pull_request).where(pull_requests: {status: 0}).size
@close_issues_size = issues.joins(:pull_request).where(pull_requests: {status: 2}).size
@merged_issues_size = issues.joins(:pull_request).where(pull_requests: {status: 1}).size
@user_admin_or_member = current_user.present? && (current_user.admin || @project.member?(current_user))
@user_admin_or_developer = current_user.present? && (current_user.admin || @project.all_developers.include?(current_user))
scopes = Issues::ListQueryService.call(issues,params.delete_if{|k,v| v.blank?}, "PullRequest")
@issues_size = scopes.size
@ -29,11 +24,11 @@ class PullRequestsController < ApplicationController
end
def new
@all_branches = Branches::ListService.call(@owner, @project)
@all_branches = PullRequests::BranchesService.new(@user, @project).call
@is_fork = @project.forked_from_project_id.present?
@projects_names = [{
project_user_login: @owner.try(:login),
project_name: "#{@owner.try(:show_real_name)}/#{@repository.try(:identifier)}",
project_user_login: @user.try(:login),
project_name: "#{@user.try(:show_real_name)}/#{@repository.try(:identifier)}",
project_id: @project.identifier,
id: @project.id
}]
@ -50,44 +45,84 @@ class PullRequestsController < ApplicationController
end
def get_branches
branch_result = Branches::ListService.call(@owner, @project)
branch_result = PullRequests::BranchesService.new(@user, @project).call
render json: branch_result
# return json: branch_result
end
def create
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"], @gitea_pull_request[:body]["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?
Rails.logger.info "[ATME] maybe to at such users: #{@atme_receivers.pluck(:login)}"
AtmeService.call(current_user, @atme_receivers, @pull_request) if @atme_receivers.size > 0
else
render_error("create pull request error: #{@gitea_pull_request[:status]}")
raise ActiveRecord::Rollback
if params[:title].nil?
normal_status(-1, "名称不能为空")
elsif params[:issue_tag_ids].nil?
normal_status(-1, "标签不能为空")
else
ActiveRecord::Base.transaction do
begin
merge_params
pull_issue = Issue.new(@issue_params)
if pull_issue.save!
pr_params = {
user_id: current_user.try(:id),
project_id: @project.id,
issue_id: pull_issue.id,
fork_project_id: params[:fork_project_id],
is_original: params[:is_original]
}
local_requests = PullRequest.new(@local_params.merge(pr_params))
if local_requests.save
remote_pr_params = @local_params
remote_pr_params = remote_pr_params.merge(head: "#{params[:merge_user_login]}:#{params[:head]}").compact if local_requests.is_original && params[:merge_user_login]
gitea_request = Gitea::PullRequest::CreateService.call(current_user.try(:gitea_token), @project.owner, @repository.try(:identifier), remote_pr_params.except(:milestone))
if gitea_request && local_requests.update_attributes(gpid: gitea_request["number"])
if params[:issue_tag_ids].present?
params[:issue_tag_ids].each do |tag|
IssueTagsRelate.create!(issue_id: pull_issue.id, issue_tag_id: tag)
end
end
if params[:assigned_to_id].present?
Tiding.create!(user_id: params[:assigned_to_id], trigger_user_id: current_user.id,
container_id: local_requests.id, container_type: 'PullRequest',
parent_container_id: @project.id, parent_container_type: "Project",
tiding_type: 'pull_request', status: 0)
end
local_requests.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: "create")
if params[:title].to_s.include?("WIP:")
pull_issue.custom_journal_detail("WIP", "", "这个合并请求被标记为尚未完成的工作。完成后请从标题中移除WIP:前缀。", current_user&.id)
end
# render :json => { status: 0, message: "PullRequest创建成功", id: pull_issue.id}
normal_status(0, "PullRequest创建成功")
else
normal_status(-1, "PullRequest创建失败")
end
else
normal_status(-1, "PullRequest创建失败")
end
end
rescue => e
normal_status(-1, e.message)
raise ActiveRecord::Rollback
end
end
end
end
def edit
@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)
@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)
end
def update
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|
@ -97,10 +132,8 @@ class PullRequestsController < ApplicationController
if @issue.update_attributes(@issue_params)
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)
if gitea_pull[:status] === :success
gitea_request = Gitea::PullRequest::UpdateService.new(@project.owner, @repository.try(:identifier), @requests_params, @pull_request.try(:gpid)).call
if gitea_request
if params[:issue_tag_ids].present?
params[:issue_tag_ids].each do |tag|
IssueTagsRelate.create(issue_id: @issue.id, issue_tag_id: tag)
@ -109,8 +142,6 @@ class PullRequestsController < ApplicationController
if params[:status_id].to_i == 5
@issue.issue_times.update_all(end_time: Time.now)
end
Rails.logger.info "[ATME] maybe to at such users: #{@atme_receivers.pluck(:login)}"
AtmeService.call(current_user, @atme_receivers, @pull_request) if @atme_receivers.size > 0
normal_status(0, "PullRequest更新成功")
else
normal_status(-1, "PullRequest更新失败")
@ -123,8 +154,6 @@ 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)) 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
@ -133,14 +162,9 @@ class PullRequestsController < ApplicationController
def refuse_merge
ActiveRecord::Base.transaction do
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) if Site.has_notice_menu?
normal_status(1, "已拒绝")
else
normal_status(-1, '合并失败')
end
@pull_request.update(status: 2)
@pull_request.issue.update(status_id: 5)
normal_status(1, "已拒绝")
rescue => e
normal_status(-1, e.message)
raise ActiveRecord::Rollback
@ -155,35 +179,30 @@ class PullRequestsController < ApplicationController
def show
@issue_user = @issue.user
@issue_assign_to = @issue.get_assign_user
@gitea_pull = Gitea::PullRequest::GetService.call(@owner.login,
@repository.identifier, @pull_request.gitea_number, current_user&.gitea_token)
end
def pr_merge
return render_forbidden("你没有权限操作.") unless @project.operator?(current_user)
return render_forbidden("你没有权限操作.") if @project.reporter?(current_user)
if params[:do].blank?
normal_status(-1, "请选择合并方式")
else
ActiveRecord::Base.transaction do
begin
@gitea_pull = Gitea::PullRequest::GetService.call(@owner.login, @repository.identifier, @pull_request.gitea_number, current_user&.gitea_token)
if @gitea_pull["merged_by"].present?
success_condition = true
else
result = PullRequests::MergeService.call(@owner, @repository, @pull_request, current_user, params)
success_condition = result.status == 200
end
if success_condition && @pull_request.merge!
# @pull_request.project_trend_status!
@pull_request.project_trends.create!(user: current_user, project: @project,action_type: ProjectTrend::MERGE)
requests_params = {
Do: params[:do],
MergeMessageField: params[:body],
MergeTitleField: params[:title]
}
merge_pr = Gitea::PullRequest::MergeService.call(current_user.gitea_token, @project.owner.login,
@repository.try(:identifier), @pull_request.try(:gpid), requests_params)
if @pull_request.update_attribute(:status, 1) && merge_pr[:status].to_i == 200
@pull_request&.project_trends&.update_all(action_type: "close")
@issue&.custom_journal_detail("merge", "", "该合并请求已被合并", current_user&.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)
normal_status(-1, "合并失败")
end
rescue => e
normal_status(-1, e.message)
@ -203,11 +222,11 @@ class PullRequestsController < ApplicationController
elsif target_head === target_base && !is_original
normal_status(-2, "分支内容相同,无需创建合并请求")
else
can_merge = @project&.pull_requests.where(head: target_head, base: target_base, status: 0, is_original: is_original, fork_project_id: params[:fork_project_id])
can_merge = @project&.pull_requests.where(user_id: current_user&.id, head: target_head, base: target_base, status: 0, is_original: is_original, fork_project_id: params[:fork_project_id])
if can_merge.present?
render json: {
status: -2,
message: "在这些分支之间的合并请求已存在:<a href='/#{@owner.login}/#{@project.identifier}/pulls/#{can_merge.first.id}''>#{can_merge.first.try(:title)}</a>",
message: "在这些分支之间的合并请求已存在:<a href='/projects/#{@project.id}/merge/#{can_merge.first.id}/Messagecount''>#{can_merge.first.try(:title)}</a>",
}
else
normal_status(0, "可以合并")
@ -216,19 +235,9 @@ class PullRequestsController < ApplicationController
end
def files
@files_result = Gitea::PullRequest::FilesService.call(@owner.login, @project.identifier, @pull_request.gitea_number, current_user&.gitea_token)
# render json: @files_result
end
def commits
@commits_result = Gitea::PullRequest::CommitsService.call(@owner.login, @project.identifier, @pull_request.gitea_number, current_user&.gitea_token)
# render json: @commits_result
end
private
def load_pull_request
@pull_request = PullRequest.find params[:id]
def set_user
@user = @project.owner
end
def find_pull_request
@ -244,7 +253,7 @@ class PullRequestsController < ApplicationController
def get_relatived
@project_tags = @project.issue_tags&.select(:id,:name, :color).as_json
@project_versions = @project.versions&.select(:id,:name, :status).as_json
@project_members = @project.all_developers
@project_members = @project.members_user_infos
@project_priories = IssuePriority&.select(:id,:name, :position).as_json
end
@ -258,8 +267,7 @@ class PullRequestsController < ApplicationController
}
@requests_params = @local_params.merge({
assignee: current_user.try(:login),
# assignees: ["#{params[:assigned_login].to_s}"],
assignees: ["#{current_user.try(:login).to_s}"],
assignees: ["#{params[:assigned_login].to_s}"],
labels: params[:issue_tag_ids],
due_date: Time.now
})
@ -278,8 +286,4 @@ class PullRequestsController < ApplicationController
status_id: 1,
}
end
def check_menu_authorize
return render_not_found unless @project.has_menu_permission("pulls")
end
end

View File

@ -1,41 +1,19 @@
class RepositoriesController < ApplicationController
include RepositoriesHelper
include ApplicationHelper
include OperateProjectAbilityAble
include Repository::LanguagesPercentagable
before_action :require_login, only: %i[edit update create_file update_file delete_file sync_mirror]
before_action :require_profile_completed, only: [:create_file]
before_action :load_repository
before_action :authorizate!, except: [:sync_mirror, :tags, :commit, :archive]
before_action :authorizate!, except: [:sync_mirror, :tags, :commit]
before_action :authorizate_user_can_edit_repo!, only: %i[sync_mirror]
before_action :get_ref, only: %i[entries sub_entries top_counts file archive]
before_action :get_ref, only: %i[entries sub_entries top_counts]
before_action :get_latest_commit, only: %i[entries sub_entries top_counts]
before_action :get_statistics, only: %i[top_counts]
def files
result = @project.educoder? ? nil : Gitea::Repository::Files::GetService.call(@owner, @project.identifier, @ref, params[:search], @owner.gitea_token)
render json: result
end
# 新版项目详情
def detail
@user = current_user
@result = Repositories::DetailService.call(@owner, @repository, @user)
@project_fork_id = @project.try(:forked_from_project_id)
if @project_fork_id.present?
@fork_project = Project.find_by(id: @project_fork_id)
@fork_project_user = @fork_project.owner
end
rescue Exception => e
uid_logger_error(e.message)
tip_exception(e.message)
end
def show
@user = current_user
@repo = @project.repository
@result = @project.forge? ? Gitea::Repository::GetService.new(@owner, @project.identifier).call : nil
@result = Gitea::Repository::GetService.new(@project.owner, @project.identifier).call
@project_fork_id = @project.try(:forked_from_project_id)
if @project_fork_id.present?
@fork_project = Project.find_by(id: @project_fork_id)
@ -48,119 +26,62 @@ class RepositoriesController < ApplicationController
def entries
@project.increment!(:visits)
CacheAsyncSetJob.perform_later("project_common_service", {visits: 1}, @project.id)
if @project.educoder?
@entries = Educoder::Repository::Entries::ListService.call(@project&.project_educoder.repo_name)
else
@entries = Gitea::Repository::Entries::ListService.new(@owner, @project.identifier, ref: @ref).call
@entries = @entries.present? ? @entries.sort_by{ |hash| hash['type'] } : []
@path = Gitea.gitea_config[:domain]+"/#{@project.owner.login}/#{@project.identifier}/raw/branch/#{@ref}/"
end
@project_owner = @project.owner
@entries = Gitea::Repository::Entries::ListService.new(@project_owner, @project.identifier, ref: @ref).call
@entries = @entries.present? ? @entries.sort_by{ |hash| hash['type'] } : []
@path = Gitea.gitea_config[:domain]+"/#{@project.owner.login}/#{@project.identifier}/raw/branch/#{@ref}/"
end
def top_counts
@result = @project.educoder? ? nil : Gitea::Repository::GetService.new(@project.owner, @project.identifier).call
@result = Gitea::Repository::GetService.new(@project.owner, @project.identifier).call
end
def sub_entries
file_path_uri = URI.parse(URI.encode(params[:filepath].to_s.strip))
@path = Gitea.gitea_config[:domain]+"/#{@project.owner.login}/#{@project.identifier}/raw/branch/#{@ref}/"
if @project.educoder?
if params[:type] === 'file'
@sub_entries = Educoder::Repository::Entries::GetService.call(@project&.project_educoder&.repo_name, file_path_uri)
logger.info "######### sub_entries: #{@sub_entries}"
return render_error('该文件暂未开放,敬请期待.') if @sub_entries['status'].to_i === -1
tmp_entries = [{
"content" => @sub_entries['data']['content'],
"type" => "blob"
}]
@sub_entries = {
"trees"=>tmp_entries,
"commits" => [{}]
}
else
@sub_entries = Educoder::Repository::Entries::ListService.call(@project&.project_educoder&.repo_name, {path: file_path_uri})
end
else
interactor = Repositories::EntriesInteractor.call(@owner, @project.identifier, file_path_uri, ref: @ref)
if interactor.success?
result = interactor.result
@sub_entries = result.is_a?(Array) ? result.sort_by{ |hash| hash['type'] } : result
else
render_error(interactor.error)
end
end
end
def commits
if 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
@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)
@commit_diff = Gitea::Repository::Commits::GetService.call(@owner.login, @repository.identifier, @sha, current_user&.gitea_token, {diff: true})
end
def tags
result = Gitea::Repository::Tags::ListService.call(current_user&.gitea_token, @owner.login, @project.identifier, {page: params[:page], limit: params[:limit]})
@tags = result.is_a?(Hash) && result.key?(:status) ? [] : result
end
def contributors
if params[:filepath].present?
@contributors = []
else
@contributors = Gitea::Repository::Contributors::GetService.call(@owner, @repository.identifier)
end
end
def edit
return render_forbidden if !@project.manager?(current_user) && !current_user.admin?
end
def create_file
interactor = Gitea::CreateFileInteractor.call(current_user.gitea_token, @owner.login, content_params)
interactor = Repositories::EntriesInteractor.call(@project.owner, @project.identifier, file_path_uri, ref: @ref)
if interactor.success?
@file = interactor.result
# create_new_pr(params)
#如果是更新流水线文件
if params[:pipeline_id]
update_pipeline(params[:pipeline_id])
end
result = interactor.result
return @sub_entries = [] if result.is_a?(Hash) && result[:status] == -1
@sub_entries = result.is_a?(Array) ? result : [result]
@sub_entries = @sub_entries.sort_by{ |hash| hash['type'] }
else
render_error(interactor.error)
end
end
def update_pipeline(pipeline_id)
pipeline = Ci::Pipeline.find(pipeline_id)
if pipeline
pipeline.update!(sync: 1)
def commits
@project_owner = @project.owner
@hash_commit = 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
end
def commit
@commit = Gitea::Repository::Commits::GetService.new(@repository.user.login, @repository.identifier, params[:sha], current_user.gitea_token).call
end
def tags
@tags = Gitea::Repository::Tags::ListService.new(current_user&.gitea_token, @project.owner.login, @project.identifier, {page: params[:page], limit: params[:limit]}).call
end
def edit
end
def create_file
interactor = Gitea::CreateFileInteractor.call(current_user.gitea_token, @project.owner.login, content_params)
if interactor.success?
@file = interactor.result
create_new_pr(params)
else
render_error(interactor.error)
end
end
def update_file
interactor = Gitea::UpdateFileInteractor.call(current_user.gitea_token, @owner.login, params.merge(identifier: @project.identifier))
interactor = Gitea::UpdateFileInteractor.call(current_user.gitea_token, @project.owner.login, params.merge(identifier: @project.identifier))
if interactor.success?
@file = interactor.result
# TODO: 是否创建pr
# create_new_pr(params)
create_new_pr(params)
render_result(1, "更新成功")
else
render_error(interactor.error)
@ -168,7 +89,7 @@ class RepositoriesController < ApplicationController
end
def delete_file
interactor = Gitea::DeleteFileInteractor.call(current_user.gitea_token, @owner.login, params.merge(identifier: @project.identifier))
interactor = Gitea::DeleteFileInteractor.call(current_user.gitea_token, @project.owner.login, params.merge(identifier: @project.identifier))
if interactor.success?
@file = interactor.result
render_result(1, "文件删除成功")
@ -189,47 +110,6 @@ class RepositoriesController < ApplicationController
render_ok
end
def readme
if params[:filepath].present?
result = Gitea::Repository::Readme::DirService.call(@owner.login, @repository.identifier, params[:filepath], params[:ref], current_user&.gitea_token)
else
result = Gitea::Repository::Readme::GetService.call(@owner.login, @repository.identifier, params[:ref], current_user&.gitea_token)
end
@readme = result[:status] === :success ? result[:body] : nil
@readme['content'] = decode64_content(@readme, @owner, @repository, params[:ref])
render json: @readme.slice("type", "encoding", "size", "name", "path", "content", "sha")
rescue
render json: nil
end
def languages
render json: languages_precentagable
end
def archive
domain = Gitea.gitea_config[:domain]
api_url = Gitea.gitea_config[:base_url]
archive_url = "/repos/#{@owner.login}/#{@repository.identifier}/archive/#{params[:archive]}"
file_path = [domain, api_url, archive_url].join
file_path = [file_path, "access_token=#{current_user&.gitea_token}"].join("?") if @repository.hidden?
return render_not_found if !request.format.zip? && !request.format.gzip?
redirect_to file_path
end
def raw
domain = Gitea.gitea_config[:domain]
api_url = Gitea.gitea_config[:base_url]
url = "/repos/#{@owner.login}/#{@repository.identifier}/raw/#{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 URI.escape(file_path)
end
private
def find_project
@ -250,29 +130,23 @@ class RepositoriesController < ApplicationController
# TODO 获取最新commit信息
def project_commits
if params[:filepath].present?
file_path_uri = URI.parse(URI.encode(params[:filepath].to_s.strip))
Gitea::Repository::Commits::FileListService.new(@project.owner.login, @project.identifier, file_path_uri,
sha: get_ref, page: 1, limit: 1, token: current_user&.gitea_token).call
else
Gitea::Repository::Commits::ListService.new(@project.owner.login, @project.identifier,
sha: get_ref, page: 1, limit: 1, token: current_user&.gitea_token).call
end
Gitea::Repository::Commits::ListService.new(@project.owner.login, @project.identifier,
sha: get_ref, page: 1, limit: 1, token: current_user&.gitea_token).call
end
def get_statistics
@branches_count = @project.educoder? ? 0 : Gitea::Repository::Branches::ListService.new(@project.owner, @project.identifier).call&.size
@tags_count = @project.educoder? ? 0 : Gitea::Repository::Tags::ListService.new(current_user&.gitea_token, @project.owner.login, @project.identifier).call&.size
@branches_count = Gitea::Repository::Branches::ListService.new(@project.owner, @project.identifier).call&.size
@tags_count = Gitea::Repository::Tags::ListService.new(current_user&.gitea_token, @project.owner.login, @project.identifier).call&.size
end
def get_ref
@ref = params[:ref] || @project&.default_branch
@ref = params[:ref] || "master"
end
def get_latest_commit
latest_commit = @project.educoder? ? nil : project_commits
@latest_commit = latest_commit.present? ? latest_commit[:body][0] : nil
@commits_count = latest_commit.present? ? latest_commit[:total_count] : 0
latest_commit = project_commits
@latest_commit = latest_commit[:body][0] if latest_commit.present?
@commits_count = latest_commit[:total_count] if latest_commit.present?
end
def content_params
@ -310,7 +184,7 @@ class RepositoriesController < ApplicationController
# uploadPushInfo
end
def create_new_pr(params)
if params[:new_branch].present? && params[:new_branch] != params[:branch]
local_params = {
@ -340,14 +214,14 @@ class RepositoriesController < ApplicationController
issue_type: "1",
tracker_id: 2,
status_id: 1,
priority_id: params[:priority_id] || "2"
priority_id: 1
}
@pull_issue = Issue.new(issue_params)
if @pull_issue.save!
local_requests = PullRequest.new(local_params.merge(user_id: current_user.try(:id), project_id: @project.id, issue_id: @pull_issue.id))
if local_requests.save
gitea_request = Gitea::PullRequest::CreateService.new(current_user.try(:gitea_token), @owner.login, @project.try(:identifier), requests_params).call
if gitea_request[:status] == :success && local_requests.update_attributes(gitea_number: gitea_request["body"]["number"])
gitea_request = Gitea::PullRequest::CreateService.new(current_user.try(:gitea_token), @project.owner, @project.try(:identifier), requests_params).call
if gitea_request && local_requests.update_attributes(gpid: gitea_request["number"])
local_requests.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: "create")
end
end

View File

@ -1,70 +1,6 @@
class SettingsController < ApplicationController
def show
@old_projects_url = nil
get_add_menu
get_common_menu
get_personal_menu
get_third_party
get_top_system_notification
@old_projects_url = nil
@old_projects_url = "https://www.trustie.net/users/#{current_user.try(:login)}/projects" if User.current.logged?
end
private
def get_add_menu
@add = []
Site.add.select(:id, :name, :url, :key).to_a.map(&:serializable_hash).each do |site|
hash = {}
site.each {|k, v|
hash.merge!("#{k}": get_site_url(k, v))
}
@add << hash
end
end
def get_common_menu
@common = {}
Site.common.select(:url, :key).each do |site|
next if site["url"].to_s.include?("current_user") && !User.current.logged?
@common.merge!("#{site["key"]}": append_http(reset_site_url(site["url"])))
end
end
def get_personal_menu
@personal = []
if User.current.logged?
Site.personal.select(:id, :name, :url, :key).to_a.map(&:serializable_hash).each do |site|
hash = {}
site.each {|k, v|
hash.merge!("#{k}": get_site_url(k, v))
}
@personal << hash
end
end
end
def get_third_party
@third_party = []
@third_party << {
name: 'educoder',
url: EducoderOauth.oauth_url
}
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
def reset_site_url(url)
return url unless url.to_s.include?("current_user")
split_arr = url.split('current_user')
split_arr.length > 1 ? split_arr.join(current_user&.login) : (split_arr << current_user&.login).join('')
end
def append_http(url)
url.to_s.start_with?("http") ? url : [request.protocol, request.host_with_port, url].join('')
end
end

View File

@ -12,11 +12,11 @@ class SyncForgeController < ApplicationController
end
end
# def create
# def create
# ActiveRecord::Base.transaction do
# params.permit!
# sync_params = params[:sync_params]
# project_user = User.where(login: sync_params[:owner_login])&.first
# project_user = User.where(login: sync_params[:owner_login])&.first
# #以前已同步的项目,那么肯定存在仓库
# SyncLog.sync_log("=================begin_to_sync_forge: project_identifier: #{sync_params[:identifier]}========")
# user_projects = Project.where(user_id: project_user.id)
@ -38,7 +38,7 @@ class SyncForgeController < ApplicationController
# check_sync_project(project, sync_params)
# else #新建项目
# SyncLog.sync_log("=================begin_to_create_new_project========")
# project_params = {
# repository_name: sync_params[:identifier],
# user_id: project_user.id,
@ -53,7 +53,7 @@ class SyncForgeController < ApplicationController
# new_project_score = ProjectScore.create(score_params)
# SyncLog.sync_log("=================new_project_score:#{new_project_score.try(:id)}========")
# end
# SyncRepositoryJob.perform_later(sync_params[:owner_login], sync_params[:identifier], sync_params[:repository], get_sudomain) if sync_params[:repository].present?
# check_new_project(project, sync_params)
# else
@ -115,7 +115,7 @@ class SyncForgeController < ApplicationController
# SyncLog.sync_log("=================sync_user_failed====#{e}")
# end
# private
# private
# def check_sync_project(project,sync_params)
# begin
@ -125,8 +125,8 @@ class SyncForgeController < ApplicationController
# # end
# SyncLog.sync_log("----begin_to_check_sync_project----project_id:#{project.id}---------------")
# change_project_score(project, sync_params[:project_score], sync_params[:repository]) if sync_params[:repository].present? #更新project_score
# change_project_issues(project, sync_params[:issues],project.id, gitea_main)
# change_project_score(project, sync_params[:project_score], sync_params[:repository]) if sync_params[:repository].present? #更新project_score
# change_project_issues(project, sync_params[:issues],project.id, gitea_main)
# change_project_members(project, sync_params[:members],gitea_main)
# change_project_versions(project, sync_params[:project_versions],gitea_main)
# change_project_watchers(project, sync_params[:project_watchers],gitea_main)
@ -134,7 +134,7 @@ class SyncForgeController < ApplicationController
# rescue => e
# SyncLog.sync_log("=========check_sync_project_errors:#{e}===================")
# end
# end
# def check_new_project(project,sync_params)
@ -167,7 +167,7 @@ class SyncForgeController < ApplicationController
# parent_id: project.id
# }
# SyncProjectsJob.perform_later(sync_projects_params,gitea_main)
# SyncLog.sync_log("***6. end_to_sync_parises---------------")
# end
# end
@ -189,7 +189,7 @@ class SyncForgeController < ApplicationController
# end
# end
# pre_project_score.save! if change_num > 0 #如果 project_score有变化则更新
# else
# else
# ProjectScore.create!(project_scores.merge(project_id: project.id))
# end
# SyncLog.sync_log("***1. end_to_sync_project_score---------------")
@ -206,7 +206,7 @@ class SyncForgeController < ApplicationController
# SyncLog.sync_log("***2--01. forge_issue_ids-#{forge_issue_ids.size.to_i}--------------")
# if forge_issue_ids.size.to_i <= old_issues_params[:count].to_i
# diff_issue_ids = old_issues_params[:ids] - forge_issue_ids
# if diff_issue_ids.size == 0 #issue数量一样判断评论是否有增减
# forge_journal_ids = Journal.select([:id, :journalized_id, :journalized_type]).where(journalized_id: forge_issue_ids).pluck(:id)
# diff_journal_ids = old_issues_params[:journals][:ids] - forge_journal_ids
@ -241,10 +241,10 @@ class SyncForgeController < ApplicationController
# # }
# # SyncLog.sync_log("***2--03. sync_projects_params_groups-#{sync_projects_params}--------------")
# # SyncProjectsJob.perform_later(sync_projects_params, gitea_main)
# end
# end
# # SyncProjectsJob.perform_later(sync_projects_params, gitea_main) if sync_projects_params.present?
# SyncLog.sync_log("***2. end_to_syncissues---------------")
# rescue Exception => e
@ -265,7 +265,7 @@ class SyncForgeController < ApplicationController
# parent_id: project.id
# }
# SyncProjectsJob.perform_later(sync_projects_params,gitea_main)
# end
# end
# SyncLog.sync_log("***5. begin_to_sync_watchers---------------")
@ -285,7 +285,7 @@ class SyncForgeController < ApplicationController
# }
# SyncProjectsJob.perform_later(sync_projects_params,gitea_main)
# end
# SyncLog.sync_log("***4. end_to_sync_versions---------------")
# end
# end
@ -304,12 +304,12 @@ class SyncForgeController < ApplicationController
# }
# SyncProjectsJob.perform_later(sync_projects_params,gitea_main)
# end
# SyncLog.sync_log("***3. end_to_sync_members---------------")
# end
# end
# def check_token
# def check_token
# sync_params = params[:sync_params]
# unless sync_params[:token] && sync_params[:token] == get_token
# render json: {message: "token_errors"}
@ -331,4 +331,4 @@ class SyncForgeController < ApplicationController
# return gitea_main
# end
end
end

View File

@ -1,8 +1,8 @@
class Users::BanksController < Users::BaseController
before_action :params_filter
def index
order = CourseList.column_names.include?(params[:order]) ? params[:order] : "updated_at"
sort = %w(desc asc).includes?(params[:sort]) ? params[:sort] : "desc"
order = params[:order] || "updated_at"
sort = params[:sort] || "desc"
@banks = @object_type.classify.constantize.where(@object_filter)
@course_lists = CourseList.where(id: @banks.pluck(:course_list_id))
@banks = @banks.where(course_list_id: params[:tag_id]) unless params[:tag_id].blank?

View File

@ -5,7 +5,7 @@ class Users::BaseController < ApplicationController
helper_method :observed_logged_user?, :observed_user
def observed_user
@_observed_user ||= (User.find_by_login(params[:user_id]) || User.find_by_id(params[:user_id]))
@_observed_user ||= (User.find_by_id(params[:user_id]) || User.find_by_login(params[:user_id]))
end
def observed_logged_user?

View File

@ -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]) if Site.has_notice_menu?
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]) if Site.has_notice_menu?
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]) if Site.has_notice_menu?
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]) if Site.has_notice_menu?
SendTemplateMessageJob.perform_now('IssueAtme', @receivers, current_user.id, atme_params[:atmeable_id])
end
end
end

View File

@ -188,32 +188,30 @@ class Users::StatisticsController < Users::BaseController
@project_languages_count = time_filter(Project.where(user_id: observed_user.id), 'created_on').joins(:project_language).group("project_languages.name").count
@platform_project_languages_count = time_filter(Project, 'created_on').joins(:project_language).group("project_languages.name").count
else
@platform_result = Cache::V2::PlatformStatisticService.new.read
@user_result = Cache::V2::UserStatisticService.new(observed_user.id).read
# 用户被follow数量
@follow_count = @user_result["follow-count"].to_i
@platform_follow_count = @platform_result["follow-count"].to_i
@follow_count = Cache::UserFollowCountService.call(observed_user)
@platform_follow_count = Cache::PlatformFollowCountService.call
# 用户pr数量
@pullrequest_count = @user_result["pullrequest-count"].to_i
@platform_pullrequest_count = @platform_result["pullrequest-count"].to_i
@pullrequest_count = Cache::UserPullrequestCountService.call(observed_user)
@platform_pullrequest_count = Cache::PlatformPullrequestCountService.call
# 用户issue数量
@issues_count = @user_result["issue-count"].to_i
@platform_issues_count = @platform_result["issue-count"].to_i
@issues_count = Cache::UserIssueCountService.call(observed_user)
@platform_issues_count = Cache::PlatformIssueCountService.call
# 用户总项目数
@project_count = @user_result["project-count"].to_i
@platform_project_count = @platform_result["project-count"].to_i
@project_count = Cache::UserProjectCountService.call(observed_user)
@platform_project_count = Cache::PlatformProjectCountService.call
# 用户项目被fork数量
@fork_count = @user_result["fork-count"].to_i
@platform_fork_count = @platform_result["fork-count"].to_i
@fork_count = Cache::UserProjectForkCountService.call(observed_user)
@platform_fork_count = Cache::PlatformProjectForkCountService.call
# 用户项目关注数
@project_watchers_count = @user_result["project-watcher-count"].to_i
@platform_project_watchers_count = @platform_result["project-watcher-count"].to_i
@project_watchers_count = Cache::UserProjectWatchersCountService.call(observed_user)
@platform_project_watchers_count = Cache::PlatformProjectWatchersCountService.call
# 用户项目点赞数
@project_praises_count = @user_result["project-praise-count"].to_i
@platform_project_praises_count = @platform_result["project-praise-count"].to_i
@project_praises_count = Cache::UserProjectPraisesCountService.call(observed_user)
@platform_project_praises_count = Cache::PlatformProjectPraisesCountService.call
# 用户不同语言项目数量
@project_languages_count = JSON.parse(@user_result["project-language"])
@platform_project_languages_count = JSON.parse(@platform_result["project-language"])
@project_languages_count = Cache::UserProjectLanguagesCountService.call(observed_user)
@platform_project_languages_count = Cache::PlatformProjectLanguagesCountService.call
end
end
end

View File

@ -1,25 +1,10 @@
class UsersController < ApplicationController
include ApplicationHelper
include Ci::DbConnectable
before_action :load_user, only: [:show, :homepage_info, :sync_token, :sync_gitea_pwd, :projects, :watch_users, :fan_users, :hovercard]
before_action :check_user_exist, only: [:show, :homepage_info,:projects, :watch_users, :fan_users, :hovercard]
before_action :require_login, only: %i[me list sync_user_info]
before_action :connect_to_ci_db, only: [:get_user_info]
before_action :convert_image!, only: [:update]
before_action :load_user, only: [:show, :homepage_info, :sync_token, :sync_gitea_pwd, :projects, :watch_users, :fan_users]
before_action :check_user_exist, only: [:show, :homepage_info,:projects, :watch_users, :fan_users]
before_action :require_login, only: %i[me list]
skip_before_action :check_sign, only: [:attachment_show]
def connect_to_ci_db(options={})
if !(current_user && !current_user.is_a?(AnonymousUser) && current_user.devops_certification?)
return
end
if current_user.ci_cloud_account.server_type == Ci::CloudAccount::SERVER_TYPE_TRUSTIE
connect_to_trustie_ci_database(options)
else
connect_to_ci_database(options)
end
end
def list
scope = User.active.recent.like(params[:search]).includes(:user_extension)
@total_count = scope.size
@ -28,31 +13,14 @@ class UsersController < ApplicationController
def show
#待办事项,现在未做
if User.current.admin? || User.current.login == @user.login
@waiting_applied_messages = @user.applied_messages.waiting
@common_applied_transfer_projects = AppliedTransferProject.where(owner_id: @user.id).common + AppliedTransferProject.where(owner_id: Organization.joins(team_users: :team).where(team_users: {user_id: @user.id}, teams: {authorize: %w(admin owner)} )).common
@common_applied_projects = AppliedProject.where(project_id: @user.full_admin_projects).common
@undo_events = @waiting_applied_messages.size + @common_applied_transfer_projects.size + @common_applied_projects.size
else
@waiting_applied_messages = AppliedMessage.none
@common_applied_transfer_projects = AppliedTransferProject.none
@common_applied_projects = AppliedProject.none
@undo_events = 0
end
@undo_events = 0
#用户的组织数量
# @user_composes_count = @user.composes.size
@user_composes_count = 0
user_organizations = User.current.logged? ? @user.organizations.with_visibility(%w(common limited)) + @user.organizations.with_visibility("privacy").joins(:team_users).where(team_users: {user_id: current_user.id}) : @user.organizations.with_visibility("common")
@user_org_count = user_organizations.size
normal_projects = Project.members_projects(@user.id).to_sql
org_projects = Project.joins(team_projects: [team: :team_users]).where(team_users: {user_id: @user.id}).to_sql
projects = Project.from("( #{ normal_projects} UNION #{ org_projects } ) AS projects").distinct
user_projects = User.current.logged? && (User.current.admin? || User.current.login == @user.login) ? projects : projects.visible
user_projects = User.current.logged? && (User.current.admin? || User.current.login == @user.login) ? @user.projects : @user.projects.visible
@projects_common_count = user_projects.common.size
@projects_mirrior_count = user_projects.mirror.size
@projects_sync_mirrior_count = user_projects.sync_mirror.size
# 为了缓存活跃用户的基本信息,后续删除
Cache::V2::OwnerCommonService.new(@user.id).read
end
def watch_users
@ -67,22 +35,16 @@ class UsersController < ApplicationController
def fan_users
watchers = @user.watchers.includes(:user).order("watchers.created_at desc")
watchers = watchers.joins(:user).merge(User.like(params[:search]))
watchers = watchers.joins(:user).where("LOWER(concat(users.lastname, users.firstname, users.login)) LIKE ?", "%#{params[:search].split(" ").join('|')}%") if params[:search].present?
@watchers_count = watchers.size
@watchers = paginate(watchers)
end
def hovercard
end
def update
return render_not_found unless @user = User.find_by(login: params[:id]) || User.find_by_id(params[:id])
return render_forbidden unless User.current.logged? && (current_user&.admin? || current_user.id == @user.id)
Util.write_file(@image, avatar_path(@user)) if user_params[:image].present?
@user.attributes = user_params.except(:image)
unless @user.save
render_error(@user.errors.full_messages.join(", "))
end
@user = User.find params[:id]
@user.update!(user_params)
render_ok
end
def me
@ -93,12 +55,6 @@ class UsersController < ApplicationController
def get_user_info
begin
@user = current_user
begin
result = Notice::Read::CountService.call(current_user.id)
@message_unread_total = result.nil? ? 0 : result[2]["unread_notification"]
rescue
@message_unread_total = 0
end
# TODO 等消息上线再打开注释
#@tidding_count = unviewed_tiddings(current_user) if current_user.present?
rescue Exception => e
@ -110,7 +66,7 @@ class UsersController < ApplicationController
def attachment_show
file_name = params[:file_name]
path = params[:path] || file_storage_directory
path = params[:path] || edu_setting('attachment_folder')
send_file "#{path}/#{file_name}", :filename => "#{file_name}",
:type => 'game',
:disposition => 'attachment' #inline can open in browser
@ -193,7 +149,7 @@ class UsersController < ApplicationController
def trustie_related_projects
projects = Project.includes(:owner, :members, :project_score).where(id: params[:ids]).order("updated_on desc")
projects_json = []
domain_url = EduSetting.get('host_name')
domain_url = EduSetting.get('host_name') + '/projects'
if projects.present?
projects.each do |p|
project_url = "/#{p.owner.login}/#{p.identifier}"
@ -262,39 +218,17 @@ class UsersController < ApplicationController
render_ok
end
def sync_user_info
user = User.find_by_login params[:login]
return render_forbidden unless user === current_user
sync_params = {
email: params[:email],
password: params[:password]
}
Users::UpdateInfoForm.new(sync_params.merge(login: params[:login])).validate!
interactor = Gitea::User::UpdateInteractor.call(user.login, sync_params)
if interactor.success?
user.update!(password: params[:password], mail: params[:email], status: User::STATUS_ACTIVE)
render_ok
else
render_error(interactor.error)
end
end
private
def load_user
@user = User.find_by_login(params[:id]) || User.find_by(id: params[:id])
end
def user_params
params.require(:user).permit(:nickname, :image,
params.require(:user).permit(:nickname, :lastname, :show_realname,:login,:mail,
user_extension_attributes: [
:gender, :location, :location_city,
:occupation, :technical_title,
:school_id, :department_id, :province, :city,
:custom_department, :identity, :student_id, :description,
:show_email, :show_location, :show_department]
:school_id, :department_id,:identity, :student_id, :description]
)
end

View File

@ -11,7 +11,7 @@ class UsersForPrivateMessagesController < ApplicationController
return
end
users = users.like(keyword)
users = users.where('LOWER(concat(lastname, firstname, nickname)) LIKE ?', "%#{keyword}%")
@users = users.limit(10).includes(:user_extension)
end

View File

@ -1,14 +1,14 @@
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]
before_action :require_login, except: [:index]
before_action :find_version , only: [:edit, :update, :destroy]
def index
@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?)
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? && (current_user == @user || current_user.admin?)
@forge_releases = @repository.version_releases.select(:id,:version_gid).includes(:attachments)
end
def new
@ -22,10 +22,6 @@ 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, "名称不能为空")
@ -41,14 +37,13 @@ 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(current_user.gitea_token, @user.try(:login), @repository.try(:identifier), version_params).call
git_version_release = Gitea::Versions::CreateService.new(@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"],
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")
@ -86,7 +81,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(current_user.gitea_token, @user.try(:login), @repository.try(:identifier), version_params, @version.try(:version_gid)).call
git_version_release = Gitea::Versions::UpdateService.new(@user.gitea_token, @user.try(:login), @repository.try(:identifier), version_params, @version.try(:version_gid)).call
unless git_version_release
raise Error, "更新失败"
end
@ -107,7 +102,7 @@ class VersionReleasesController < ApplicationController
ActiveRecord::Base.transaction do
begin
if @version.destroy
git_version_release = Gitea::Versions::DeleteService.new(current_user.gitea_token, @user.try(:login), @repository.try(:identifier), @version.try(:version_gid)).call
git_version_release = Gitea::Versions::DeleteService.new(@user.gitea_token, @user.try(:login), @repository.try(:identifier), @version.try(:version_gid)).call
if git_version_release.status == 204
normal_status(0, "删除成功")
@ -129,7 +124,7 @@ class VersionReleasesController < ApplicationController
private
def set_user
@user = @repository.owner
@user = @repository.user
end
def find_version
@ -162,8 +157,4 @@ class VersionReleasesController < ApplicationController
end
end
def check_release_authorize
return render_forbidden("您没有权限进行此操作.") unless current_user.admin? || @project.manager?(current_user)
end
end

View File

@ -1,13 +1,13 @@
class VersionsController < ApplicationController
before_action :require_login, except: [:index, :show]
before_action :require_profile_completed, only: [:create]
before_action :load_repository
before_action :check_menu_authorize
before_action :check_issue_permission, except: [:show, :index]
before_action :set_version, only: [:edit, :update, :destroy, :show,:update_status]
def index
@user_admin_or_member = current_user.present? && (current_user.admin || @project.member?(current_user))
order_name = params[:order_name] || "created_on"
order_type = params[:order_type] || "desc"
status = params[:status]
versions = @project.versions.version_includes
@open_versions_size = versions.where(status: "open")&.size
@ -26,13 +26,20 @@ class VersionsController < ApplicationController
end
def show
version_issues = @version.issues.issue_issue.issue_includes
order_name = params[:order_name] || "created_on"
order_type = params[:order_type] || "desc"
version_issues = @version.issues.issue_includes
status_type = params[:status_type] || "1"
# @close_issues_size = version_issues.where(status_id: 5).size
# @open_issues_size = version_issues.size - @close_issues_size
if status_type.to_s == "1" #表示开启中的
version_issues = version_issues.where.not(status_id: 5)
else
version_issues = version_issues.where(status_id: 5)
end
version_issues = version_issues.where(author_id: params[:author_id]) if params[:author_id].present? && params[:author_id].to_s != "all"
version_issues = version_issues.where(assigned_to_id: params[:assigned_to_id]) if params[:assigned_to_id].present? && params[:assigned_to_id].to_s != "all"
version_issues = version_issues.where(tracker_id: params[:tracker_id]) if params[:tracker_id].present? && params[:tracker_id].to_s != "all"
@ -44,26 +51,10 @@ class VersionsController < ApplicationController
version_issues = version_issues.joins(:issue_tags).where(issue_tags: {id: params[:issue_tag_id].to_i}) if params[:issue_tag_id].present? && params[:issue_tag_id].to_s != "all"
version_issues = version_issues.reorder("#{order_name} #{order_type}")
has_filter_params = (params[:author_id].present? && params[:author_id].to_s != "all") ||
(params[:assigned_to_id].present? && params[:assigned_to_id].to_s != "all") ||
(params[:tracker_id].present? && params[:tracker_id].to_s != "all") ||
(params[:status_id].present? && params[:status_id].to_s != "all") ||
(params[:priority_id].present? && params[:priority_id].to_s != "all") ||
(params[:fixed_version_id].present? && params[:fixed_version_id].to_s != "all") ||
(params[:done_ratio].present? && params[:done_ratio].to_s != "all") ||
(params[:issue_type].present? && params[:issue_type].to_s != "all") ||
(params[:issue_tag_id].present? && params[:issue_tag_id].to_s != "all")
@version_close_issues_size = has_filter_params ? version_issues.closed.size : @version.issues.issue_issue.issue_includes.closed.size
@version_issues_size = has_filter_params ? version_issues.size : @version.issues.issue_issue.issue_includes.size
if status_type.to_s == "1" #表示开启中的
version_issues = version_issues.where.not(status_id: 5)
else
version_issues = version_issues.where(status_id: 5)
end
@page = params[:page] || 1
@limit = params[:limit] || 15
# @version_issues_size = version_issues.size
@version_issues_size = version_issues.size
@version_issues = version_issues.page(@page).per(@limit)
end
@ -175,16 +166,4 @@ class VersionsController < ApplicationController
end
end
def order_name
Version.column_names.include?(params[:order_name]) ? params[:order_name] : 'created_on'
end
def order_type
%w(desc asc).include?(params[:order_type]) ? params[:order_type] : 'desc'
end
def check_menu_authorize
return render_not_found unless @project.has_menu_permission("versions")
end
end

View File

@ -1,6 +1,5 @@
class WatchersController < ApplicationController
before_action :require_login, except: %i[index]
before_action :require_profile_completed, only: [:follow]
# before_action :find_project_with_id
before_action :get_target

View File

@ -86,7 +86,7 @@ class Weapps::CoursesController < Weapps::BaseController
end
if search.present?
@teacher_list = @teacher_list.joins(:user).where("LOWER(CONCAT(users.lastname, users.firstname)) like ? OR users.nickname like ?", "%#{search}%", "%#{search}%")
@teacher_list = @teacher_list.joins(:user).where("LOWER(CONCAT(users.lastname, users.firstname)) like ?", "%#{search}%")
end
@teacher_list_size = @teacher_list.size
@ -127,8 +127,8 @@ class Weapps::CoursesController < Weapps::BaseController
@students = CourseMember.students(@course)
if search.present?
@students = @students.joins(user: :user_extension).where("LOWER(CONCAT(users.lastname, users.firstname)) like ? or users.nickname like ? or
user_extensions.student_id like ?", "%#{search}%", "%#{search}%", "%#{search}%")
@students = @students.joins(user: :user_extension).where("LOWER(CONCAT(users.lastname, users.firstname)) like ? or
user_extensions.student_id like ?", "%#{search}%", "%#{search}%")
end
if course_group_id.present?

View File

@ -86,7 +86,7 @@ class ZipsController < ApplicationController
#搜索
if params[:search].present?
@ex_users = @ex_users.joins(user: :user_extension).where("CONCAT(lastname, firstname) like ? OR nickname like ? OR student_id like ?", "%#{params[:search]}%", "%#{params[:search]}%", "%#{params[:search]}%")
@ex_users = @ex_users.joins(user: :user_extension).where("CONCAT(lastname, firstname) like ? OR student_id like ?", "%#{params[:search]}%", "%#{params[:search]}%")
end
default_ex_users_size = @ex_users&.size
@ -130,8 +130,8 @@ class ZipsController < ApplicationController
end
unless params[:search].blank?
@all_student_works = @all_student_works.joins(user: :user_extension).where("CONCAT(lastname, firstname) like ? or nickname like ?
or student_id like ?", "%#{params[:search]}%", "%#{params[:search]}%", "%#{params[:search]}%")
@all_student_works = @all_student_works.joins(user: :user_extension).where("concat(lastname, firstname) like ?
or student_id like ?", "%#{params[:search]}%", "%#{params[:search]}%")
end
student_work_sizes = @all_student_works&.size

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

View File

@ -1,502 +1 @@
# 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|commits 提交时间距当前时间的时间值|
|-- message |string|commit说明信息|
|-- sha |string|commits 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|commits 提交时间距当前时间的时间值|
|-- message |string|commit说明信息|
|-- sha |string|commits 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
}
]
}
```

View File

@ -199,36 +199,6 @@ await octokit.request('GET /api/users/:login/messages.json')
Success Data.
</aside>
## 用户阅读系统通知
用户阅读系统通知
> 示例:
```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
@ -402,290 +372,6 @@ 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::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": "我创建的或负责的",
"total_settings_count": 4,
"settings": [
{
"name": "易修被指派",
"key": "IssueAssigned",
"notification_disabled": true,
"email_disabled": false
},
{
"name": "合并请求被指派",
"key": "PullRequestAssigned",
"notification_disabled": true,
"email_disabled": false
}
]
},
{
"type": "TemplateMessageSetting::ManageProject",
"type_name": "我管理的仓库",
"total_settings_count": 4,
"settings": [
{
"name": "有新的易修",
"key": "Issue",
"notification_disabled": true,
"email_disabled": false
},
{
"name": "有新的合并请求",
"key": "PullRequest",
"notification_disabled": true,
"email_disabled": false
},
{
"name": "有成员变动",
"key": "Member",
"notification_disabled": true,
"email_disabled": false
},
{
"name": "设置更改",
"key": "SettingChanged",
"notification_disabled": true,
"email_disabled": false
}
]
}
]
}
```
<aside class="success">
Success Data.
</aside>
## 获取用户消息设置配置信息
获取用户消息设置配置信息
> 示例:
```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::IssueAssigned": true,
"CreateOrAssign::PullRequestAssigned": 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::IssueAssigned": false,
"CreateOrAssign::PullRequestAssigned": false,
"ManageProject::Issue": false,
"ManageProject::PullRequest": false,
"ManageProject::Member": false,
"ManageProject::SettingChanged": true,
"Normal::Organization": false,
"Normal::Project": true,
"Normal::Permission": false
}
}
```
<aside class="success">
Success Data.
</aside>
## 重新设置用户消息设置配置信息
重新设置用户消息设置配置信息
> 示例:
```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::IssueAssigned": true,
"CreateOrAssign::PullRequestAssigned": 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::IssueAssigned": false,
"CreateOrAssign::PullRequestAssigned": 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::IssueAssigned": true,
"CreateOrAssign::PullRequestAssigned": 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::IssueAssigned": false,
"CreateOrAssign::PullRequestAssigned": false,
"ManageProject::Issue": false,
"ManageProject::PullRequest": false,
"ManageProject::Member": false,
"ManageProject::SettingChanged": true,
"Normal::Organization": false,
"Normal::Project": true,
"Normal::Permission": false
}
}
```
<aside class="success">
Success Data.
</aside>
## 获取用户星标项目
获取用户星标项目

View File

@ -1,68 +1,19 @@
class BaseForm
include ActiveModel::Model
Error = Class.new(StandardError)
EmailError = Class.new(Error)
LoginError = Class.new(Error)
PhoneError = Class.new(Error)
PasswordFormatError = Class.new(Error)
VerifiCodeError = Class.new(Error)
PasswordConfirmationError = Class.new(Error)
def check_project_category(project_category_id)
unless project_category_id == ''
raise "project_category_id参数值无效." if project_category_id && !ProjectCategory.exists?(project_category_id)
end
raise "project_category_id参数值无效." if (ProjectCategory.find_by_id project_category_id).blank?
end
def check_project_language(project_language_id)
unless project_language_id == ''
raise "project_language_id参数值无效." if project_language_id && !ProjectLanguage.exists?(project_language_id)
end
raise "project_language_id参数值无效." if (ProjectLanguage.find_by_id project_language_id).blank?
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?
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.check_exists?(repository_name)
end
def check_password(password)
password = strip(password)
raise PasswordFormatError, "密码8~16位密码支持字母数字和符号" unless password =~ CustomRegexp::PASSWORD
end
def check_password_confirmation(password, password_confirmation)
password = strip(password)
password_confirmation = strip(password_confirmation)
raise PasswordFormatError, "确认密码为8~16位密码支持字母数字和符号" unless password_confirmation =~ CustomRegexp::PASSWORD
raise PasswordConfirmationError, "两次输入的密码不一致" unless password == password_confirmation
end
def check_verifi_code(verifi_code, code)
code = strip(code)
# return if code == "123123" # TODO 万能验证码,用于测试
raise VerifiCodeError, "验证码不正确" if verifi_code&.code != code
raise VerifiCodeError, "验证码已失效" if !verifi_code&.effective?
end
private
def strip(str)
str.to_s.strip.presence
end
# 1 手机类型0 邮箱类型
# 注意新版的login是自动名生成的
def phone_mail_type value
value =~ /^1\d{10}$/ ? 1 : 0
end
end

View File

@ -5,7 +5,7 @@ class Issues::CreateForm
validates :subject, presence: { message: "不能为空" }
validates :subject, length: { maximum: 200, too_long: "不能超过200个字符" }
validates :subject, length: { maximum: 80, too_long: "不能超过80个字符" }
end

View File

@ -5,6 +5,6 @@ class Issues::UpdateForm
validates :subject, presence: { message: "不能为空" }
validates :subject, length: { maximum: 200, too_long: "不能超过200个字符" }
validates :subject, length: { maximum: 80, too_long: "不能超过80个字符" }
end

View File

@ -1,20 +1,16 @@
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: CustomRegexp::REPOSITORY_NAME_REGEX, multiline: true, message: "只能含有数字、字母、下划线且不能以下划线开头和结尾" }
:project_language_id, :ignore_id, :license_id, :private
validates :name, length: { maximum: 50 }
validates :repository_name, length: { maximum: 100 }
validates :description, length: { maximum: 200 }
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: "只能含有数字、字母、下划线且不能以下划线开头和结尾" }
validate :check_ignore, :check_license, :check_owner, :check_max_repo_creation
validate :check_ignore, :check_license
validate do
check_project_category(project_category_id)
check_project_language(project_language_id)
check_project_name(user_id, name) unless name.blank?
check_repository_name(user_id, repository_name) unless repository_name.blank?
end
def check_license
@ -24,16 +20,4 @@ class Projects::CreateForm < BaseForm
def check_ignore
raise "ignore_id值无效." if ignore_id && Ignore.find_by(id: ignore_id).blank?
end
def check_owner
@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 @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

View File

@ -1,30 +1,17 @@
class Projects::MigrateForm < BaseForm
attr_accessor :user_id, :name, :repository_name, :project_category_id, :description,
:project_language_id, :clone_addr, :private, :is_mirror, :auth_username, :auth_password, :owner
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
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 }
attr_accessor :user_id, :name, :description, :repository_name, :project_category_id, :project_language_id, :clone_addr, :private, :is_mirror, :auth_username, :auth_password
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: "地址格式不正确" }
validate do
check_project_name(user_id, name) unless name.blank?
check_repository_name(user_id, repository_name) unless repository_name.blank?
check_project_category(project_category_id)
check_project_language(project_language_id)
check_owner
check_max_repo_creation
end
def check_owner
@owner = Owner.find_by(id: user_id)
raise "user_id值无效." if user_id && 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
end
end

View File

@ -1,15 +1,4 @@
class Projects::UpdateForm < BaseForm
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 }
validates :identifier, format: { with: CustomRegexp::REPOSITORY_NAME_REGEX, multiline: true, message: "只能含有数字、字母、下划线且不能以下划线开头和结尾" }
validate do
check_project_category(project_category_id)
check_project_language(project_language_id)
check_repository_name(user_id, identifier) unless identifier.blank? || identifier == project_identifier
end
attr_reader :name, :description, :repository_name, :project_category_id
end

View File

@ -4,7 +4,7 @@ module Admins::ProjectsHelper
owner = project.owner
if owner.is_a?(User)
link_to(project.owner&.real_name, "/#{project&.owner&.login}", target: '_blank')
link_to(project.owner&.real_name, "/users/#{project&.owner&.login}", target: '_blank')
elsif owner.is_a?(Organization)
link_to(project.owner&.real_name, "/organize/#{project&.owner&.login}", target: '_blank')
else

553
app/helpers/api_helper.rb Normal file
View File

@ -0,0 +1,553 @@
# encoding: utf-8
module ApiHelper
ONE_MINUTE = 60 * 1000
ONE_HOUR = 60 * ONE_MINUTE
ONE_DAY = 24 * ONE_HOUR
ONE_MONTH = 30 * ONE_DAY
ONE_YEAR = 12 * ONE_MONTH
#获取用户的工作单位
def get_user_work_unit user
work_unit = ""
if user.user_extensions.identity == 0 || user.user_extensions.identity == 1
work_unit = user.user_extensions.school.name unless user.user_extensions.school.nil?
elsif user.user_extensions.identity == 3
work_unit = user.user_extensions.occupation
elsif user.user_extensions.identity == 2
work_unit = user.firstname
end
work_unit
end
#获取用户地区
def get_user_location user
location = ""
location << (user.user_extensions.location || '')
location << (user.user_extensions.location_city || '')
location
end
def get_user_realname user
name = user.lastname + user.firstname
name.empty? || name.nil? || name == " " ? user.login : name
end
def get_assigned_homeworks(homeworks, n, index)
homeworks += homeworks
homeworks[index + 1 .. index + n]
end
def stars_to_json_like starts,show_jour,homework,show_real_name
result = []
starts.each do |s|
comment = get_homework_review homework,show_jour,s.rater
rater_name = show_real_name ? s.rater.login : l(:label_anonymous)
rater_id = show_real_name ? s.rater.id : ''
result << {:rater_id =>rater_id ,:rater_name => rater_name,:created_at => format_time(s.created_at),:stars => s.stars,:comment => comment}
end
result
end
#########################################################
#sw
#获取课程未匿评数量
#param: user => "用户", course_id => "查询的课程ID"
#return: 作业的数量
#########################################################
def get_course_anonymous_evaluation user,course
count = 0
if course
is_teacher = is_course_teacher user,course
if is_teacher #如果是老师,显示学生提交的作业数
course.homeworks.each do |bid|
count += bid.homeworks.count
end
else #如果是学生,显示未匿评的数量
course.homeworks.each do |bid|
count += get_student_not_batch_homework_list bid,user
end
end
end
[count,is_teacher]
end
def get_user_language user
(user.language.nil? || user.language == "") ? 'zh':user.language
end
# 学生获取课程作业的状态
def get_homework_status homework
homework_status = ""
if homework
if homework.homework_type == 1 && homework.homework_detail_manual
case homework.homework_detail_manual.comment_status
when 1
homework_status = show_homework_deadline homework
when 2
homework_status = "正在匿评"
when 3
homework_status = "匿评结束"
end
elsif homework.homework_type == 0
homework_status = "未启用匿评"
elsif homework.homework_type == 2
homework_status = "编程作业"
else
end
end
homework_status
end
#获取作业的是否可以匿评的描述
def homework_status_desc homework
if homework.homework_type == 1 && homework.homework_detail_manual #匿评作业
if homework.end_time >= Time.now
link = show_homework_deadline homework
elsif homework.student_works.count >= 2 #作业份数大于2
case homework.homework_detail_manual.comment_status
when 1
link = '启动匿评'
when 2
link = '关闭匿评'
when 3
link = " 匿评结束"
end
else
link = "提交作业数过少"
end
else
link = "未开启匿评作业"
end
link
end
#获取
def get_submit_sutdent_list homework
studentlist = []
if homework.is_a?(Hash) && homework.key?(:studentlist)
studentlist = homework[:studentlist]
else
homework.student_works.order("created_at desc").page(1).per(6).each do |work|
studentlist << work.user
end
end
studentlist
end
#计算作业的截止日期,剩余日期
def show_homework_deadline homework
day = 0
if (day = (Date.parse(homework.end_time.to_s) - Date.parse(Time.now.to_s)).to_i) > 0
"距作业截止还有" << day.to_s << ""
else
"已截止,但可补交"
end
end
#获取作业中学生的匿评比率
# 匿评比率 = 学生总共评价的作业的作业份数 / 作业份数 * 分配数 * 100%
# 教辅匿评比率 = 教辅已经评价的作业份数 / 总的作业份数 * 100%
def get_evaluation_part homework,role
homework_eva_completed_task_num = 0
homework_eva_task_num = 0
#匿评作业 # 且匿评状态不是还没有开启匿评
if homework.homework_type == 1 && homework.homework_detail_manual && homework.homework_detail_manual.comment_status != 1
# 总共需要评价的任务数
homework_eva_task_num = homework.homework_detail_manual.evaluation_num * homework.student_works.count
unless homework_eva_task_num == 0 #总任务数不为0 的情况下
#获取已经评价了多少的份作业 student_work_score里记录了评价情况每条记录有提交作业的id
#先求出提交作业的id集合
work_ids = "(" + homework.student_works.map(&:id).join(",") + ")"
#只要 student_work_score 中的 student_work_id在work_ids集合中那么久说明这个任务被完成了
sql = "select count(1) from student_works_scores where reviewer_role = #{role} and student_work_id in #{work_ids} "
homework_eva_completed_task_num = ActiveRecord::Base.connection().select_value(sql)
end
end
if homework_eva_task_num == 0
0
else
( homework_eva_completed_task_num / homework_eva_task_num.to_f * 100 ) .round(1)
end
end
# 获取当前时间
def time_from_now time
lastUpdateTime = time.to_i*1000
currentTime = Time.now.to_i*1000
timePassed = currentTime - lastUpdateTime
timeIntoFormat = 0
updateAtValue = ""
if timePassed < 0
updateAtValue = "刚刚"
elsif timePassed < ONE_MINUTE
updateAtValue = "1分钟前"
elsif timePassed < ONE_HOUR
timeIntoFormat = timePassed / ONE_MINUTE
updateAtValue = timeIntoFormat.to_s + "分钟前"
elsif (timePassed < ONE_DAY)
timeIntoFormat = timePassed / ONE_HOUR
updateAtValue = timeIntoFormat.to_s + "小时前"
elsif (timePassed < ONE_MONTH)
timeIntoFormat = timePassed / ONE_DAY
updateAtValue = timeIntoFormat.to_s + "天前"
elsif (timePassed < ONE_YEAR)
timeIntoFormat = timePassed / ONE_MONTH
updateAtValue = timeIntoFormat.to_s + "个月前"
else
timeIntoFormat = timePassed / ONE_YEAR
updateAtValue = timeIntoFormat.to_s + "年前"
end
updateAtValue
end
# 获取当前时间
def time_from_future time
lastUpdateTime = time.to_i*1000
currentTime = Time.now.to_i*1000
timePassed = lastUpdateTime - currentTime;
timeIntoFormat = 0
updateAtValue = ""
if timePassed < 0
updateAtValue = "马上"
elsif timePassed < ONE_MINUTE
updateAtValue = "1分钟"
elsif timePassed < ONE_HOUR
timeIntoFormat = timePassed / ONE_MINUTE
updateAtValue = timeIntoFormat.to_s + "分钟"
elsif (timePassed < ONE_DAY)
timeIntoFormat = timePassed / ONE_HOUR
updateAtValue = timeIntoFormat.to_s + "小时"
elsif (timePassed < ONE_MONTH)
timeIntoFormat = timePassed / ONE_DAY
updateAtValue = timeIntoFormat.to_s + ""
elsif (timePassed < ONE_YEAR)
timeIntoFormat = timePassed / ONE_MONTH
updateAtValue = timeIntoFormat.to_s + "个月"
else
timeIntoFormat = timePassed / ONE_YEAR
updateAtValue = timeIntoFormat.to_s + ""
end
updateAtValue
end
# 计算到结束还有多长时间 **天**小时**分
def how_much_time time
result = ""
result = ((time - Time.now.to_i).to_i / (24*60*60)).to_s + ""
result += (((time - Time.now.to_i).to_i % (24*60*60)) / (60*60)).to_s + " 小时 "
result += ((((time - Time.now.to_i).to_i % (24*60*60)) % (60*60)) / 60).to_s + ""
end
#日期转换为时间
def convert_to_time date, num
if num == 0
date = date.to_s + " 00:00"
elsif num == 1
date = date.to_s + " 23:59"
end
return date
end
#获取用户
def get_user user_id
user = User.find user_id
user
end
#获取项目
def get_project project_id
project = Project.find project_id
project
end
#获取课程
def get_course course_id
course = Course.find course_id
course
end
#获取点赞数
def get_activity_praise_num(object)
obj_type = object.class
obj_id = object.id
record = PraiseTreadCache.find_by_object_id_and_object_type(obj_id,obj_type)
if record
return ((record.praise_num.nil? ? 0 : record.praise_num.to_i)-(record.tread_num.nil? ? 0 : record.tread_num.to_i))
else
return 0
end
end
#获取缺陷的优先级
def get_issue_priority_api value
issuetype = ""
if value == 4
issuetype = "紧急"
elsif value == 2
issuetype = "正常"
elsif value == 3
issuetype = ""
elsif value == 1
issuetype = ""
else
issuetype = "立刻"
end
end
def jdetails_to_strings(details, no_html=false, options={})
options[:only_path] = (options[:only_path] == false ? false : true)
options[:token] = options[:token] if options[:token]
strings = []
values_by_field = {}
details.each do |detail|
if detail.property == 'cf'
field_id = detail.prop_key
field = CustomField.find_by_id(field_id)
if field && field.multiple?
values_by_field[field_id] ||= {:added => [], :deleted => []}
if detail.old_value
values_by_field[field_id][:deleted] << detail.old_value
end
if detail.value
values_by_field[field_id][:added] << detail.value
end
next
end
end
strings << jshow_detail(detail, no_html, options)
end
values_by_field.each do |field_id, changes|
detail = JournalDetail.new(:property => 'cf', :prop_key => field_id)
if changes[:added].any?
detail.value = changes[:added]
strings << jshow_detail(detail, no_html, options)
elsif changes[:deleted].any?
detail.old_value = changes[:deleted]
strings << jshow_detail(detail, no_html, options)
end
end
strings
end
# Returns the textual representation of a single journal detail
def jshow_detail(detail, no_html=false, options={})
multiple = false
case detail.property
when 'attr'
field = detail.prop_key.to_s.gsub(/\_id$/, "")
label = l(("field_" + field).to_sym)
case detail.prop_key
when 'due_date', 'start_date'
value = format_date(detail.value.to_date) if detail.value
old_value = format_date(detail.old_value.to_date) if detail.old_value
when 'project_id', 'status_id', 'tracker_id', 'assigned_to_id',
'priority_id', 'category_id', 'fixed_version_id'
value = find_name_by_reflection(field, detail.value)
old_value = find_name_by_reflection(field, detail.old_value)
when 'estimated_hours'
value = "%0.02f" % detail.value.to_f unless detail.value.blank?
old_value = "%0.02f" % detail.old_value.to_f unless detail.old_value.blank?
when 'parent_id'
label = l(:field_parent_issue)
value = "##{detail.value}" unless detail.value.blank?
old_value = "##{detail.old_value}" unless detail.old_value.blank?
when 'is_private'
value = l(detail.value == "0" ? :general_text_No : :general_text_Yes) unless detail.value.blank?
old_value = l(detail.old_value == "0" ? :general_text_No : :general_text_Yes) unless detail.old_value.blank?
end
when 'cf'
custom_field = CustomField.find_by_id(detail.prop_key)
if custom_field
multiple = custom_field.multiple?
label = custom_field.name
value = format_value(detail.value, custom_field.field_format) if detail.value
old_value = format_value(detail.old_value, custom_field.field_format) if detail.old_value
end
when 'attachment'
label = l(:label_attachment)
end
call_hook(:helper_issues_show_detail_after_setting,
{:detail => detail, :label => label, :value => value, :old_value => old_value })
label ||= detail.prop_key
value ||= detail.value
old_value ||= detail.old_value
unless no_html
label = content_tag('strong', label)
old_value = content_tag("i", old_value) if detail.old_value
old_value = content_tag("del", old_value) if detail.old_value and detail.value.blank?
if detail.property == 'attachment' && !value.blank? && atta = Attachment.find_by_id(detail.prop_key)
# Link to the attachment if it has not been removed
if options[:token].nil?
value = atta.filename
else
value = atta.filename
end
# 放大镜搜索功能
# if options[:only_path] != false && atta.is_text?
# value += link_to(
# image_tag('magnifier.png'),
# :controller => 'attachments', :action => 'show',
# :id => atta, :filename => atta.filename
# )
# end
else
value = content_tag("i", value) if value
end
end
# 缺陷更新结果在消息中显示样式
if no_html == "message"
label = content_tag(:span, label, :class => "issue_update_message")
old_value = content_tag("span", old_value) if detail.old_value
old_value = content_tag("del", old_value) if detail.old_value and detail.value.blank?
if detail.property == 'attachment' && !value.blank? && atta = Attachment.find_by_id(detail.prop_key)
# Link to the attachment if it has not been removed
if options[:token].nil?
value = atta.filename
else
value = atta.filename
end
else
value = content_tag(:span, value, :class => "issue_update_message_value") if value
end
end
if detail.property == 'attr' && detail.prop_key == 'description'
s = l(:text_journal_changed_no_detail, :label => label)
unless no_html
diff_link = link_to l(:label_diff),
{:controller => 'journals', :action => 'diff', :id => detail.journal_id,
:detail_id => detail.id, :only_path => options[:only_path]},
:title => l(:label_view_diff)
s << " (#{ diff_link })"
end
s.html_safe
elsif detail.value.present?
case detail.property
when 'attr', 'cf'
if detail.old_value.present?
l(:text_journal_changed, :label => label, :old => old_value, :new => value).html_safe
elsif multiple
l(:text_journal_added, :label => label, :value => value).html_safe
else
l(:text_journal_set_to, :label => label, :value => value).html_safe
end
when 'attachment'
l(:text_journal_added, :label => label, :value => value).html_safe
end
else
l(:text_journal_deleted, :label => label, :old => old_value).html_safe
end
end
#课程动态的更新
def update_course_activity_api type, id
course_activity = CourseActivity.where("course_act_type=? and course_act_id =?", type.to_s, id.to_i).first
if course_activity
course_activity.updated_at = Time.now
course_activity.save
end
end
#首页动态更新
def update_user_activity_api type, id
user_activity = UserActivity.where("act_type=? and act_id =?", type.to_s, id.to_i).first
if user_activity
user_activity.updated_at = Time.now
user_activity.save
end
end
#项目动态更新
def update_forge_activity_api type, id
forge_activity = ForgeActivity.where("forge_act_type=? and forge_act_id=?", type.to_s, id.to_i).first
if forge_activity
forge_activity.updated_at = Time.now
forge_activity.save
end
end
#组织动态更新
def update_org_activity_api type , id
org_activity = OrgActivity.where("org_act_type=? and org_act_id =?", type.to_s, id.to_i).first
if org_activity
org_activity.updated_at = Time.now
org_activity.save
end
end
#个人动态更新
def update_principal_activity_api type, id
principal_activity = PrincipalActivity.where("principal_act_type=? and principal_act_id =?", type.to_s, id.to_i).first
if principal_activity
principal_activity.updated_at = Time.now
principal_activity.save
end
end
#赞/取消赞
def praise_or_cancel(type,id,user,flag)
unless id.nil? and type.nil?
#首先创建或更新praise_tread 表
pt = PraiseTread.new
pt.user_id = user.id
pt.praise_tread_object_id = id.to_i
pt.praise_tread_object_type = type
pt.praise_or_tread = flag
pt.save
# end
#再创建或更新praise_tread_cache表
#@ptc = PraiseTreadCache.find_by_object_id_and_object_type(id,type)
ptc = PraiseTreadCache.where("object_id = ? and object_type = ?",id.to_i,type).first
ptc = ptc.nil? ? PraiseTreadCache.new : ptc
ptc.object_id = id.to_i
ptc.object_type = type
ptc.save
ptc.praise_plus(flag,1)
end
end
def praise_plus(flag,num)
case flag
when 1
self.update_attribute(:praise_num, self.praise_num.to_i + num)
end
end
def praise_minus(num)
self.update_attribute(:praise_num, self.praise_num.to_i - num)
end
class Errors
def self.define_error(arr)
@errors = {}
arr.each_with_index { |item, index|
if index %2 == 1
@errors[arr[index-1]] = item
end
}
if arr.count % 2== 1
@default_error = arr.last
else
@default_error = "未知错误"
end
end
def self.message(msg_id)
@errors[msg_id] || @default_error
end
end
end

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