20 |
20 |
import stat
|
21 |
21 |
import tempfile
|
22 |
22 |
import contextlib
|
|
23 |
import errno
|
23 |
24 |
|
|
25 |
from django.conf import settings
|
24 |
26 |
from django.core.files.storage import default_storage
|
25 |
27 |
from django.template.loader import get_template
|
26 |
28 |
from django.utils import six
|
... | ... | |
32 |
34 |
from passerelle.utils.api import endpoint
|
33 |
35 |
from passerelle.utils.jsonresponse import APIError
|
34 |
36 |
from passerelle.utils.conversion import ensure_encoding
|
|
37 |
from passerelle.utils.files import atomic_write
|
35 |
38 |
|
36 |
39 |
|
37 |
40 |
@contextlib.contextmanager
|
... | ... | |
51 |
54 |
|
52 |
55 |
@property
|
53 |
56 |
def basepath(self):
|
54 |
|
return os.path.join(
|
|
57 |
path = os.path.join(
|
55 |
58 |
default_storage.path('actesweb'), self.slug)
|
|
59 |
if not os.path.exists(path):
|
|
60 |
try:
|
|
61 |
os.makedirs(path)
|
|
62 |
except OSError as e:
|
|
63 |
if e.errno != errno.EEXIST:
|
|
64 |
raise
|
|
65 |
if settings.FILE_UPLOAD_DIRECTORY_PERMISSIONS:
|
|
66 |
# user and group must be able to delete/move files, others can read/access
|
|
67 |
os.chmod(path, 0o775)
|
|
68 |
return path
|
56 |
69 |
|
57 |
70 |
@endpoint(perm='can_access', methods=['post'], description=_('Create demand'))
|
58 |
71 |
def create(self, request, *args, **kwargs):
|
... | ... | |
67 |
80 |
template_name = 'actesweb/demand.txt'
|
68 |
81 |
demand_content = get_template(template_name).render(payload)
|
69 |
82 |
application_id = payload['application_id']
|
70 |
|
# create tmp dir
|
71 |
|
tmp_dir = os.path.join(self.basepath, 'tmp')
|
72 |
|
if not os.path.exists(tmp_dir):
|
73 |
|
if default_storage.directory_permissions_mode:
|
74 |
|
d_umask = os.umask(0)
|
75 |
|
try:
|
76 |
|
os.makedirs(tmp_dir, mode=default_storage.directory_permissions_mode)
|
77 |
|
except OSError:
|
78 |
|
pass
|
79 |
|
finally:
|
80 |
|
os.umask(d_umask)
|
81 |
|
else:
|
82 |
|
os.makedirs(tmp_dir)
|
83 |
83 |
|
84 |
84 |
# ensure demand_content can be encoded to latin15
|
85 |
85 |
demand_content = ensure_encoding(demand_content, 'iso-8859-15')
|
86 |
86 |
|
87 |
87 |
filename = '%s.DEM' % now().strftime('%Y-%m-%d_%H-%M-%S_%f')
|
88 |
88 |
filepath = os.path.join(self.basepath, filename)
|
89 |
|
with named_tempfile(dir=tmp_dir, suffix='.DEM', delete=False) as tpf:
|
90 |
|
tpf.write(demand_content)
|
91 |
|
tpf.flush()
|
92 |
|
os.fsync(tpf.file.fileno())
|
93 |
|
tempfile_name = tpf.name
|
94 |
|
os.rename(tempfile_name, filepath)
|
95 |
|
# set read only permission for owner and group
|
96 |
|
os.chmod(filepath, stat.S_IRUSR|stat.S_IRGRP|stat.S_IWGRP)
|
|
89 |
with atomic_write(filepath) as fd:
|
|
90 |
fd.write(demand_content.encode('iso-8859-15'))
|
|
91 |
# user can read/write, group can read, others can't
|
|
92 |
os.chmod(filepath, 0o640)
|
97 |
93 |
demand_id = '%s_%s' % (application_id, os.path.basename(filepath))
|
98 |
94 |
return {'data': {'demand_id': demand_id}}
|