Skip to content

Commit

Permalink
公共模板允许同时退订多个仓库
Browse files Browse the repository at this point in the history
  • Loading branch information
a76yyyy committed Oct 17, 2021
1 parent 247b047 commit 93b06ae
Show file tree
Hide file tree
Showing 6 changed files with 261 additions and 51 deletions.
82 changes: 59 additions & 23 deletions web/handlers/subscribe.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ def post(self, userid):
else:
tmp.append(env)
repos['repos'] = tmp
repos["lastupdate"] = 0
self.db.site.mod(1, repos=json.dumps(repos, ensure_ascii=False, indent=4))
else:
raise Exception('仓库名/url/分支不能为空')
Expand All @@ -203,10 +204,50 @@ def post(self, userid):
self.render('utils_run_result.html', log=str(e), title=u'设置失败', flg='danger')
return

self.render('utils_run_result.html', log=u'设置成功,请手动刷新页面查看', title=u'设置成功', flg='success')
self.render('utils_run_result.html', log=u'设置成功,请关闭操作对话框或刷新页面查看', title=u'设置成功', flg='success')
return

class GetReposInfoHandler(BaseHandler):
@tornado.web.authenticated
def post(self, userid):
try:
user = self.current_user
if (user['id'] == int(userid)) and (user['role'] == u'admin'):
envs = {}
for key in self.request.body_arguments:
envs[key] = self.get_body_arguments(key)
tmp = json.loads(self.db.site.get(1, fields=('repos'))['repos'])['repos']
repos = []
for repoid, selected in envs.items():
if isinstance(selected[0],bytes):
selected[0] = selected[0].decode()
if (selected[0] == 'true'):
repos.append(tmp[int(repoid)])
else:
raise Exception('非管理员用户,不可查看')
except Exception as e:
traceback.print_exc()
self.render('utils_run_result.html', log=str(e), title=u'获取信息失败', flg='danger')
return

self.render('pubtpl_reposinfo.html', repos=repos)
return

class unsubscribe_repos_Handler(BaseHandler):
@tornado.web.authenticated
def get(self, userid):
try:
user = self.current_user
if (user['id'] == int(userid)) and (user['role'] == u'admin'):
self.render('pubtpl_unsubscribe.html', user=user)
else:
raise Exception('非管理员用户,不可设置')
return
except Exception as e:
traceback.print_exc()
self.render('utils_run_result.html', log=str(e), title=u'打开失败', flg='danger')
return

@tornado.web.authenticated
def post(self, userid):
try:
Expand All @@ -217,29 +258,23 @@ def post(self, userid):
envs[key] = self.get_body_arguments(key)
env = {}
for k, v in envs.items():
env[k] = v[0]

if (env['reponame'] != ''):
repos = json.loads(self.db.site.get(1, fields=('repos'))['repos'])
tmp = repos['repos']
inflg = False
repoindex = 99
try:
env[k] = json.loads(v[0])
except:
env[k] = v[0]
repos = json.loads(self.db.site.get(1, fields=('repos'))['repos'])
tmp = repos['repos']
result = []
for i, j in enumerate(tmp):
# 检查是否存在同名仓库
for i in range(0, len(tmp)):
if tmp[i]['reponame'] == env['reponame']:
repoindex = i
del tmp[repoindex]
repos['repos'] = tmp
pubtpls = self.db.pubtpl.list(reponame=env['reponame'], fields=('id'))
for pubtpl in pubtpls:
self.db.pubtpl.delete(pubtpl['id'])
self.db.site.mod(1, repos=json.dumps(repos, ensure_ascii=False, indent=4))
break
if not env['selectedrepos'].get(str(i),False) :
result.append(j)
else:
raise Exception('不存在此仓库')

else:
raise Exception('仓库名不能为空')
pubtpls = self.db.pubtpl.list(reponame=j['reponame'], fields=('id'))
for pubtpl in pubtpls:
self.db.pubtpl.delete(pubtpl['id'])
repos['repos'] = result
self.db.site.mod(1, repos=json.dumps(repos, ensure_ascii=False, indent=4))
else:
raise Exception('非管理员用户,不可设置')

Expand All @@ -248,14 +283,15 @@ def post(self, userid):
self.render('utils_run_result.html', log=str(e), title=u'设置失败', flg='danger')
return

self.render('utils_run_result.html', log=u'设置成功,请手动刷新页面查看', title=u'设置成功', flg='success')
self.render('utils_run_result.html', log=u'设置成功,请关闭操作对话框或刷新页面查看', title=u'设置成功', flg='success')
return

handlers = [
('/subscribe/(\d+)/', SubscribeHandler),
('/subscribe/(\d+)/updating/', SubscribeUpdatingHandler),
('/subscribe/refresh/(\d+)/', SubscribeRefreshHandler),
('/subscribe/signup_repos/(\d+)/', Subscrib_signup_repos_Handler),
('/subscribe/(\d+)/get_reposinfo', GetReposInfoHandler),
('/subscribe/unsubscribe_repos/(\d+)/', unsubscribe_repos_Handler),
]

6 changes: 5 additions & 1 deletion web/tpl/pubtpl_register.html
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ <h2 class="text-center">注册仓库</h2>

return false;
});
})
$('#modal_load').on('hide.bs.modal',
function () {
location.reload();
})
});
</script>
</form>
18 changes: 18 additions & 0 deletions web/tpl/pubtpl_reposinfo.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<table class="table table-hover">
<thead>
<tr>
<th style="text-align:center" title="仓库名">仓库名</th>
<th style="text-align:center" title="仓库分支">仓库分支</th>
</tr>
</thead>
<tbody>
{% for repo in repos %}
<tr>
<td style="text-align:center">
<a href="{{ repo.repourl }}" target="_blank" rel="noopener noreferrer">{{ repo.reponame }}</a>
</td>
<td style="text-align:center">{{ repo.repobranch }}</td>
</tr>
{% endfor %}
</tbody>
</table>
134 changes: 108 additions & 26 deletions web/tpl/pubtpl_subscribe.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,17 @@ <h2>
<span type="span" class="btn btn-default">
<a data-load-method="GET" class="modal_load" href="/subscribe/signup_repos/{{userid}}/" title="注册模板仓库">注册</a>
</span>
<span type="span" class="btn btn-default">
<a data-load-method="GET" class="modal_load" href="/subscribe/unsubscribe_repos/{{userid}}/" title="取消注册此仓库">退订</a>
</span>
{% endif %}
</h2>
<table class="table table-hover">
<thead>
<tr>
{% if adminflg %}
<th style="text-align:center" title="仓库操作区">操作</th>
<th style="text-align:center" title="操作">操作</th>
<th style="text-align:center" title="仓库序号">序号</th>
{% endif %}
<th style="text-align:center" title="注册的仓库名">仓库名</th>
<th style="text-align:center" title="注册的仓库连接">链接</th>
Expand All @@ -38,12 +42,15 @@ <h2>
<tr>
{% if adminflg %}
<td style="text-align:center">
{% if repo.reponame != 'default'%}
<div class="btn-group btn-group-xs" role="group" aria-label="...">
<button type="button" class="btn btn-default btn-sm" name="unsubscribe_{{repo.reponame}}" title="取消注册此仓库" onclick="unsubscribe_repo('{{repo.reponame}}')">退订</input>
</div>
{% if repo.reponame == 'default'%}
<input type="checkbox" name="{{loop.index0}}" class="Repo checkbox" style="display: inline; min-height: unset;" disabled=true>
{% else %}
<input type="checkbox" name="{{loop.index0}}" class="Repo checkbox" style="display: inline; min-height: unset;" onclick="repoNode.toggle(this)">
{% endif %}
</td>
<td style="text-align:center">
{{loop.index0}}
</td>
{% endif %}
<td style="text-align:center">{{ repo.reponame }}</td>
<td style="text-align:center">
Expand Down Expand Up @@ -118,27 +125,102 @@ <h2>
})
</script>
<script>
function unsubscribe_repo(name) {
data = {
reponame: name
}
$.ajax("/subscribe/unsubscribe_repos/{{userid}}/", {
type: 'POST',
data: data,
})
.done(function(data) {
$('#error-msg').html(data).show()

})
.fail(function(jxhr) {
$('#error-msg').html('<h1 class="alert alert-danger text-center">设置失败</h1><div class="well"></div>').show().find('div').text(jxhr.responseText);
})
.always(function() {
$this.button('reset');
});

return false;
}
const repoNode = {
selectedRepoNodesJSON: '{}',

get selectedRepoNodes() {
return this.getSelectedRepoNodes()
},

set selectedRepoNodes(val) {
this.setSelectedRepoNodes(val)
},

getSelectedRepoNodes: function(){
if(this.selectedRepoNodesJSON == '{}'){
if (typeof(sessionStorage.selectedrepo) != "undefined"){
this.selectedRepoNodesJSON = sessionStorage.selectedrepo
}
}
return JSON.parse(this.selectedRepoNodesJSON)
},

setSelectedRepoNodes: function(val){
this.selectedRepoNodesJSON = JSON.stringify(val)
sessionStorage.selectedrepo=JSON.stringify(val)
},

toggle: function(repoNode, uncheck) {
let _selectedRepoNodes = this.selectedRepoNodes
_selectedRepoNodes[repoNode.name] =repoNode.checked
this.selectedRepoNodes = _selectedRepoNodes
if(!uncheck) {
(typeof setRepoGroupChecked == 'function') && setRepoGroupChecked(repoNode.className)
}
},


init: function() {
let _selectedRepoNodes = this.selectedRepoNodes
let _classNames= {}
for (let key in _selectedRepoNodes){
let reponodes = document.getElementsByName(key);
if (reponodes.length > 0){
reponodes[0].checked = _selectedRepoNodes[key]
// 将已选中的reponode的className 存储在_classNames中
if(_selectedRepoNodes[key]) {
_classNames[reponodes[0].className] = true
}
}
}

for(let key in _classNames){
(typeof setRepoGroupChecked == 'function') && setRepoGroupChecked(key)
}
}

}

/**
* 修改全选按钮样式
* 在repoNode.init()之前加载
*
**/
function setRepoGroupChecked(className){
let _eles = document.getElementsByName(className)
let _nodeGroupChecked
for(let i=0; i<_eles.length; i++) {
if(_eles[i].nodeName.toLowerCase() == 'input' &&
_eles[i].getAttribute('type') == 'checkbox'
){
_nodeGroupChecked = _eles[i]
}
}
if(typeof _nodeGroupChecked == 'undefined') return;
let _checkedNum = 0
const _repoNodes = document.getElementsByClassName(className)

for(key in _repoNodes) {
if(_repoNodes[key].checked == true) {
_checkedNum++
}
}

if(_checkedNum == _repoNodes.length) {
_nodeGroupChecked.indeterminate = false;
_nodeGroupChecked.checked = true;
}else if(_checkedNum > 0) {
_nodeGroupChecked.indeterminate = true;
_nodeGroupChecked.checked = false;
}else {
_nodeGroupChecked.indeterminate = false;
_nodeGroupChecked.checked = false;
}
}

// 页面加载后初始化
repoNode.init()

</script>
{% endif %}

Expand Down
70 changes: 70 additions & 0 deletions web/tpl/pubtpl_unsubscribe.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<form method="POST" action="/subscribe/unsubscribe_repos/{{userid}}/">
<h2 class="text-center">退订仓库</h2>
<hr>
<div id="run-result"></div>
<script>
var selectedrepos = {};
debugger
if (typeof (sessionStorage.selectedrepo) != "undefined") {
selectedrepos = JSON.parse(sessionStorage['selectedrepo'])
NProgress.start();
NProgress.inc();
$.ajax("/subscribe/{{user.id}}/get_reposinfo", {
type: 'POST',
data: selectedrepos,
})
.done(function (data) {
$('#repotable').html(data).show()
})
.fail(function (jxhr) {
$('#run-result').html('<h1 class="alert alert-danger text-center">设置失败</h1><div class="well"></div>').show().find('div').text(jxhr.responseText);
})
.always(function () { NProgress.done(); })
} else {
$('#run-result').html('<h1 class="alert alert-danger text-center">FAIL</h1><div class="well"></div>').show().find('div').text('请选择要退订的仓库');
}
</script>
{% if current_user %}
<div id="repotable"></div>
<div class="text-right">
<button id="unsubscribe" name="unsubscribe" type="button" data-loading-text="loading..."
class="btn btn-primary">退订</button>
</div>
<script>
$(function () {
$('#unsubscribe').on('click', function () {
NProgress.start();
data = {
selectedrepos: JSON.stringify(selectedrepos)
}
var $this = $(this);
$this.button('loading');
NProgress.inc();
$.ajax("/subscribe/unsubscribe_repos/{{user.id}}/", {
type: 'POST',
data: data,
})
.done(function (data) {
$('#run-result').html(data).show()
})
.fail(function (jxhr) {
$('#run-result').html('<h1 class="alert alert-danger text-center">设置失败</h1><div class="well"></div>').show().find('div').text(jxhr.responseText);
})
.always(function () {
$this.button('reset');
NProgress.inc();
if (typeof (sessionStorage.selectedrepo) != "undefined") {
sessionStorage.removeItem('selectedrepo')
}
});
NProgress.done();
return false;
});
$('#modal_load').on('hide.bs.modal',
function () {
location.reload();
})
});
</script>
{% endif %}
</form>
2 changes: 1 addition & 1 deletion worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def run(self):
failed += 1
except Exception as e:
logging.exception(e)
raise gen.Return((success, failed))
return (success, failed)

scan_fields = ('id', 'tplid', 'userid', 'init_env', 'env', 'session', 'retry_count', 'retry_interval', 'last_success', 'last_failed', 'success_count', 'failed_count', 'last_failed_count', 'next', 'disabled', )
def scan(self):
Expand Down

0 comments on commit 93b06ae

Please sign in to comment.