fargo/fargo/fargo/managers.py

51 lines
1.8 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 datetime
from django.db import models
from django.utils.timezone import now
from . import utils
class DocumentManager(models.Manager):
def cleanup(self, n=None):
'''Delete all orphaned documents'''
n = n or now()
# use a window of 60 seconds to be sure this document will never be used
qs = self.filter(creation_date__lt=n - datetime.timedelta(seconds=60))
qs = qs.filter(user_documents__isnull=True,
oauth2_tempfiles__isnull=True)
for document in qs:
document.content.delete(False)
qs.delete()
def get_by_file(self, f):
'''Get document with the same SHA-256 hash as the passde Django file
like object.
'''
file_hash = utils.sha256_of_file(f)
try:
o = self.get(content_hash=file_hash)
except self.model.DoesNotExist:
o = self.model()
o.content.save(file_hash, f)
return o
def used_space(self, user):
return sum([doc.content.size for doc in self.filter(user_documents__user=user).distinct()])