fargo/fargo/fargo/utils.py

71 lines
1.9 KiB
Python

# fargo - document box
# Copyright (C) 2016-2019 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import hashlib
from django.utils.timezone import utc
from django.utils.encoding import smart_bytes
from django.apps import apps
try:
import magic
except ImportError:
magic = None
def to_isodate(dt):
return dt.astimezone(utc).isoformat('T').split('.')[0] + 'Z'
def get_document_type_schema(settings, document_type):
for schema in settings.FARGO_DOCUMENT_TYPES:
if schema.get('name') == document_type:
return schema
def sha256_of_file(f):
'''Compute SHA-256 hash of Django File object'''
hasher = hashlib.sha256()
for chunk in f.chunks():
hasher.update(chunk)
return hasher.hexdigest()
def get_mime_type(path):
if magic is None:
return None
magic_object = magic.open(magic.MIME)
magic_object.load()
mime_type = magic_object.file(smart_bytes(path))
magic_object.close()
if mime_type:
mime_type = mime_type.split(';')[0]
if mime_type.startswith('cannot open'):
mime_type = None
return mime_type
def cleanup_model(model, n=None):
manager = getattr(model, 'objects', None)
if hasattr(manager, 'cleanup'):
manager.cleanup(n=n)
def cleanup(n=None):
for model in apps.get_models():
cleanup_model(model, n=n)