Skip to content

Commit

Permalink
Merge pull request #2 from yaal-coop/precommit
Browse files Browse the repository at this point in the history
Add ruff pre-commit
  • Loading branch information
nschont authored Aug 16, 2023
2 parents 5ca3f4e + 1a582ea commit fcb38d4
Show file tree
Hide file tree
Showing 19 changed files with 65 additions and 87 deletions.
5 changes: 5 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: 'v0.0.276'
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
- repo: https://github.com/psf/black
rev: 22.12.0
hooks:
Expand Down
7 changes: 7 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,10 @@ extend-exclude = '''
[tool.pytest.ini_options]
env_files = ["web.env"]
testpaths = "web"

[tool.ruff]
ignore = [
"E501", # line too long
"E722", # bare expect
"E402", # import not at the top of the file
]
9 changes: 3 additions & 6 deletions web/flaskr/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.

from flask import Flask, render_template, request, session
from flask import Flask, request, session
import os
import logging

Expand Down Expand Up @@ -57,6 +57,7 @@ def global_processor():
"config": app.config,
"beta": app.config["BETA"],
"documentation_link": app.config["DOCUMENTATION_LINK"],
"LANGUAGES": LANGUAGES,
**app.config["WORDINGS"],
}

Expand All @@ -67,10 +68,6 @@ def global_processor():
csrf = CSRFProtect()
csrf.init_app(app)

@app.context_processor
def global_processor():
return {"LANGUAGES": LANGUAGES}

# init database
with app.app_context():
import flaskr.routes
Expand All @@ -79,7 +76,7 @@ def global_processor():
from .models import db

db.init_app(app)
migrate = Migrate(app, db, compare_type=True)
Migrate(app, db, compare_type=True)

# ensure the instance folder exists
os.makedirs(app.instance_path, exist_ok=True)
Expand Down
1 change: 0 additions & 1 deletion web/flaskr/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
SelectField,
StringField,
TextAreaField,
MultipleFileField,
BooleanField,
HiddenField,
validators,
Expand Down
15 changes: 5 additions & 10 deletions web/flaskr/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,9 @@

from flaskr.tasks import background_upload

import importlib.util
import sys
import signal


from flask_sqlalchemy import SQLAlchemy
from sqlalchemy_utils import EncryptedType
from os import fork

from flask import current_app, url_for, render_template

Expand All @@ -29,6 +24,8 @@
from datetime import date, datetime, timedelta, timezone

from flaskr.utils import secret_key
import os


db = SQLAlchemy()

Expand Down Expand Up @@ -63,7 +60,7 @@ def get_user_nc_credentials(username):
)
data = response.json()
return data
except requests.exceptions.RequestException as e:
except requests.exceptions.RequestException:
print("Cannot contact NC, returning None values")
return {"nctoken": None, "nclocator": None, "nclogin": None}

Expand Down Expand Up @@ -259,7 +256,6 @@ def insertDocsNoDefault(self):
"%s/%s" % (BIGBLUEBUTTON_ENDPOINT, insertAction),
params=params,
)
headers = {"Content-Type": "application/xml"}
pr = request.prepare()
bigbluebutton_secret = BIGBLUEBUTTON_SECRET
s = "%s%s" % (
Expand All @@ -268,7 +264,7 @@ def insertDocsNoDefault(self):
)
params["checksum"] = hashlib.sha1(s.encode("utf-8")).hexdigest()

r = requests.post(
requests.post(
f"{BIGBLUEBUTTON_ENDPOINT}/{insertAction}",
headers={"Content-Type": "application/xml"},
data=xml,
Expand Down Expand Up @@ -415,15 +411,14 @@ def create(self):
"%s/%s" % (BIGBLUEBUTTON_ENDPOINT, insertAction),
params=params,
)
headers = {"Content-Type": "application/xml"}
pr = request.prepare()
bigbluebutton_secret = BIGBLUEBUTTON_SECRET
s = "%s%s" % (
pr.url.replace("?", "").replace(BIGBLUEBUTTON_ENDPOINT + "/", ""),
bigbluebutton_secret,
)
params["checksum"] = hashlib.sha1(s.encode("utf-8")).hexdigest()
task = background_upload.delay(
background_upload.delay(
f"{BIGBLUEBUTTON_ENDPOINT}/{insertAction}", xml, params
)

Expand Down
48 changes: 20 additions & 28 deletions web/flaskr/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from werkzeug.utils import secure_filename

from webdav3.client import Client as webdavClient
from webdav3.exceptions import MethodNotSupported, WebDavException
from webdav3.exceptions import WebDavException

from pathlib import Path

Expand All @@ -27,38 +27,34 @@
render_template,
send_file,
make_response,
Response,
request,
redirect,
flash,
session,
jsonify,
url_for,
)
from xml.etree import ElementTree
from flask_babel import lazy_gettext
from flask_pyoidc import OIDCAuthentication
from flask_pyoidc.provider_configuration import (
ProviderConfiguration,
ClientMetadata,
)
from flask_pyoidc.user_session import UserSession
from sqlalchemy import or_, exc
from sqlalchemy import exc
import random
import hashlib
import os
import re
import smtplib
import string
import requests
import shutil
import secrets
import uuid

from datetime import datetime, date
from email.mime.text import MIMEText
from email.message import EmailMessage
from urllib.parse import quote
from netaddr import IPNetwork, IPAddress

from flaskr.forms import (
Expand Down Expand Up @@ -252,7 +248,7 @@ def get_meetings_stats():
stats_array = [row.split(",") for row in stats_array]
participantCount = int(stats_array[current_app.config["STATS_INDEX"]][1])
runningCount = int(stats_array[current_app.config["STATS_INDEX"]][2])
except Exception as e:
except Exception:
return None

result = {"participantCount": participantCount, "runningCount": runningCount}
Expand All @@ -262,18 +258,15 @@ def get_meetings_stats():
@bp.route("/api/meetings", methods=["GET"])
@auth.token_auth(provider_name="default")
def api_meetings():
if auth.current_token_identity:
current_identity = auth.current_token_identity
else:
if not auth.current_token_identity:
return redirect("/")

info = {
"given_name": auth.current_token_identity["given_name"],
"family_name": auth.current_token_identity["family_name"],
"email": auth.current_token_identity["email"],
}
user = get_or_create_user(info)
fullname = user.fullname
stats = get_meetings_stats()
return {
"meetings": [
{
Expand All @@ -292,7 +285,7 @@ def api_meetings():
def insertDocuments(meeting_id):
from flask import request

user = get_current_user()
get_current_user()
meeting = Meeting.query.get(meeting_id)
files_title = request.get_json()
secret_key = current_app.config["SECRET_KEY"]
Expand All @@ -316,7 +309,6 @@ def insertDocuments(meeting_id):
"%s/%s" % (current_app.config["BIGBLUEBUTTON_ENDPOINT"], "insertDocument"),
params=params,
)
headers = {"Content-Type": "application/xml"}
pr = request.prepare()
bigbluebutton_secret = current_app.config["BIGBLUEBUTTON_SECRET"]
s = "%s%s" % (
Expand All @@ -326,7 +318,7 @@ def insertDocuments(meeting_id):
bigbluebutton_secret,
)
params["checksum"] = hashlib.sha1(s.encode("utf-8")).hexdigest()
r = requests.post(
requests.post(
f"{bbb_endpoint}/insertDocument",
headers={"Content-Type": "application/xml"},
data=xml,
Expand Down Expand Up @@ -482,7 +474,7 @@ def quick_mail_meeting():
id=email
) # this user can probably be removed if we created adock function
m = get_quick_meeting_from_user_and_random_string(user)
signinurl = _send_mail(m, email)
_send_mail(m, email)
flash(
lazy_gettext("Vous avez reçu un courriel pour vous connecter"), "success_login"
)
Expand Down Expand Up @@ -831,7 +823,7 @@ def add_meeting_file_dropzone(title, meeting_id, is_default):
meetingFile.is_default = False

meetingFile.save()
secret_key = current_app.config["SECRET_KEY"]
current_app.config["SECRET_KEY"]
meetingFile.update()
# file has been associated AND uploaded to nextcloud, we can safely remove it from visio-agent tmp directory
removeDropzoneFile(dropzonePath)
Expand All @@ -851,7 +843,7 @@ def add_meeting_file_dropzone(title, meeting_id, is_default):


def add_meeting_file_URL(url, meeting_id, is_default):
user = get_current_user()
get_current_user()
title = url.rsplit("/", 1)[-1]

# test MAX_SIZE_UPLOAD for 20Mo
Expand Down Expand Up @@ -880,7 +872,7 @@ def add_meeting_file_URL(url, meeting_id, is_default):
meetingFile.url = url
meetingFile.is_default = is_default

getFile = requests.get(url)
requests.get(url)

try:
meetingFile.save()
Expand Down Expand Up @@ -911,7 +903,7 @@ def add_meeting_file_nextcloud(path, meeting_id, is_default):
try:
client = webdavClient(options)
metadata = client.info(path)
except WebDavException as exception:
except WebDavException:
user.disable_nextcloud()
return jsonify(
status=500,
Expand All @@ -922,7 +914,7 @@ def add_meeting_file_nextcloud(path, meeting_id, is_default):
return jsonify(
status=500,
isfrom="nextcloud",
msg=f"Fichier {title} TROP VOLUMINEUX, ne pas dépasser 20Mo",
msg=f"Fichier {path} TROP VOLUMINEUX, ne pas dépasser 20Mo",
)

meetingFile = MeetingFiles()
Expand All @@ -932,7 +924,7 @@ def add_meeting_file_nextcloud(path, meeting_id, is_default):
meetingFile.meeting_id = meeting_id
meetingFile.nc_path = path
meetingFile.is_default = is_default
secret_key = current_app.config["SECRET_KEY"]
current_app.config["SECRET_KEY"]

try:
meetingFile.save()
Expand All @@ -952,7 +944,7 @@ def add_meeting_file_nextcloud(path, meeting_id, is_default):


def add_external_meeting_file_nextcloud(path, meeting_id):
user = get_current_user()
get_current_user()

externalMeetingFile = MeetingFilesExternal()

Expand Down Expand Up @@ -1123,7 +1115,7 @@ def save_meeting():
)

if meeting.is_meeting_running():
end_meeting_form = EndMeetingForm()
EndMeetingForm()
EndMeetingForm.meeting_id.data = meeting.id
return render_template(
"meeting/end.html",
Expand Down Expand Up @@ -1200,7 +1192,7 @@ def insertDoc(token):
# xml now use
xml = f"<?xml version='1.0' encoding='UTF-8'?> <modules> <module name='presentation'><document url='{current_app.config['SERVER_FQDN']}/ncdownload/{m.id}/{m.download_hash}' filename='m.title' /> </module></modules>"

r = requests.post(
requests.post(
f"{current_app.config['BIGBLUEBUTTON_ENDPOINT']}/insertDocument",
data=xml,
headers=headers,
Expand Down Expand Up @@ -1271,7 +1263,7 @@ def ncdownload(isexternal, mfid, mftoken):
"local_path": tmpName,
}
client.download_sync(**kwargs)
except WebDavException as exception:
except WebDavException:
meeting_file.meeting.user.disable_nextcloud()
return jsonify(status=500, msg="La connexion avec Nextcloud semble rompue")
# send the downloaded file to the BBB:
Expand Down Expand Up @@ -1449,7 +1441,7 @@ def join_mail_meeting():
return redirect("/")
fullname = form["fullname"].data
meeting_fake_id = form["meeting_fake_id"].data
user_id = form["user_id"].data
form["user_id"].data
expiration = form["expiration"].data
h = form["h"].data

Expand Down Expand Up @@ -1542,7 +1534,7 @@ def delete_meeting():
flash(
"Nous n'avons pas pu supprimer les vidéos de cette "
+ current_app.config["WORDINGS"]["meeting_label"]
+ " : {message}".format(code=return_code, message=message),
+ " : {message}".format(message=message),
"error",
)
else:
Expand Down
3 changes: 1 addition & 2 deletions web/flaskr/tasks.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import os
import time
import requests

from celery import Celery
Expand All @@ -13,7 +12,7 @@

@celery.task(name="background_upload")
def background_upload(endpoint, xml, params):
r = requests.post(
requests.post(
endpoint,
headers={"Content-Type": "application/xml"},
data=xml,
Expand Down
4 changes: 2 additions & 2 deletions web/migrations/alembic_helpers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Code based on https://github.com/talkpython/data-driven-web-apps-with-flask

from alembic import op
from sqlalchemy import engine_from_config, inspect
from sqlalchemy import engine_from_config

from sqlalchemy import MetaData

Expand Down Expand Up @@ -36,7 +36,7 @@ def table_does_not_exist(table):
def table_has_column(table, column):
has_column = False
print(table, flush=True)
if not table in schema:
if table not in schema:
return
for s_column in schema[table]:
print(" %s" % s_column, flush=True)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

import os
import sys
Expand Down
Loading

0 comments on commit fcb38d4

Please sign in to comment.