assets: import/export slot assets (#37674)

This commit is contained in:
Valentin Deniaud 2020-01-02 17:49:59 +01:00
parent e451097bef
commit dcc6d9f97a
2 changed files with 40 additions and 1 deletions

View File

@ -14,6 +14,7 @@
# 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 json
import tarfile
import os
@ -33,6 +34,7 @@ import ckeditor
from sorl.thumbnail.shortcuts import get_thumbnail
from combo.data.models import CellBase
from combo.data.utils import import_site
from .forms import AssetUploadForm, AssetsImportForm
from .models import Asset
@ -276,7 +278,11 @@ class AssetsImport(FormView):
filepath = default_storage.path(tarinfo.name)
if not overwrite and os.path.exists(filepath):
continue
assets.extract(tarinfo, path=media_prefix)
if tarinfo.name == '_assets.json':
json_assets = assets.extractfile(tarinfo).read()
import_site(json.loads(json_assets.decode('utf-8')))
else:
assets.extract(tarinfo, path=media_prefix)
messages.success(self.request, _('The assets file has been imported.'))
return super(AssetsImport, self).form_valid(form)
@ -292,6 +298,14 @@ def assets_export(request, *args, **kwargs):
assets_file.add(
os.path.join(basedir, filename),
os.path.join(basedir, filename)[len(media_prefix):])
if Asset.objects.exists():
json_file = tarfile.TarInfo('_assets.json')
json_fd = BytesIO()
export = {'assets': Asset.export_all_for_json(),}
json_fd.write(json.dumps(export).encode('utf-8'))
json_file.size = json_fd.tell()
json_fd.seek(0)
assets_file.addfile(json_file, fileobj=json_fd)
assets_file.close()
return HttpResponse(fd.getvalue(), content_type='application/x-tar')

View File

@ -1096,6 +1096,31 @@ def test_asset_slots_management(app, admin_user):
assert '>CGU<' in resp.text
def test_asset_slots_export(app, admin_user):
app = login(app)
with override_settings(COMBO_ASSET_SLOTS={'collectivity:banner': {'label': 'Banner'}}):
resp = app.get('/manage/assets/')
resp = resp.click('Overwrite')
resp.form['upload'] = Upload('test.png',
base64.decodestring(b'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQI12NgAgAABAADRWoApgAA\nAABJRU5ErkJggg=='),
'image/png')
resp = resp.form.submit().follow()
assert Asset.objects.filter(key='collectivity:banner').count() == 1
resp = resp.click('Export')
assert resp.content_type == 'application/x-tar'
content = resp.content
Asset.objects.filter(key='collectivity:banner').delete()
resp = app.get('/manage/assets/')
resp = resp.click('Import')
resp.form['assets_file'] = Upload('test.tar', content)
resp = resp.form.submit()
assert Asset.objects.filter(key='collectivity:banner').count() == 1
def test_serve_asset(settings, app, admin_user):
settings.COMBO_ASSET_SLOTS = {'collectivity:banner': {'label': 'Banner'}}
app = login(app)