19/05/22 - 15h30

master
ChérifBALDE 2022-05-19 15:06:21 +02:00 committed by cherif
parent 176c5fed94
commit 581ffd0a37
5 changed files with 263 additions and 9 deletions

View File

@ -44,7 +44,7 @@ token_fr_pontuation = []
La taille maximal d'un champs à retourner. La taille maximal d'un champs à retourner.
Au dela de 300 caractère, le système rame Au dela de 300 caractère, le système rame
''' '''
MAX_CARACT = 300 MAX_CARACT = 250
MAX_CARACT_DEDUIT = 50 MAX_CARACT_DEDUIT = 50
TOKEN_SIZE = 25 TOKEN_SIZE = 25
MAX_CARACT_DETAIL = 500 MAX_CARACT_DETAIL = 500

View File

@ -8,6 +8,7 @@ import datetime
import inspect import inspect
import sys, os import sys, os
import prj_common as mycommon import prj_common as mycommon
import GlobalVariable as MYSY_GV
locale.setlocale(category=locale.LC_ALL, locale='fr_FR.utf8') locale.setlocale(category=locale.LC_ALL, locale='fr_FR.utf8')
@ -202,7 +203,7 @@ def send_user_init_pwd_mail(token, account_mail):
msg = MIMEMultipart("alternative") msg = MIMEMultipart("alternative")
msg['Subject'] = '[MySy Training] : Reinitialisez votre mot de passe' msg['Subject'] = '[MySy Training Technology] : Reinitialisez votre mot de passe'
msg['From'] = 'billardman01@hotmail.com' msg['From'] = 'billardman01@hotmail.com'
msg['To'] = str(account_mail) msg['To'] = str(account_mail)
@ -284,8 +285,6 @@ def send_user_init_pwd_mail(token, account_mail):
''' '''
Envoie de l'email de suppression du compte utilisateur Envoie de l'email de suppression du compte utilisateur
''' '''
def send_user_delete_account(token, account_mail): def send_user_delete_account(token, account_mail):
try: try:
tomorrow = datetime.date.today() + datetime.timedelta(days=1) tomorrow = datetime.date.today() + datetime.timedelta(days=1)
@ -293,7 +292,7 @@ def send_user_delete_account(token, account_mail):
msg = MIMEMultipart("alternative") msg = MIMEMultipart("alternative")
msg['Subject'] = '[MySy Training] : Suppression de votre' msg['Subject'] = '[MySy Training Technology] : Suppression de votre'
msg['From'] = 'billardman01@hotmail.com' msg['From'] = 'billardman01@hotmail.com'
msg['To'] = str(account_mail) msg['To'] = str(account_mail)
@ -372,3 +371,70 @@ Le échéant, vous pouvez finaliser la suppression de votre compte en cliquant s
exc_type, exc_obj, exc_tb = sys.exc_info() exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno)) mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, " Impossible d'envoyer l'email de notification " return False, " Impossible d'envoyer l'email de notification "
'''
Cette fonction envoir n'import quel email avec les varibable :
- recever_email
- objet_mail
- message_mail
'''
def SendGenericEmail(mail_recever=None, mail_object=None, mail_message=None):
try:
tomorrow = datetime.date.today() + datetime.timedelta(days=1)
tomorrow_day = tomorrow.strftime("%A")
print("debut envoi mail de test ")
# on rentre les renseignements pris sur le site du fournisseur
msg = MIMEMultipart("alternative")
msg['Subject'] = '[MySy Training Technology] : '+str(mail_object)
msg['From'] = MYSY_GV.INTERNAL_MAIL_SENDER
msg['To'] = str(mail_recever)
html = '''
<!DOCTYPE html>
<html>
<body>
<div style="background-color:#eee;padding:0px;text-align:center;width:100%">
<h2 style="font-family:Georgia, 'Times New Roman', Times, serif;color#454349;">
<img src="http://88.170.110.220/img/MYSY-LOGO-BLUE.png" alt="Mysy Training Logo" width="110px" height="70px"/> </h2>
</div>
<div style="padding:20px 0px;text-align:center;font-family:Georgia, 'Times New Roman', Times, serif;color#454349;font-size:2rem;">
<div style="width:100%">
<div style="text-align:center;">
Bonjour
<div style="padding:20px 0px;text-align:center;font-family:Georgia, 'Times New Roman', Times, serif;color#454349;font-size:1.2rem;">
Message de <font color="green">MySy-Training Technology </font>.<br/>
{mymessage}
</div>
</body>
</html> '''.format(mymessage=mail_message)
html_mime = MIMEText(html, 'html')
# msg.attach(texte_mime)
msg.attach(html_mime)
print("html_mime =" + str(html))
toaddr = str(mail_recever)
cc = ['cbalde@mysy-training.com']
toaddrs = [toaddr] + cc
# msg.attach(MIMEText(open(filename).read()))
with smtplib.SMTP(smtp_address, port) as server:
server.starttls() # Secure the connection
server.login(user, password)
server.sendmail(sender, toaddrs, msg.as_string())
mycommon.myprint("mail successfully sent to " + str(toaddrs))
return True
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
print(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False

25
main.py
View File

@ -1010,6 +1010,31 @@ def mysy_recherche_levenshtein_orig():
status, result = TP.mysy_recherche_levenshtein_orig() status, result = TP.mysy_recherche_levenshtein_orig()
return jsonify(status=status, message=result) return jsonify(status=status, message=result)
'''
Cette API est le cron qui traite les emails stockes dans la collection
'user_message'
'''
@app.route('/myclass/api/CronUSerMessage_Mail/', methods=['GET','POST'])
@crossdomain(origin='*')
def CronUSerMessage_Mail():
# On recupere le corps (payload) de la requete
payload = request.form.to_dict()
print(" ### payload = ", payload)
status, date_treatment, result = mycommon.CronUSerMessage_Mail()
return jsonify(status=status, date_treatment = str(date_treatment), message=result)
'''
Juste une API pour tester de ptite choses
'''
@app.route('/myclass/api/testch/', methods=['GET','POST'])
@crossdomain(origin='*')
def testch():
# On recupere le corps (payload) de la requete
payload = request.form.to_dict()
print(" ### payload = ", payload)
status, result = mycommon.Reordertab()
return jsonify(status=status, message=result)
if __name__ == '__main__': if __name__ == '__main__':
print(" debut api") print(" debut api")

View File

@ -4,6 +4,8 @@ import textdistance
from datetime import datetime from datetime import datetime
import logging import logging
import secrets import secrets
from bson import ObjectId
from pymongo import MongoClient from pymongo import MongoClient
import inspect import inspect
from werkzeug.utils import secure_filename from werkzeug.utils import secure_filename
@ -19,7 +21,8 @@ import GlobalVariable as MYSY_GV
from serpapi import GoogleSearch from serpapi import GoogleSearch
import prj_common as mycommon import prj_common as mycommon
import re import re
import email_mgt as email_mgt
import random
def myprint(message = ""): def myprint(message = ""):
logging.info(str(datetime.now()) + " : "+str(message) ) logging.info(str(datetime.now()) + " : "+str(message) )
@ -638,3 +641,156 @@ def CreateMyCode():
exc_type, exc_obj, exc_tb = sys.exc_info() exc_type, exc_obj, exc_tb = sys.exc_info()
print(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno)) print(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, '-1' return False, '-1'
'''
Cette fonction va aller cherche tous les messages à envoyer
dans la collection 'user_message' et declencher le traitement
adequat
'''
def CronUSerMessage_Mail():
try:
nb_message = 0
coll_message = MYSY_GV.dbname['user_message']
my_today = datetime.today()
for val in coll_message.find({'sent':'0', 'valide':'1', 'type':'email'}):
ismail_traited = '1'
error_message = ""
nb_message = nb_message + 1
print(" traitement du message : "+str(val))
mail_recever = ""
if ("recever_mail" in val.keys()):
if val['recever_mail']:
mail_recever = str(val['recever_mail']).strip()
mail_object = ""
if ("object" in val.keys()):
if val['object']:
mail_object = str(val['object']).strip()
message = ""
if ("message" in val.keys()):
if val['message']:
message = str(val['message']).strip()
# pattern des email
patter_mail = re.compile(r"^[\w\.]+@([\w-]+\.)+[\w]{2,4}$")
if (re.match(patter_mail, str(mail_recever))):
if( len(mail_object) == 0 or len(message) == 0 ):
myprint(" WARNING : Impossible d'enboyer le mail au destinataire. l'objet ou le message sont vides : mail_object = "
+ str(mail_object)+ " ou message = "+str(message))
ismail_traited = 'error'
error_message = "l'objet ou le message sont vides"
else:
if( email_mgt.SendGenericEmail(mail_recever, mail_object, message) is False ):
ismail_traited = 'error'
error_message = " Erreur SMPT "
# envoyer le mail
else:
myprint(" WARNING : Impossible d'envoyer le mail au destinataire. format incorrecte: "+str(mail_recever))
ismail_traited = 'error'
error_message = "format du mail receveur est incorrecte "
'''
Mise à jour du statut du message
'''
ret_val = coll_message.find_one_and_update({'_id': ObjectId(val['_id']),},
{"$set": {'sent':str(ismail_traited),
'error_message':str(error_message)}},
return_document=ReturnDocument.AFTER
)
if (ret_val and ret_val['_id']):
nb_doc = str(ret_val['_id'])
myprint(" le message = " + str(nb_doc)+" a bien été mise à jour")
else:
myprint(
str(inspect.stack()[0][3]) + " WARNING : Impossible de mettre à jour le user_message = " + str(
nb_doc))
return True, str(my_today), str(nb_message) + " traite (s) : OK"
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
print(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False,str(datetime.today()), " Impossible de traiter les demandes d'envoi d'email "
'''
Cette fonction prend un tableau
et retourn le meme tableau mais dans un order aléatoire
/!\ cette fonction est trop lente, je ne peux l'utiliser
'''
def RendomizeTab(table):
try:
if( table.count() <= 0 ):
print(" impossible de rendomize")
return False, []
taille = table.count()-1
new_tab = []
new_tab_cpt = 0
i = 0
while( new_tab_cpt <= taille ):
cpt = random.randint(0, taille)
#print("cpt = " + str(cpt) + " - len(table) = " + str(table.count()))
#print(" ANALYSE DE " + str(table[cpt]['_id']))
if( table[cpt] not in new_tab ):
#print(" AJOUT DE "+str(table[cpt]['_id']))
new_tab.append(table[cpt])
new_tab_cpt = new_tab_cpt +1
return True, new_tab
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
print(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, []
def Reordertab():
try:
coll_name = MYSY_GV.dbname['myclass']
table = coll_name.find({'trainer':'PYRAMYD'},
{"external_code": 1, "title": 1, "_id": 1, "url": 1, })
print(str(table.count()))
taille = table.count()-1
new_tab = []
new_tab_cpt = 0
i = 0
while( new_tab_cpt <= taille ):
cpt = random.randint(0, taille)
#print("cpt = " + str(cpt) + " - len(table) = " + str(table.count()))
#print(" ANALYSE DE " + str(table[cpt]['_id']))
if( table[cpt] not in new_tab ):
#print(" AJOUT DE "+str(table[cpt]['_id']))
new_tab.append(table[cpt])
new_tab_cpt = new_tab_cpt +1
return True, new_tab
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
print(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, []

View File

@ -116,7 +116,7 @@ def update_class_by_attribut(objId, attribut, value):
return False return False
import random
def get_all_class(diction): def get_all_class(diction):
try: try:
@ -179,9 +179,16 @@ def get_all_class(diction):
val_tmp = 1 val_tmp = 1
insertObject = [] insertObject = []
for x in coll_name.find({'valide':'1', 'locked':'0'}, {"_id": 0, "indexed": 0, "indexed_desc": 0, "indexed_obj": 0, "indexed_title": 0, for x in coll_name.find({'valide':'1', 'locked':'0'}, {"_id": 0, "indexed": 0, "indexed_desc": 0, "indexed_obj": 0, "indexed_title": 0,
"valide": 0, "locked": 0, "partner_owner_recid": 0, }): "valide": 0, "locked": 0, "partner_owner_recid": 0, }).sort(
#mycommon.myprint("AVANT ==> "+str(x['description'])) [ ("_id", pymongo.DESCENDING),]):
#print("AVANT ==> "+str(x['description']))
val = x['description'] val = x['description']
if( len(x['description']) > MYSY_GV.MAX_CARACT ): if( len(x['description']) > MYSY_GV.MAX_CARACT ):
x['description'] = val[:MYSY_GV.MAX_CARACT]+" ..." x['description'] = val[:MYSY_GV.MAX_CARACT]+" ..."