-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgitlab2dingsvr.py
690 lines (619 loc) · 40.9 KB
/
gitlab2dingsvr.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
#!/usr/bin/env python
#--coding:utf-8--
from http.server import BaseHTTPRequestHandler, HTTPServer
from os import path
from urllib.parse import urlparse
import urllib
from urllib import request,parse
from time import localtime, strftime
import json,configparser,sqlite3,os
config = configparser.ConfigParser()
config.read("config.ini")
def log(log_str):
timestamp = strftime("[%d/%b/%Y %H:%M:%S]", localtime())
print(timestamp + log_str)
def read_list_from_db(list_type_str):
sqconn = sqlite3.connect('gitlab2ding.db')
sqc = sqconn.cursor()
if list_type_str == "git_members":
user_list_tuple = sqc.execute("SELECT GITEMAIL,DINGUID FROM USERS")
elif list_type_str == "lab_members":
user_list_tuple = sqc.execute("SELECT GITLABUSERNAME,DINGUID FROM USERS")
elif list_type_str == "ding_user_list":
user_list_tuple = sqc.execute("SELECT PHONE,DINGUID FROM USERS WHERE GITLABUSERNAME IS NULL")
db_list_dict = {}
db_user = user_list_tuple.fetchone()
while db_user!=None:
if db_user[0]!=None:
db_list_dict[db_user[0]] = db_user[1]
db_user = user_list_tuple.fetchone()
sqconn.close()
log(list_type_str+" updated from sqlite db")
return db_list_dict
# some start up work
try:
os.system("python3 labFetchUser.py")
except:
log("labFetchUser fail")
else:
log("labFetchUser success")
git_members = read_list_from_db("git_members")
lab_members = read_list_from_db("lab_members")
print(git_members)
print(lab_members)
AgentID = config["config"]["agentid"]
port = int(config["config"]["port"])
debug = config["config"]["debug"]
debuger = config["config"]["debuger"]
# debug 0 :normal
# 1 :send to user and debuger
# 2 :send to debuger only
corpid = config["config"]["corpid"]
corpsecret = config["config"]["corpsecret"]
gitlabtoken = config["config"]["gitlabtoken"]
gitlaburl = config["config"]["gitlaburl"]
webhookurl = config["config"]["webhookurl"]
# start up finish
def sqlite_linkuser_add(phone_str,value_str,key_str):
sqconn = sqlite3.connect('gitlab2ding.db')
sqc = sqconn.cursor()
sqc.execute("SELECT PHONE FROM USERS")
try:
sqc.execute("UPDATE USERS set "+key_str+" = '"+value_str+"' where PHONE='"+phone_str+"'")
except :
log( "sqlite_linkuser_add fail:"+phone_str+";"+value_str+";"+key_str)
sqconn.commit()
sqconn.close()
else:
log( "sqlite_linkuser_add success:"+phone_str+";"+value_str+";"+key_str)
sqconn.commit()
sqconn.close()
def labuid2username(uid_str):
req_labid2username = request.Request(gitlaburl+"/api/v4/users/"+uid_str+"?private_token="+gitlabtoken)
data_from_lab = request.urlopen(req_labid2username).read()
data_for_username = json.loads(data_from_lab.decode("utf-8"))
username = data_for_username["username"]
return username
def receiverSort(receiver_list):
receiver_str = ""
if len(receiver_list) > 0 :
for receiver in receiver_list :
receiver_str=receiver_str + "|" + receiver
else:
return ""
if (receiver_str[0]=="|"):
receiver_str = receiver_str[1:]
if (debug == "1" ):
log( "[debug]receiver_str:" + receiver_str)
receiver_str = receiver_str+ "|" + debuger
if (debug == "2" ):
log( "[debug]receiver_str:" + receiver_str)
receiver_str = debuger
return receiver_str
def searchAt(receiver_list,content_str):
content_dict = content_str.split("@")
for content in content_dict:
i=0
for c in content:
if (ord(c)>=65 and ord(c)<=90) or (ord(c)>=97 and ord(c)<=122):
i=i+1
else:
break
for key in lab_members.keys():
if (i>0 and content[:i]==key):
receiver_list.append(lab_members[key])#to at
log("at "+key+" get.")
break
return receiver_list
class gitlab2dingsvr_RequestHandler(BaseHTTPRequestHandler):
# GET
def do_POST(self):
timestamp = strftime("[%d/%b/%Y %H:%M:%S]", localtime())
querypath = urlparse(self.path)
filepath, query = querypath.path, querypath.query
data_b = self.rfile.read(int(self.headers['content-length']))
self.send_response(200)
self.send_header('Content-type',"None")
self.end_headers()
data_s = data_b.decode("utf-8")
data_json = json.loads(data_s)
receiver_dingUid = []
send_valid=0;
if "event_name" in data_json:
'''
■
■
■■■ ■ ■ ■■■■■ ■■■
■ ■ ■ ■ ■ ■ ■■
■ ■ ■ ■ ■ ■
■■■■ ■ ■ ■ ■ ■
■ ■ ■ ■■ ■ ■ ■■
■■■■■ ■■■ ■ ■■■ ■■■
■ ■ ■
■ ■ ■
■ ■ ■
■ ■ ■ ■■■ ■■■■ ■■■■ ■■■ ■■■ ■ ■
■ ■■ ■ ■ ■■ ■ ■ ■■ ■■ ■ ■■ ■ ■■ ■ ■
■■■ ■ ■■■■■ ■ ■ ■ ■ ■ ■ ■ ■ ■■■
■■ ■■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■■
■■ ■ ■ ■■ ■ ■ ■ ■ ■ ■■ ■ ■■ ■ ■
■ ■ ■■■ ■■■■ ■ ■ ■■■ ■■■ ■ ■
'''
if data_json['event_name']=="project_create":
new_project_id_str = str(data_json["project_id"])
log( "new project:"+data_json["path_with_namespace"]+"(id:"+new_project_id_str+"), adding webhook")
addHook_json_str = (
"{\"id\":"+new_project_id_str+",\"url\": \""+webhookurl+"\" ,"
"\"push_events\" : 1 ,"
"\"issues_events\" : 1 ,"
"\"confidential_issues_events\" : 1, "
"\"merge_requests_events\" : 1, "
"\"tag_push_events\" : 1, "
"\"note_events\" : 1, "
"\"confidential_note_events\" : 1,"
"\"job_events\" : 1, "
"\"pipeline_events\" : 1, "
"\"wiki_page_events\" : 1, "
"\"enable_ssl_verification\" : 1 }"
)
addHook_json_str_b = addHook_json_str.encode('utf-8')
url = gitlaburl+"/api/v4/projects/"+new_project_id_str+"/hooks"
headersAddhook = {"Private-Token": gitlabtoken ,"Content-Type":"application/json"}
req_addhook = request.Request(url, data=addHook_json_str_b,headers=headersAddhook, method="POST")
data_from_addhook_req = request.urlopen(req_addhook).read()
log( data_from_addhook_req.decode('utf_8'))
elif "object_kind" in data_json:
'''
■
■■ ■ ■■
■■ ■ ■■
■
■ ■■■ ■ ■ ■■■ ■■■ ■ ■ ■ ■■■ ■■■
■■ ■■ ■ ■■ ■■ ■ ■ ■ ■ ■■ ■■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■■■■■ ■ ■ ■ ■ ■■■■■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■■ ■ ■ ■■ ■ ■■ ■ ■ ■ ■ ■ ■■ ■
■ ■■■ ■ ■ ■■■ ■■■ ■ ■ ■ ■ ■■■
■ ■
■ ■
■ ■
pipeline object
to: commit(according to commit email)
'''
if (data_json['object_kind'] == "pipeline"):
send_valid = 1
log( "pipeline trigger received")
if data_json['commit']['author']['email'] in git_members:
receiver_dingUid.append(git_members[data_json['commit']['author']['email']])
log( "committer email:" + data_json['commit']['author']['email'] + " found")
status = data_json['object_attributes']['status']
commit_msg = data_json['commit']['message']
object_id = str(data_json['object_attributes']['id'])
log(data_json["project"]["web_url"]+"/pipelines/"+object_id)
project_name = data_json['project']['name']
if len(receiver_dingUid)==0 :
send_valid = 0
else:
receiver_dingUid_str = receiverSort(receiver_dingUid)
msg2dingapi_json_str=(
"{\"touser\": \""+receiver_dingUid_str+"\", \"agentid\": \""+AgentID+"\","
"\"msgtype\": \"markdown\","
"\"markdown\": {\"title\": \"最近提交的CI状态变化\","
"\"text\": \"## 最近提交的CI状态变化为"+status+" \\n"
"### 项目:"+project_name.replace("\"","\\\"")+" \\n"
"### 提交备注:"+commit_msg.replace("\"","\\\"")+" \\n"
"[点击查看]("+data_json["project"]["web_url"]+"/pipelines/"+object_id+")"+timestamp+"\"} }"
)
msg2dingapi_b = msg2dingapi_json_str.encode('utf-8')
'''
■■
■■
■ ■■ ■■ ■ ■ ■■■
■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■
■ ■■ ■■ ■ ■ ■■■■■
■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■■ ■■ ■■ ■
■ ■■ ■■ ■■■ ■ ■■■
issue object: create, at, edit
msg to: author, at, assignee(according to lab username)
'''
elif (data_json['object_kind'] == "issue"):
send_valid=1;
log( "issue trigger received")
if("assignees" in data_json):
if("username" in data_json["assignees"][0]):
if(data_json["assignees"][0]["username"] in lab_members):
receiver_dingUid.append(lab_members[data_json["assignees"][0]["username"]])#to assignee
log("assignee "+data_json["assignees"][0]["username"]+" get.")
issue_url = data_json["object_attributes"]["url"]
log(issue_url)
issue_title = data_json["object_attributes"]["title"]
issue_id = str(data_json["object_attributes"]["iid"])
issue_content = data_json['object_attributes']['description']
if issue_content != None:
receiver_dingUid = searchAt(receiver_dingUid,issue_content)
project_name = data_json['project']['name']
if len(receiver_dingUid)==0 :
send_valid = 0
else:
receiver_dingUid_str = receiverSort(receiver_dingUid)
msg2dingapi_json_str=(
"{\"touser\": \""+receiver_dingUid_str+"\", \"agentid\": \""+AgentID+"\","
"\"msgtype\": \"markdown\","
"\"markdown\": {\"title\": \"issue#"+issue_id+"通知\","
"\"text\": \"## 和你相关的issue#"+issue_id+"通知 \\n"
"### 项目:"+project_name.replace("\"","\\\"")+" \\n"
"### 标题:"+issue_title.replace("\"","\\\"")+" \\n"
"[点击查看]("+issue_url+")"+timestamp+"\"} }"
)
msg2dingapi_b = msg2dingapi_json_str.encode('utf-8')
'''
■■ ■ ■■■■■
■■■ ■■ ■ ■■
■ ■ ■■ ■ ■
■ ■■ ■ ■ ■■■ ■ ■■ ■■ ■ ■■■ ■ ■ ■■■ ■■■■
■ ■■ ■ ■ ■ ■ ■■ ■ ■■ ■ ■ ■ ■ ■ ■ ■ ■■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■■■■ ■ ■ ■ ■
■ ■■ ■ ■ ■■■■■ ■ ■ ■ ■■■■■ ■ ■ ■■■■■ ■ ■
■ ■■■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■■■ ■ ■■ ■ ■ ■■ ■■ ■■ ■ ■ ■■ ■■ ■ ■■ ■■
■ ■ ■ ■■■ ■ ■■■ ■ ■■■ ■ ■■ ■■■ ■■■ ■
■ ■
■ ■ ■
■■■ ■
merge request object: create, at, edit
msg to: author, at, assignee(according to lab username)
'''
elif (data_json['object_kind'] == "merge_request"):
send_valid=1;
log( data_json['object_kind']+" trigger received")
if("assignee" in data_json):
if("username" in data_json["assignee"]):
if(data_json["assignee"]["username"] in lab_members):
receiver_dingUid.append(lab_members[data_json["assignee"]["username"]])#to assignee
log("assignee "+data_json["assignee"]["username"]+" get.")
object_url = data_json["object_attributes"]["url"]
log(object_url)
merge_req_title = data_json["object_attributes"]["title"]
merge_req_id = str(data_json["object_attributes"]["iid"])
merge_req_content = data_json['object_attributes']['description']
if merge_req_content != None:
receiver_dingUid = searchAt(receiver_dingUid,merge_req_content)
project_name = data_json['project']['name']
if len(receiver_dingUid)==0 :
send_valid = 0
else:
receiver_dingUid_str = receiverSort(receiver_dingUid)
msg2dingapi_json_str=(
"{\"touser\": \""+receiver_dingUid_str+"\", \"agentid\": \""+AgentID+"\","
"\"msgtype\": \"markdown\","
"\"markdown\": {\"title\": \"MergeRequest#"+merge_req_id+"通知\","
"\"text\": \"## 和你相关的MergeRequest#"+merge_req_id+"通知 \\n"
"### 项目:"+project_name.replace("\"","\\\"")+" \\n"
"### 标题:"+merge_req_title.replace("\"","\\\"")+" \\n"
"[点击查看]("+object_url+")"+timestamp+"\"} }"
)
msg2dingapi_b = msg2dingapi_json_str.encode('utf-8')
'''
■■
■■ ■
■
■ ■■ ■■ ■ ■ ■■■ ■■ ■■■■ ■ ■■ ■■■ ■ ■■ ■■■ ■■■ ■ ■■■ ■■■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■■ ■■ ■■ ■■ ■■ ■■ ■■ ■ ■ ■■ ■■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■■ ■■ ■ ■ ■■■■■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■■■■■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■■ ■■ ■■ ■ ■ ■ ■■ ■ ■ ■ ■ ■ ■ ■ ■■ ■ ■ ■ ■
■ ■■ ■■ ■■■ ■ ■■■ ■■ ■■■■ ■ ■ ■ ■ ■ ■ ■■■ ■ ■ ■
issue comment object: new comment, at, edit
msg to: comment author, at and assignee
'''
elif (data_json['object_kind'] == "note") and (data_json['object_attributes']['noteable_type'] == "Issue") :
send_valid=1;
log( data_json['object_attributes']['noteable_type'] +" comment trigger received")
comment_url = data_json["object_attributes"]["url"]
log(comment_url)
comment_content = data_json['object_attributes']['note']
if comment_content != None:
receiver_dingUid = searchAt(receiver_dingUid,comment_content)
# content above are same in object kind NOTE (comment)
issue_author_id = str(data_json["issue"]["author_id"])
issue_author = labuid2username(issue_author_id)
if(issue_author in lab_members):
receiver_dingUid.append(lab_members[issue_author])
log("issue author "+issue_author+" get.")
if data_json["issue"]["assignee_id"] != None :
issue_assignee_id = str(data_json["issue"]["assignee_id"])
issue_assignee = labuid2username(issue_assignee_id)
if(issue_assignee in lab_members):
receiver_dingUid.append(lab_members[issue_assignee])
log("issue assignee "+issue_assignee+" get.")
issue_id = str(data_json["issue"]["iid"])
issue_title = str(data_json["issue"]["title"])
project_name = data_json['project']['name']
if len(receiver_dingUid)==0 :
send_valid = 0
else:
receiver_dingUid_str = receiverSort(receiver_dingUid)
msg2dingapi_json_str=(
"{\"touser\": \""+receiver_dingUid_str+"\", \"agentid\": \""+AgentID+"\","
"\"msgtype\": \"markdown\","
"\"markdown\": {\"title\": \"issue#"+issue_id+"评论通知\","
"\"text\": \"## 和你相关的issue#"+issue_id+"评论 \\n"
"### 项目:"+project_name.replace("\"","\\\"")+" \\n"
"### 标题:"+issue_title.replace("\"","\\\"")+" \\n"
"[点击查看]("+comment_url+")"+timestamp+"\"} }"
)
msg2dingapi_b = msg2dingapi_json_str.encode('utf-8')
'''
■■
■■ ■ ■
■ ■
■■ ■■■■ ■ ■■ ■■■ ■ ■■ ■■■ ■ ■■■■ ■■ ■■■■ ■ ■■ ■■■ ■ ■■ ■■■ ■■■ ■ ■■■ ■■■■
■ ■ ■ ■■ ■■ ■■ ■■ ■■ ■■ ■■ ■ ■ ■ ■ ■ ■■ ■■ ■■ ■■ ■■ ■■ ■■ ■ ■ ■■ ■■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■■■■■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■■ ■ ■ ■ ■ ■ ■ ■ ■■ ■ ■ ■ ■
■■ ■■■■ ■ ■ ■ ■ ■ ■ ■ ■■ ■■ ■■■■ ■ ■ ■ ■ ■ ■ ■■■ ■ ■ ■■
commit comment object: new comment, at, edit
msg to: comment author, at
'''
elif (data_json['object_kind'] == "note") and (data_json['object_attributes']['noteable_type'] == "Commit") :
send_valid=1;
log( data_json['object_attributes']['noteable_type'] +" comment trigger received")
comment_url = data_json["object_attributes"]["url"]
log(comment_url)
comment_content = data_json['object_attributes']['note']
if comment_content != None:
receiver_dingUid = searchAt(receiver_dingUid,comment_content)
# content above are same in object kind NOTE (comment)
commit_author_email = data_json["commit"]["author"]["email"]
if(commit_author_email in git_members):
receiver_dingUid.append(git_members[commit_author_email])
log("commit author "+commit_author_email+" get.")
commit_msg = data_json['commit']['message']
project_name = data_json['project']['name']
if len(receiver_dingUid)==0 :
send_valid = 0
else:
receiver_dingUid_str = receiverSort(receiver_dingUid)
msg2dingapi_json_str=(
"{\"touser\": \""+receiver_dingUid_str+"\", \"agentid\": \""+AgentID+"\","
"\"msgtype\": \"markdown\","
"\"markdown\": {\"title\": \"commit评论通知\","
"\"text\": \"## 和你相关的commit评论 \\n"
"### 项目:"+project_name.replace("\"","\\\"")+" \\n"
"### 提交备注:"+commit_msg.replace("\"","\\\"")+" \\n"
"[点击查看]("+comment_url+")"+timestamp+"\"} }"
)
msg2dingapi_b = msg2dingapi_json_str.encode('utf-8')
'''
■■ ■ ■■■■■
■■■ ■■ ■ ■■
■ ■ ■■ ■ ■
■ ■■ ■ ■ ■■■ ■ ■■ ■■ ■ ■■■ ■ ■ ■■■ ■■■■
■ ■■ ■ ■ ■ ■ ■■ ■ ■■ ■ ■ ■ ■ ■ ■ ■ ■■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■■■■ ■ ■ ■ ■
■ ■■ ■ ■ ■■■■■ ■ ■ ■ ■■■■■ ■ ■ ■■■■■ ■ ■
■ ■■■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■■■ ■ ■■ ■ ■ ■■ ■■ ■■ ■ ■ ■■ ■■ ■ ■■ ■■
■ ■ ■ ■■■ ■ ■■■ ■ ■■■ ■ ■■ ■■■ ■■■ ■
■ ■
■ ■ ■
■■■ ■
■
■
■■ ■■■■ ■ ■■ ■■■ ■ ■■ ■■■ ■■■ ■ ■■■ ■■■■
■ ■ ■ ■■ ■■ ■■ ■■ ■■ ■■ ■■ ■ ■ ■■ ■■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■■■■■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■■ ■ ■ ■ ■ ■ ■ ■ ■■ ■ ■ ■ ■
■■ ■■■■ ■ ■ ■ ■ ■ ■ ■■■ ■ ■ ■■
merge request comment object: new comment, at, edit
msg to: comment author, at, merge assignee
'''
elif (data_json['object_kind'] == "note") and (data_json['object_attributes']['noteable_type'] == "MergeRequest") :
send_valid=1;
log( data_json['object_attributes']['noteable_type'] +" comment trigger received")
comment_url = data_json["object_attributes"]["url"]
log(comment_url)
comment_content = data_json['object_attributes']['note']
if comment_content != None:
receiver_dingUid = searchAt(receiver_dingUid,comment_content)
# content above are same in object kind NOTE (comment)
req_author_id = str(data_json["merge_request"]["author_id"])
req_author = labuid2username(req_author_id)
if(req_author in lab_members):
receiver_dingUid.append(lab_members[req_author])
log("MergeRequest author "+req_author+" get.")
if data_json["merge_request"]["assignee_id"] != None :
req_assignee_id = str(data_json["merge_request"]["assignee_id"])
req_assignee = labuid2username(req_assignee_id)
if(req_assignee in lab_members):
receiver_dingUid.append(lab_members[req_assignee])
log("MergeRequest assignee "+req_assignee+" get.")
merge_req_title = data_json['merge_request']['title']
project_name = data_json['project']['name']
if len(receiver_dingUid)==0 :
send_valid = 0
else:
receiver_dingUid_str = receiverSort(receiver_dingUid)
msg2dingapi_json_str=(
"{\"touser\": \""+receiver_dingUid_str+"\", \"agentid\": \""+AgentID+"\","
"\"msgtype\": \"markdown\","
"\"markdown\": {\"title\": \"MergeRequest通知\","
"\"text\": \"## 和你相关的MergeRequest评论 \\n"
"### 项目:"+project_name.replace("\"","\\\"")+" \\n"
"### 标题:"+merge_req_title.replace("\"","\\\"")+" \\n"
"[点击查看]("+comment_url+")"+timestamp+"\"} }"
)
msg2dingapi_b = msg2dingapi_json_str.encode('utf-8')
'''
■
■
■
■
■■ ■■■ ■ ■■■ ■■ ■ ■ ■■ ■■■ ■■ ■■ ■
■ ■ ■ ■ ■■ ■■ ■ ■■ ■■ ■■ ■■ ■ ■ ■ ■■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■■ ■■■■■ ■ ■ ■ ■ ■ ■ ■ ■■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■■ ■ ■ ■ ■■ ■■ ■ ■ ■ ■ ■ ■■ ■■
■■ ■■■ ■ ■ ■■■ ■ ■ ■ ■ ■■ ■■■ ■
■
■ ■
■■■
recognized object, have msg to send
'''
if (send_valid == 1):
send_valid =0
req_dingapi = request.Request("https://oapi.dingtalk.com/gettoken?corpid="+corpid+"&corpsecret="+corpsecret)
data_from_dingapi = request.urlopen(req_dingapi).read()
data_for_access_token = json.loads(data_from_dingapi.decode("utf-8"))
access_token = data_for_access_token['access_token']
if(debug!="0"):
log( "[debug]access_token:" + access_token)
url = "https://oapi.dingtalk.com/message/send?access_token="+access_token
headers2dingapi={"Content-Type":"application/json"}
req_dingapi = request.Request(url, data=msg2dingapi_b,headers=headers2dingapi, method="POST")
data_from_dingapi = request.urlopen(req_dingapi).read()
log( data_from_dingapi.decode('utf_8'))
json_from_dingapi = json.loads(data_from_dingapi.decode("utf-8"))
if (json_from_dingapi["errcode"]!=0):
print(msg2dingapi_json_str)
else: # send_valid==0, unhandled object kind
log( "Object "+data_json['object_kind'] +" received. not handled")
if (data_json['object_kind']=="note"):
log( "noteable_type "+data_json['object_attributes']['noteable_type'])
if "object_attributes" in data_json:
if "url" in data_json['object_attributes']:
log( data_json['object_attributes']['url'])
'''
bind dingUid to git email and lab username
query: action=&name=&username=&email=
'''
def do_GET(self):
method_get_req_dict = {}
global git_members
global lab_members
querypath = urlparse(self.path)
filepath, query = querypath.path, querypath.query
response_text=""
try:
datas = urllib.parse.unquote(querypath.query).split("&")
for data in datas:
key = data.split("=")[0]
value = data.split("=")[1]
method_get_req_dict[key] = value
except:
self.send_response(400)
self.send_header('Content-type',"text; charset=utf-8")
self.end_headers()
self.wfile.write("400 - Bad Request".encode("utf-8"))
log("bad request: "+ querypath.query)
else:
self.send_response(200)
self.send_header('Content-type',"text; charset=utf-8")
self.end_headers()
if "action" in method_get_req_dict:
'''
■ ■
■ ■■ ■
■ ■■ ■
■ ■
■ ■ ■ ■■■ ■ ■ ■ ■ ■■ ■■■ ■ ■■
■ ■ ■■ ■■ ■ ■ ■ ■ ■ ■ ■ ■ ■■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■■■ ■ ■ ■■ ■■■■■ ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■■ ■■ ■ ■ ■■ ■ ■
■ ■ ■ ■ ■ ■ ■■■ ■ ■■ ■■■ ■
action: add new user link
param: action, name(phone number,primary key), email(optional), username(gitlab username)
'''
if method_get_req_dict["action"] == "linkuser":
#ding_user_all = configparser.ConfigParser()
#ding_user_all.read("user_all")
#ding_user_list = ding_user_all["ding_userid_all"]
try:
os.system("python3 labFetchUser.py")
except:
log("labFetchUser fail")
else:
log("labFetchUser success")
ding_user_list = read_list_from_db("ding_user_list")
if method_get_req_dict["mobile"] in ding_user_list:
method_get_req_dict["dingUid"] = ding_user_list[method_get_req_dict["mobile"]]
response_text = "User found.\n"
if "email" in method_get_req_dict:
if method_get_req_dict["email"] not in git_members:
#config.set("gitmembers",method_get_req_dict["email"],method_get_req_dict["dingUid"])
#config.write(open('config.ini', 'w'))
sqlite_linkuser_add(method_get_req_dict["mobile"],method_get_req_dict["email"],"GITEMAIL")
response_text = response_text+"Git email added.\n"
log( "add git email for "+method_get_req_dict["mobile"] + ":"+method_get_req_dict["email"])
else:
response_text = response_text+"Git email already exists!!!\n"
log( "add git email for "+method_get_req_dict["mobile"] + ":"+method_get_req_dict["email"]+" fail:already exists")
if "username" in method_get_req_dict:
if method_get_req_dict["username"] not in lab_members:
#config.set("labmembers",method_get_req_dict["username"],method_get_req_dict["dingUid"])
#config.write(open('config.ini', 'w'))
sqlite_linkuser_add(method_get_req_dict["mobile"],method_get_req_dict["username"],"GITLABUSERNAME")
response_text = response_text+"Gitlab username added.\n"
log( "add lab username for "+method_get_req_dict["mobile"]+ ":"+method_get_req_dict["username"])
else:
response_text = response_text+"Gitlab username already exists!!!\n"
log( "add lab username for "+method_get_req_dict["mobile"]+ ":"+method_get_req_dict["username"]+" fail:already exists")
git_members = read_list_from_db("git_members")
lab_members = read_list_from_db("lab_members")
else:
response_text = "User not found, or already linked.\n"
log( "cannot find unlinked user : "+method_get_req_dict["mobile"])
elif method_get_req_dict["action"] == "linkfront":
response_text = '''
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<body>
<p>关联钉钉账号</p>
<p>根据自己实际情况修改相应字段:</p>
<form action="{0}" method="GET">
action:(默认为linkuser,无需改动)<br>
<input type="text" name="action" value="linkuser">
<br>
mobile: 必须。你的钉钉注册手机号。<br>
<input type="text" name="mobile">
<br>
username: 必须。你在Gitlab上的Username(你登录时所用的用户名,显示在点开右上角头像后第二行@开头的字段)<br>
<input type="text" name="username">
<br>
email: 可选。你在git提交中使用的email(如果你不是代码开发者,则不需要填写)<br>
<input type="text" name="email">
<br>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
'''.format(webhookurl)
else:
response_text = "error: action error"
log( "error: action error: "+method_get_req_dict["action"])
else: # no action param in request
response_text = "error: no action."
log( "error: no action param.")
self.wfile.write(response_text.encode("utf-8"))
def run():
print('starting server, port', port)
# Server settings
server_address = ('127.0.0.1', port)
httpd = HTTPServer(server_address, gitlab2dingsvr_RequestHandler)
print('running server...')
httpd.serve_forever()
if __name__ == '__main__':
run()