Example #1
0
def upload_view(request):
    """
    :param request: Django Request
    :return: Http Response
    """
    if preferences.Setting.active_release is None:
        messages.error(
            request,
            mark_safe(
                _("Active release not set: you cannot publish your "
                  "repository without an active release. <a href=\"%s\">Add Release</a>"
                  ) % reverse("admin:WEIPDCRM_release_add")))
    # POST
    if request.method == 'POST':
        # action: upload
        if 'action' in request.POST and request.POST['action'] == 'upload':
            if 'ajax' in request.POST and request.POST['ajax'] == 'true':
                result_dict = {}
                if 'job' in request.POST:
                    job_id = request.POST['job']
                    result_dict = {}
                    m_job = queues.get_queue('high').fetch_job(job_id)
                    if m_job is None:
                        result_dict.update({
                            'result': False,
                            'msg': _('No such job'),
                            'job': None
                        })
                    else:
                        result_dict.update({
                            'result': True,
                            'msg': '',
                            'job': {
                                'id': m_job.id,
                                'is_failed': m_job.is_failed,
                                'is_finished': m_job.is_finished,
                                'result': m_job.result
                            }
                        })
                else:
                    form = UploadForm(request.POST, request.FILES)
                    if form.is_valid():
                        # Handle File
                        if settings.ENABLE_REDIS is True:
                            m_job = handle_uploaded_file(request)
                            result_dict.update({
                                'status':
                                True,
                                'msg':
                                _('Upload succeed, proceeding...'),
                                'job': {
                                    'id': m_job.id,
                                    'result': m_job.result
                                }
                            })
                        else:
                            m_result = handle_uploaded_file(request)
                            succeed = m_result['success']
                            if succeed:
                                result_dict.update({
                                    'status':
                                    True,
                                    'msg':
                                    _('Upload succeed, proceeding...'),
                                    'job': {
                                        'id': None,
                                        'result': {
                                            'version': m_result['version']
                                        }
                                    }
                                })
                            else:
                                result_dict.update({
                                    'status': False,
                                    'msg': m_result['exception'],
                                    'job': None
                                })
                    else:
                        result_dict.update({
                            'status':
                            False,
                            'msg':
                            _('Upload failed, invalid form.'),
                            'job':
                            None
                        })
                return HttpResponse(json.dumps(result_dict),
                                    content_type='application/json')
            else:
                # render upload result
                form = UploadForm(request.POST, request.FILES)
                if form.is_valid():
                    # Handle File
                    if settings.ENABLE_REDIS is True:
                        m_job = handle_uploaded_file(request)
                        job_id = m_job.id
                        msg = _('Upload succeed, proceeding...')
                    else:
                        m_result = handle_uploaded_file(request)
                        if m_result["success"] is True:
                            return redirect(
                                Version.objects.get(id=int(
                                    m_result["version"])).get_admin_url())
                        else:
                            job_id = ''
                            msg = m_result["exception"]
                else:
                    job_id = ''
                    msg = _('Upload failed, invalid form.')
                form = UploadForm()
                context = admin.site.each_context(request)
                context.update({
                    'title': _('Upload New Packages'),
                    'form': form,
                    'job_id': job_id,
                    'msg': msg
                })
                template = 'admin/upload.html'
                return render(request, template, context)
        # action: async-import
        elif 'action' in request.POST and request.POST[
                'action'] == 'async-import':
            if not settings.ENABLE_REDIS:
                messages.error(
                    request,
                    mark_safe(
                        _("To use this action, you must enable <b>Redis Queue</b>."
                          )))
            else:
                items = os.listdir(settings.UPLOAD_ROOT)
                import_items = []
                for item in items:
                    if item[-4:] == ".deb":
                        item_path = os.path.join(settings.UPLOAD_ROOT, item)
                        import_items.append(item_path)
                if len(import_items) > 0:
                    temp_root = settings.TEMP_ROOT
                    if not os.path.exists(temp_root):
                        try:
                            mkdir_p(temp_root)
                        except OSError:
                            pass
                    import_jobs = []
                    queue = django_rq.get_queue('high')
                    for import_item in import_items:
                        package_temp_path = os.path.join(
                            temp_root,
                            str(uuid.uuid1()) + '.deb')
                        shutil.copy(import_item, package_temp_path)
                        os.chmod(package_temp_path, 0o755)
                        import_job = queue.enqueue(handle_uploaded_package,
                                                   package_temp_path)
                        import_jobs.append(import_job)
                    if len(import_jobs) == 1:
                        messages.info(
                            request,
                            mark_safe(
                                _("%(job_count)s package importing job have been added to the \"<a href=\"%(jobs)s\">high</a>\" queue."
                                  ).format(
                                      job_count=str(len(import_jobs)),
                                      jobs=reverse('rq_jobs', args=(1, )),
                                  )))
                    else:
                        messages.info(
                            request,
                            mark_safe(
                                _("%(job_count)s package importing jobs have been added to the \"<a href=\"%(jobs)s\">high</a>\" queue."
                                  ).format(
                                      job_count=str(len(import_jobs)),
                                      jobs=reverse('rq_jobs', args=(1, )),
                                  )))
                else:
                    messages.warning(request,
                                     _("There is no package to import."))
            return redirect('upload')
    # GET
    elif request.method == 'GET':
        form = UploadForm()
        context = admin.site.each_context(request)
        context.update({
            'title': _('Upload New Packages'),
            'form': form,
            'job_id': ''
        })
        template = 'admin/upload.html'
        return render(request, template, context)
Example #2
0
File: upload.py Project: jhvip/DCRM
def upload_view(request):
    if preferences.Setting.active_release is None:
        messages.error(
            request,
            _("Active release not set: you cannot publish your "
              "repository without an active release."))
    """
    :param request: Django Request
    :return: Http Response
    """
    if request.method == 'POST':
        # Save Package File To Resource Base
        if 'ajax' in request.POST and request.POST['ajax'] == 'true':
            result_dict = {}
            if 'job' in request.POST:
                job_id = request.POST['job']
                result_dict = {}
                m_job = queues.get_queue('high').fetch_job(job_id)
                if m_job is None:
                    result_dict.update({
                        'result': False,
                        'msg': _('No such job'),
                        'job': None
                    })
                else:
                    result_dict.update({
                        'result': True,
                        'msg': '',
                        'job': {
                            'id': m_job.id,
                            'is_failed': m_job.is_failed,
                            'is_finished': m_job.is_finished,
                            'result': m_job.result
                        }
                    })
            else:
                form = UploadForm(request.POST, request.FILES)
                if form.is_valid():
                    # Handle File
                    if settings.ENABLE_REDIS is True:
                        m_job = handle_uploaded_file(request)
                        result_dict.update({
                            'status':
                            True,
                            'msg':
                            _('Upload succeed, proceeding...'),
                            'job': {
                                'id': m_job.id,
                                'result': m_job.result
                            }
                        })
                    else:
                        m_result = handle_uploaded_file(request)
                        succeed = m_result['success']
                        if succeed:
                            result_dict.update({
                                'status':
                                True,
                                'msg':
                                _('Upload succeed, proceeding...'),
                                'job': {
                                    'id': None,
                                    'result': {
                                        'version': m_result['version']
                                    }
                                }
                            })
                        else:
                            result_dict.update({
                                'status': False,
                                'msg': m_result['exception'],
                                'job': None
                            })
                else:
                    result_dict.update({
                        'status': False,
                        'msg': _('Upload failed, invalid form.'),
                        'job': None
                    })
            return HttpResponse(json.dumps(result_dict),
                                content_type='application/json')
        else:
            # render upload result
            form = UploadForm(request.POST, request.FILES)
            if form.is_valid():
                # Handle File
                if settings.ENABLE_REDIS is True:
                    m_job = handle_uploaded_file(request)
                    job_id = m_job.id
                    msg = _('Upload succeed, proceeding...')
                else:
                    m_result = handle_uploaded_file(request)
                    if m_result["success"] is True:
                        return redirect(
                            Version.objects.get(
                                id=int(m_result["version"])).get_admin_url())
                    else:
                        job_id = ''
                        msg = m_result["exception"]
            else:
                job_id = ''
                msg = _('Upload failed, invalid form.')
            form = UploadForm()
            context = admin.site.each_context(request)
            context.update({
                'title': _('Upload'),
                'form': form,
                'job_id': job_id,
                'msg': msg
            })
            template = 'admin/upload.html'
            return render(request, template, context)
    else:
        form = UploadForm()
        context = admin.site.each_context(request)
        context.update({'title': _('Upload'), 'form': form, 'job_id': ''})
        template = 'admin/upload.html'
        return render(request, template, context)