Commit ca3ca9d6 authored by PICHOU Kyâne's avatar PICHOU Kyâne
Browse files

Add script to disable notifications

parent 5a68a316
Pipeline #28088 failed with stages
## Détection des teams inactives sur mattermost
# Scripts Mattermost de Picasoft
### Scripts bash utilisant l'[API v4](https://api.mattermost.com/)
* mattermost_api_liste_teams_anciennes.sh
* mattermost_api_dernier_message.sh
### Pré-requis
Pour que les scripts fonctionnent bien, il est necesaire d'utiliser le compte admin de l'instance mattermost. (Les identifiants de Picasoft se trouvent dans la section privée du wiki).
### Utilisation
* Depuis n'importe quel ordi sous linux, télecharger ce dossier, extraire et ouvrir un terminal dessus.
* Générer un token: `curl -i -d '{"login_id":"<adresse@email.com>","password":"<mot_de_passe>"}' https://team.picasoft.net/api/v4/users/login | grep token`
(Adaptez la commande pour votre instance)
* Lancez cette commande: `./mattermost_api_liste_teams_anciennes.sh "token"`
Exemple: `./mattermost_api_liste_teams_anciennes.sh "h1z8..................5tmf"`
* Le script garde dans le fichier teams_anciennes.txt les détails des teams où le dernier message a été envoyé il y a plus de 1 an (id, display_name, email de l'admin de la team et la date du dernier message sur cette team)
* Si vous voulez modifier cette durée, il suffit de modifier cette ligne: `age_limite=31536000` (au début de mattermost_api_liste_teams_anciennes.sh). Il faut mettre une durée en secondes.
### Problèmes actuels
* Lorsqu'on génère un token, la commande qu'on a tappé (et donc le mot de passe du compte admin) reste dans l'historique! (~/.bash_history)
### Contribution
Toute contribution est bienvenue! N'hésitez pas à ouvrir une pull request ou à m'envoyer un mail sur amaldona@etu.utc.fr
### Licence
The MIT License
Copyright (c) 2017 Andrés Maldonado
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:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
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.
Ce *repository* héberge plusieurs scripts qui facilitent l'administration de Mattermost pour Picasoft.
- `team_inactives` permet de détecter les équipes inactives
- `disable_notifications` permet de désactiver les notifications mail d'une adresse mail donnée (utile pour de vieux comptes avec des adresses etu)
# Disable notifications
This script simply disable email notifications for a user and send a private message. It is useful when people have a wrong or deleted email address associated to their account (eg. old UTC student email).
This script need some requirements that you can install with `pip install requirements.txt`.
The script need access to an admin account on the Mattermost server. To provide authentication information there is 2 way :
- envrionment variables : `MM_URL` (eg. `https://team.picasoft.net`), `MM_USER` and `MM_PASSWORD`
- CLI arguments : `--mm-url`, `--mm-user` and `--mm-password`
Also, there is a required CLI argument : `--email` which is the mail of the user that need to have notifications disabled.
#!/usr/bin/python3
# coding=utf-8
"""Remove notifications for a mattermost user."""
# Imports
import argparse
import os
from urllib.parse import urlparse
import sys
import json
from mattermostdriver import Driver
# Constants
NOTIF_MESSAGE = """Salut ! Ceci est un message "automatique" de Picasoft :).
On a constaté des erreurs d'envois des mails de notifications de Mattermost vers ton adresse mail `[[EMAIL]]`. Un robot a donc désactivé les notifications par mails de ton compte Mattermost.
Cela peut venir du fait que ton adresse n'existe plus, ou encore d'un problème venant de ton serveur mail ou de celui de Picasoft. Si tu penses que l'on fait erreur et/ou pour avoir plus d'informations, n'hésite pas à nous contacter sur notre équipe Mattermost `Picasoft` ou par mail à `contact@picasoft.net`."""
def mattermost_connect(args):
"""
Instanciate a Mattermost connector.
:param args: CLI arguments
:return mat_api: A Mattermost APi connector
"""
# Extract Mattermost server informations
if args.mm_url is not None:
mm_url = args.mm_url
elif os.getenv('MM_URL') is not None:
mm_url = os.getenv('MM_URL')
else:
print('You need to specify --mm-url or MM_URL environment variable !')
sys.exit(1)
if args.mm_user is not None:
mm_user = args.mm_user
elif os.getenv('MM_USER') is not None:
mm_user = os.getenv('MM_USER')
else:
print('You need to specify --mm-user or MM_USER environment variable !')
sys.exit(1)
if args.mm_password is not None:
mm_password = args.mm_password
elif os.getenv('MM_PASSWORD') is not None:
mm_password = os.getenv('MM_PASSWORD')
else:
print('You need to specify --mm-password or MM_PASSWORD environment variable !')
sys.exit(1)
# Parse Mattermost URL
o = urlparse(mm_url)
if o.port is None:
if o.scheme == 'https':
mm_port = 443
elif o.scheme == 'http':
mm_port = 80
else:
print('Impossible to get Mattermost server port for ' + mm_url)
sys.exit(1)
else:
mm_port = o.port
# Connect to Mattermost
mat_api = Driver({
'url': o.hostname,
'login_id': mm_user,
'password': mm_password,
'scheme': o.scheme,
'port': mm_port
})
mat_api.login()
return mat_api
def get_user_by_email(email, conn):
"""
Get a Mattermost user by its email address.
:param email: Email to search for
:param conn: Connector for Mattermost API
:return user: Mattermost user
"""
# Search the user
try:
res = conn.client.make_request('post', '/users/search', options={'term': email})
except Exception as e:
print(e)
print('Error when requesting Mattermost API to search user ' + email)
sys.exit(1)
data = json.loads(res.text)
# Check in results for a user with the exact mail adress
for user in data:
if user['email'] == email:
return user
return None
def notify(user, message, conn):
"""
Send a private message to a Mattermost user.
:param user: Mattermost user object
:param message: Message to send
:param conn: Connector for Mattermost API
"""
# Get current user
try:
res = conn.client.make_request('get', '/users/me')
except Exception as e:
print(e)
print('Error when requesting Mattermost API to get current user.')
sys.exit(1)
data = json.loads(res.text)
# Create private message channel
try:
res = conn.client.make_request('post', '/channels/direct', options=[data['id'], user['id']])
except Exception as e:
print(e)
print('Error when requesting Mattermost API to create private conversation.')
sys.exit(1)
data = json.loads(res.text)
# Post a message
try:
conn.client.make_request('post', '/posts', options={'channel_id': data['id'], 'message': message})
except Exception as e:
print(e)
print('Error when requesting Mattermost API to send a private message.')
sys.exit(1)
def disable_notifications(user, conn):
"""
Disable mail notifications for a Mattermost user.
:param user: Mattermost user object
:param conn: Connector for Mattermost API
"""
# Patch user to disable mail notifications
try:
conn.client.make_request('put', '/users/' + user['id'] + '/patch', options={'notify_props': {'email': 'false'}})
except Exception as e:
print(e)
print('Error when disabling notifications for user ' + user['id'] + ' with Mattermost API.')
sys.exit(1)
def main():
"""Run the main function."""
# Parse CLI arguments
parser = argparse.ArgumentParser(description='Remove Matttermost notifications for an email.')
parser.add_argument('--email', help='Email of the user', required=True)
parser.add_argument(
'--mm-url',
help='Full URL of the Mattermost instance (eg. https://team.picasoft.net). Can be specified using MM_URL environment variable.',
required=False
)
parser.add_argument(
'--mm-user',
help='Username or email of a Mattermost admin account. Can be specified using MM_USER environment variable.',
required=False
)
parser.add_argument(
'--mm-password',
help='Password of the Mattermost admin account. Can be specified using MM_PASSWORD environment variable.',
required=False
)
args = parser.parse_args()
# Connect to Mattermost
mat_api = mattermost_connect(args)
# Get the user
user_email = args.email
user = get_user_by_email(user_email, mat_api)
if user is None:
print('Impossible to find a user matching ' + user_email)
sys.exit(1)
# Disable notifications
disable_notifications(user, mat_api)
# Send notification
msg = NOTIF_MESSAGE.replace('[[EMAIL]]', user_email)
notify(user, msg, mat_api)
if __name__ == '__main__':
main()
## Détection des teams inactives sur mattermost
### Scripts bash utilisant l'[API v4](https://api.mattermost.com/)
* mattermost_api_liste_teams_anciennes.sh
* mattermost_api_dernier_message.sh
### Pré-requis
Pour que les scripts fonctionnent bien, il est necesaire d'utiliser le compte admin de l'instance mattermost. (Les identifiants de Picasoft se trouvent dans la section privée du wiki).
### Utilisation
* Depuis n'importe quel ordi sous linux, télecharger ce dossier, extraire et ouvrir un terminal dessus.
* Générer un token: `curl -i -d '{"login_id":"<adresse@email.com>","password":"<mot_de_passe>"}' https://team.picasoft.net/api/v4/users/login | grep token`
(Adaptez la commande pour votre instance)
* Lancez cette commande: `./mattermost_api_liste_teams_anciennes.sh "token"`
Exemple: `./mattermost_api_liste_teams_anciennes.sh "h1z8..................5tmf"`
* Le script garde dans le fichier teams_anciennes.txt les détails des teams où le dernier message a été envoyé il y a plus de 1 an (id, display_name, email de l'admin de la team et la date du dernier message sur cette team)
* Si vous voulez modifier cette durée, il suffit de modifier cette ligne: `age_limite=31536000` (au début de mattermost_api_liste_teams_anciennes.sh). Il faut mettre une durée en secondes.
### Problèmes actuels
* Lorsqu'on génère un token, la commande qu'on a tappé (et donc le mot de passe du compte admin) reste dans l'historique! (~/.bash_history)
### Contribution
Toute contribution est bienvenue! N'hésitez pas à ouvrir une pull request ou à m'envoyer un mail sur amaldona@etu.utc.fr
### Licence
The MIT License
Copyright (c) 2017 Andrés Maldonado
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:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
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.
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment