Skip to content

Commit 8763170

Browse files
committed
fix #3389
1 parent ea0a7ec commit 8763170

File tree

3 files changed

+135
-3
lines changed

3 files changed

+135
-3
lines changed

qiita_pet/handlers/download.py

Lines changed: 128 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from tornado.web import authenticated, HTTPError
1010
from tornado.gen import coroutine
1111

12-
from os.path import basename, getsize, join, isdir
12+
from os.path import basename, getsize, join, isdir, getctime
1313
from os import walk
1414

1515
from .base_handlers import BaseHandler
@@ -23,7 +23,7 @@
2323
from qiita_db.util import (filepath_id_to_rel_path, get_db_files_base_dir,
2424
get_filepath_information, get_mountpoint,
2525
filepath_id_to_object_id, get_data_types,
26-
retrieve_filepaths)
26+
retrieve_filepaths, get_work_base_dir)
2727
from qiita_db.meta_util import validate_filepath_access_by_user
2828
from qiita_db.metadata_template.sample_template import SampleTemplate
2929
from qiita_db.metadata_template.prep_template import PrepTemplate
@@ -35,6 +35,10 @@
3535
from uuid import uuid4
3636
from base64 import b64encode
3737
from datetime import datetime, timedelta, timezone
38+
from tempfile import mkdtemp
39+
from zipfile import ZipFile
40+
from io import BytesIO
41+
from shutil import copyfile
3842

3943

4044
class BaseHandlerDownload(BaseHandler):
@@ -374,6 +378,128 @@ def get(self, path):
374378
self.finish()
375379

376380

381+
class DownloadDataReleaseFromPrep(BaseHandlerDownload):
382+
@authenticated
383+
@coroutine
384+
@execute_as_transaction
385+
def get(self, prep_template_id):
386+
user = self.current_user
387+
if user.level not in ('admin', 'web-lab admin'):
388+
raise HTTPError(403, reason="%s doesn't have access to download "
389+
"the data release files" % user.email)
390+
391+
pid = int(prep_template_id)
392+
pt = PrepTemplate(pid)
393+
sid = pt.study_id
394+
st = SampleTemplate(sid)
395+
date = datetime.now().strftime('%m%d%y-%H%M%S')
396+
td = mkdtemp(dir=get_work_base_dir())
397+
398+
files = []
399+
readme = [
400+
f'Delivery created on {date}',
401+
'',
402+
f'Host (human) removal: {pt.artifact.human_reads_filter_method}',
403+
'',
404+
# this is not changing in the near future so just leaving
405+
# hardcoded for now
406+
'Main woltka reference: WoLr2, more info visit: '
407+
'https://ftp.microbio.me/pub/wol2/',
408+
'',
409+
f"Qiita's prep: https://qiita.ucsd.edu/study/description/{sid}"
410+
f"?prep_id={pid}",
411+
'',
412+
]
413+
414+
human_names = {
415+
'ec.biom': 'KEGG Enzyme (EC)',
416+
'per-gene.biom': 'Per gene Predictions',
417+
'none.biom': 'Per genome Predictions',
418+
'cell_counts.biom': 'Cell counts',
419+
'pathway.biom': 'KEGG Pathway',
420+
'ko.biom': 'KEGG Ontology (KO)',
421+
'rna_copy_counts.biom': 'RNA copy counts'
422+
}
423+
424+
fn = join(td, f'sample_information_from_prep_{pid}.tsv')
425+
readme.append(f'Sample information: {basename(fn)}')
426+
files.append(fn)
427+
st.to_dataframe(samples=list(pt)).to_csv(fn, sep='\t')
428+
429+
fn = join(td, f'prep_information_{pid}.tsv')
430+
readme.append(f'Prep information: {basename(fn)}')
431+
files.append(fn)
432+
pt.to_dataframe().to_csv(fn, sep='\t')
433+
434+
readme.append('')
435+
436+
bioms = dict()
437+
coverages = None
438+
for a in Study(sid).artifacts(artifact_type='BIOM'):
439+
if a.prep_templates[0].id != pid:
440+
continue
441+
biom = None
442+
for fp in a.filepaths:
443+
if fp['fp_type'] == 'biom':
444+
biom = fp
445+
if coverages is None and 'coverages.tgz' == basename(fp['fp']):
446+
coverages = fp['fp']
447+
if biom is None:
448+
continue
449+
biom_fn = basename(biom['fp'])
450+
if biom_fn not in bioms:
451+
bioms[biom_fn] = [a, biom]
452+
else:
453+
if getctime(biom['fp']) > getctime(bioms[biom_fn][1]['fp']):
454+
bioms[biom_fn] = [a, biom]
455+
456+
for fn, (a, fp) in bioms.items():
457+
aname = basename(fp["fp"])
458+
nname = f'{a.id}_{aname}'
459+
nfile = join(td, nname)
460+
copyfile(fp['fp'], nfile)
461+
files.append(nfile)
462+
463+
hname = ''
464+
if aname in human_names:
465+
hname = human_names[aname]
466+
readme.append(f'{nname}\t{hname}')
467+
468+
for an in a.ancestors.nodes():
469+
p = an.processing_parameters
470+
if p is not None:
471+
c = p.command
472+
cn = c.name
473+
s = c.software
474+
sn = s.name
475+
sv = s.version
476+
pd = p.dump()
477+
readme.append(f'\t{cn}\t{sn}\t{sv}\t{pd}')
478+
479+
if coverages is not None:
480+
aname = basename(fp["fp"])
481+
nfile = join(td, aname)
482+
copyfile(fp['fp'], nfile)
483+
files.append(nfile)
484+
485+
fn = join(td, 'README.txt')
486+
with open(fn, 'w') as fp:
487+
fp.write('\n'.join(readme))
488+
files.append(fn)
489+
490+
zp_fn = f'data_release_{pid}_{date}.zip'
491+
zp = BytesIO()
492+
with ZipFile(zp, 'w') as zipf:
493+
for fp in files:
494+
zipf.write(fp, basename(fp))
495+
496+
self.set_header('Content-Type', 'application/zip')
497+
self.set_header("Content-Disposition", f"attachment; filename={zp_fn}")
498+
self.write(zp.getvalue())
499+
zp.close()
500+
self.finish()
501+
502+
377503
class DownloadPublicHandler(BaseHandlerDownload):
378504
@coroutine
379505
@execute_as_transaction

qiita_pet/templates/study_ajax/prep_summary.html

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -447,6 +447,9 @@ <h4>
447447
{% end %}
448448
{% if editable %}
449449
<br/>
450+
{% if user_level in ('admin', 'wet-lab admin') %}
451+
<a class="btn btn-info" href="{% raw qiita_config.portal_dir %}/download_data_release_from_prep/{{prep_id}}"><span class="glyphicon glyphicon-download-alt"></span> Dowload Data Release</a>
452+
{% end %}
450453
{% if deprecated %}
451454
<a class="btn btn-warning" onclick="deprecate_preparation({{prep_id}}, false);"><span class="glyphicon glyphicon-pushpin"></span> Remove Deprecation</a>
452455
{% else%}

qiita_pet/webserver.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,8 @@
5555
DownloadHandler, DownloadStudyBIOMSHandler, DownloadRelease,
5656
DownloadRawData, DownloadEBISampleAccessions, DownloadEBIPrepAccessions,
5757
DownloadUpload, DownloadPublicHandler, DownloadPublicArtifactHandler,
58-
DownloadSampleInfoPerPrep, DownloadPrivateArtifactHandler)
58+
DownloadSampleInfoPerPrep, DownloadPrivateArtifactHandler,
59+
DownloadDataReleaseFromPrep)
5960
from qiita_pet.handlers.prep_template import (
6061
PrepTemplateHandler, PrepTemplateGraphHandler, PrepTemplateJobHandler)
6162
from qiita_pet.handlers.ontology import OntologyHandler
@@ -194,6 +195,8 @@ def __init__(self):
194195
(r"/software/", SoftwareHandler),
195196
(r"/workflows/", WorkflowsHandler),
196197
(r"/download/(.*)", DownloadHandler),
198+
(r"/download_data_release_from_prep/(.*)",
199+
DownloadDataReleaseFromPrep),
197200
(r"/download_study_bioms/(.*)", DownloadStudyBIOMSHandler),
198201
(r"/download_raw_data/(.*)", DownloadRawData),
199202
(r"/download_ebi_accessions/samples/(.*)",

0 commit comments

Comments
 (0)