def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['download_type'] = forms.ChoiceField( choices=[(d_type.download_type, d_type.label) for d_type in fetch_aristotle_downloaders()], widget=forms.RadioSelect) self.fields['items'].required = True
def extensions(request): content=[] aristotle_apps = fetch_aristotle_settings().get('CONTENT_EXTENSIONS', []) if aristotle_apps: for app_label in aristotle_apps: app=apps.get_app_config(app_label) try: app.about_url = reverse('%s:about' % app_label) except: pass # if there is no about URL, thats ok. content.append(app) content = list(set(content)) aristotle_downloads = fetch_aristotle_downloaders() downloads=[] if aristotle_downloads: for download in aristotle_downloads: downloads.append(download()) return render( request, "aristotle_mdr/static/extensions.html", {'content_extensions': content, 'download_extensions': downloads, } )
def build_downloaders(self, queryset): downloaders = fetch_aristotle_downloaders() from aristotle_mdr.utils.cached_querysets import register_queryset qs_uuid = register_queryset(self.filterset.qs.order_by('name'), 60 * 60) options: list = [] ids = [concept.id for concept in queryset] state_map = {v: k for k, v in MDR.STATES._identifier_map.items()} filter_kwargs = self.get_filterset_kwargs(self.filterset_class)['data'] for dl in downloaders: query = QueryDict(mutable=True) url = '{url}?{qstring}'.format(url=reverse( 'aristotle:registrationauthority_data_dictionary_download_options', kwargs={ "iid": self.registration_authority.pk, "download_type": dl.download_type, "state_name": state_map[int(filter_kwargs['status'])], "registration_date": filter_kwargs['registration_date'] }), qstring=query.urlencode()) options.append({'label': dl.label, 'url': url}) return options
def extensions(request): content=[] aristotle_apps = fetch_aristotle_settings().get('CONTENT_EXTENSIONS', []) if aristotle_apps: for app_label in aristotle_apps: app=apps.get_app_config(app_label) try: app.about_url = reverse('%s:about' % app_label) except: pass # if there is no about URL, thats ok. content.append(app) content = list(set(content)) aristotle_downloads = fetch_aristotle_downloaders() downloads=[] if aristotle_downloads: for download in aristotle_downloads: downloads.append(download()) return render( request, "aristotle_mdr/static/extensions.html", {'content_extensions': content, 'download_extensions': downloads, } )
def get_download_class(download_type: str): downloader_class = None dl_classes = fetch_aristotle_downloaders() for klass in dl_classes: if klass.download_type == download_type: downloader_class = klass return downloader_class
def bulk_download(request, download_type, items=None): r""" By default, ``aristotle_mdr.views.bulk_download`` is called whenever a URL matches the pattern defined in ``aristotle_mdr.urls_aristotle``:: bulk_download/(?P<download_type>[a-zA-Z0-9\-\.]+)/? This is passed into ``bulk_download`` which takes the items GET arguments from the request and determines if a user has permission to view the requested items. For any items the user can download they are exported in the desired format as described in ``aristotle_mdr.views.download``. If the requested module is able to be imported, ``downloader.py`` from the given module is imported, this file **MUST** have a ``bulk_download`` function defined which returns a Django ``HttpResponse`` object of some form. """ # downloadOpts = fetch_aristotle_settings().get('DOWNLOADERS', []) items = request.GET.getlist('items') download_opts = fetch_aristotle_downloaders() get_params = request.GET.copy() get_params.setdefault('bulk', True) for kls in download_opts: if download_type == kls.download_type: try: # properties for download template properties = kls.get_bulk_download_config(request, items) if get_params.get('public', False): properties['user'] = False res = kls.bulk_download.delay(properties, items) if not properties.get('title', ''): properties['title'] = 'Auto-generated document' get_params.pop('title') get_params.setdefault('title', properties['title']) response = redirect('{}?{}'.format( reverse('aristotle:preparing_download', args=[download_type]), urlencode(get_params, True) )) download_key = request.session.get(download_utils.get_download_session_key(get_params, download_type)) if download_key: async_result(download_key).forget() request.session[download_utils.get_download_session_key(get_params, download_type)] = res.id return response except TemplateDoesNotExist: debug = getattr(settings, 'DEBUG') if debug: raise # Maybe another downloader can serve this up continue raise Http404
def downloadMenu(item): """ Returns the complete download menu for a partcular item. It accepts the id of the item to make a download menu for, and the id must be of an item that can be downloaded, otherwise the links will show, but not work. For example:: {% downloadMenu item %} """ from django.template.loader import get_template downloadOpts = fetch_aristotle_downloaders() from aristotle_mdr.utils import get_download_template_path_for_item downloadsForItem = [] app_label = item._meta.app_label model_name = item._meta.model_name for d in downloadOpts: download_type = d.download_type item_register = d.metadata_register if type(item_register) is not str: if item_register.get(app_label, []) == '__all__': downloadsForItem.append(d) elif model_name in item_register.get(app_label, []): downloadsForItem.append(d) else: if item_register == '__all__': downloadsForItem.append(d) elif item_register == '__template__': try: get_template( get_download_template_path_for_item( item, download_type)) downloadsForItem.append(d) except template.TemplateDoesNotExist: pass # This is ok. except: # TODO: Should probably do something with this error pass # Something very bad has happened in the template. return get_template("aristotle_mdr/helpers/downloadMenu.html").render({ 'item': item, 'download_options': downloadsForItem, })
def downloadMenu(item): """ Returns the complete download menu for a partcular item. It accepts the id of the item to make a download menu for, and the id must be of an item that can be downloaded, otherwise the links will show, but not work. For example:: {% downloadMenu item %} """ downloadOpts = fetch_aristotle_downloaders() from aristotle_mdr.utils import get_download_template_path_for_item downloadsForItem = [] app_label = item._meta.app_label model_name = item._meta.model_name for d in downloadOpts: template_type = d.template_type item_register = d.metadata_register if type(item_register) is not str: if item_register.get(app_label, []) == '__all__': downloadsForItem.append(d) elif model_name in item_register.get(app_label, []): downloadsForItem.append(d) else: if item_register == '__all__': downloadsForItem.append(d) elif item_register == '__template__': try: get_template( get_download_template_path_for_item( item, template_type)) downloadsForItem.append(d) except template.TemplateDoesNotExist: pass # This is ok. dlOptionsForItem = [] for dl_class in downloadsForItem: dlOptionsForItem.append(dl_class.get_class_info()) return { 'item': item, 'download_options': dlOptionsForItem, }
def downloadMenu(item): """ Returns the complete download menu for a partcular item. It accepts the id of the item to make a download menu for, and the id must be of an item that can be downloaded, otherwise the links will show, but not work. For example:: {% downloadMenu item %} """ from django.template.loader import get_template downloadOpts = fetch_aristotle_downloaders() from aristotle_mdr.utils import get_download_template_path_for_item downloadsForItem = [] app_label = item._meta.app_label model_name = item._meta.model_name for d in downloadOpts: download_type = d.download_type item_register = d.metadata_register if type(item_register) is not str: if item_register.get(app_label, []) == '__all__': downloadsForItem.append(d) elif model_name in item_register.get(app_label, []): downloadsForItem.append(d) else: if item_register == '__all__': downloadsForItem.append(d) elif item_register == '__template__': try: get_template(get_download_template_path_for_item(item, download_type)) downloadsForItem.append(d) except template.TemplateDoesNotExist: pass # This is ok. except: # TODO: Should probably do something with this error pass # Something very bad has happened in the template. return get_template( "aristotle_mdr/helpers/downloadMenu.html").render( {'item': item, 'download_options': downloadsForItem, } )
def extensions(request): content = [] aristotle_apps = fetch_aristotle_settings().get('CONTENT_EXTENSIONS', []) if aristotle_apps: for app_label in aristotle_apps: app = apps.get_app_config(app_label) try: app.about_url = reverse('%s:about' % app_label) except: pass # If there is no "about" URL, that's ok. content.append(app) content = list(set(content)) aristotle_downloaders = fetch_aristotle_downloaders() download_extensions = [dldr.get_class_info() for dldr in aristotle_downloaders] return render( request, "aristotle_mdr/static/extensions.html", {'content_extensions': content, 'download_extensions': download_extensions} )
def bulk_download(request, download_type, items=None): r""" By default, ``aristotle_mdr.views.bulk_download`` is called whenever a URL matches the pattern defined in ``aristotle_mdr.urls_aristotle``:: bulk_download/(?P<download_type>[a-zA-Z0-9\-\.]+)/? This is passed into ``bulk_download`` which takes the items GET arguments from the request and determines if a user has permission to view the requested items. For any items the user can download they are exported in the desired format as described in ``aristotle_mdr.views.download``. If the requested module is able to be imported, ``downloader.py`` from the given module is imported, this file **MUST** have a ``bulk_download`` function defined which returns a Django ``HttpResponse`` object of some form. """ items = [] for iid in request.GET.getlist('items'): item = MDR._concept.objects.get_subclass(pk=iid) if item.can_view(request.user): items.append(item) # downloadOpts = fetch_aristotle_settings().get('DOWNLOADERS', []) downloadOpts = fetch_aristotle_downloaders() for kls in downloadOpts: if download_type == kls.download_type: try: return kls.bulk_download(request, items) except TemplateDoesNotExist: debug = getattr(settings, 'DEBUG') if debug: raise # Maybe another downloader can serve this up continue raise Http404
def download(request, download_type, iid=None): r""" By default, ``aristotle_mdr.views.download`` is called whenever a URL matches the pattern defined in ``aristotle_mdr.urls_aristotle``:: download/(?P<download_type>[a-zA-Z0-9\-\.]+)/(?P<iid>\d+)/? This is passed into ``download`` which resolves the item id (``iid``), and determines if a user has permission to view the requested item with that id. If a user is allowed to download this file, ``download`` iterates through each download type defined in ``ARISTOTLE_SETTINGS.DOWNLOADERS``. A download option tuple takes the following form form:: ('file_type','display_name','font_awesome_icon_name','module_name'), With ``file_type`` allowing only ASCII alphanumeric and underscores, ``display_name`` can be any valid python string, ``font_awesome_icon_name`` can be any Font Awesome icon and ``module_name`` is the name of the python module that provides a downloader for this file type. For example, the Aristotle-PDF with Aristotle-MDR is a PDF downloader which has the download definition tuple:: ('pdf','PDF','fa-file-pdf-o','aristotle_pdr'), Where a ``file_type`` multiple is defined multiple times, **the last matching instance in the tuple is used**. Next, the module that is defined for a ``file_type`` is dynamically imported using ``exec``, and is wrapped in a ``try: except`` block to catch any exceptions. If the ``module_name`` does not match the regex ``^[a-zA-Z0-9\_]+$`` ``download`` raises an exception. If the module is able to be imported, ``downloader.py`` from the given module is imported, this file **MUST** have a ``download`` function defined which returns a Django ``HttpResponse`` object of some form. """ item = MDR._concept.objects.get_subclass(pk=iid) item = get_if_user_can_view(item.__class__, request.user, iid) if not item: if request.user.is_anonymous(): return redirect(reverse('friendly_login') + '?next=%s' % request.path) else: raise PermissionDenied get_params = request.GET.copy() get_params.setdefault('items', iid) download_opts = fetch_aristotle_downloaders() for kls in download_opts: if download_type == kls.download_type: try: # properties requested for the file requested kls.item = item properties = kls.get_download_config(request, iid) if get_params.get('public', False): properties['user'] = False res = kls.download.delay(properties, iid) get_params.setdefault('title', properties.get('title', 'Auto-Generated Document')) response = redirect('{}?{}'.format( reverse('aristotle:preparing_download', args=[download_type]), urlencode(get_params, True) )) download_key = request.session.get(download_utils.get_download_session_key(get_params, download_type)) if download_key: async_result(download_key).forget() request.session[download_utils.get_download_session_key(get_params, download_type)] = res.id return response except TemplateDoesNotExist: debug = getattr(settings, 'DEBUG') if debug: raise # Maybe another downloader can serve this up continue raise Http404
def __init__(self, *args, **kwargs): super(BulkDownloadForm, self).__init__(*args, **kwargs) self.fields['download_type'] = forms.ChoiceField( choices=[(d_type.download_type, d_type.label) for d_type in fetch_aristotle_downloaders()], widget=forms.RadioSelect)