-
Notifications
You must be signed in to change notification settings - Fork 14
/
mattermost_api.py
86 lines (62 loc) · 2.15 KB
/
mattermost_api.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
# -*- coding: utf-8 -*-
import json
import logging
import requests
import settings
logger = logging.getLogger('flask.app')
def get_user(user_id):
"""Return the json data of the user."""
if not settings.MATTERMOST_PA_TOKEN:
return {}
try:
header = {'Authorization': 'Bearer ' + settings.MATTERMOST_PA_TOKEN}
url = settings.MATTERMOST_URL + '/api/v4/users/' + user_id
r = requests.get(url, headers=header)
if r.ok:
return json.loads(r.text)
except KeyError as e:
logger.error(e)
return {}
def user_locale(user_id):
"""Return the locale of the user with the given user_id."""
if not settings.MATTERMOST_PA_TOKEN:
return "en"
user = get_user(user_id)
if 'locale' in user:
locale = user['locale']
if locale:
return locale
return "en"
def is_admin_user(user_id):
"""Return whether the user is an admin."""
user = get_user(user_id)
if 'roles' in user:
return 'system_admin' in user['roles']
return False
def is_team_admin(user_id, team_id):
"""Return whether the user is an admin in the given team."""
if not settings.MATTERMOST_PA_TOKEN:
return False
try:
header = {'Authorization': 'Bearer ' + settings.MATTERMOST_PA_TOKEN}
url = settings.MATTERMOST_URL + '/api/v4/teams/' + team_id + '/members/' + user_id
r = requests.get(url, headers=header)
if r.ok:
roles = json.loads(r.text)['roles']
return 'team_admin' in roles
except KeyError as e:
logger.error(e)
return False
def resolve_usernames(user_ids):
"""Resolve the list of user ids to list of user names."""
if len(user_ids) == 0:
return []
try:
header = {'Authorization': 'Bearer ' + settings.MATTERMOST_PA_TOKEN}
url = settings.MATTERMOST_URL + '/api/v4/users/ids'
r = requests.post(url, headers=header, json=user_ids)
if r.ok:
return [user["username"] for user in json.loads(r.text)]
except Exception as e:
logger.error('Username query failed: %s', str(e))
return ['<Failed to resolve usernames>']