Exemplo n.º 1
0
def plugin_upload(request):
    """
    This is the "single step" way to create new plugins:
    uploads a package and creates a new Plugin with a new PluginVersion
    """
    if request.method == 'POST':
        form = PackageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                plugin_data = {
                    'name': form.cleaned_data['name'],
                    'package_name': form.cleaned_data['package_name'],
                    'description': form.cleaned_data['description'],
                    'created_by': request.user,
                    'published': request.user.has_perm('plugins.can_publish'),
                    'icon': form.cleaned_data['icon_file'],
                }
                new_plugin = Plugin(**plugin_data)
                new_plugin.save()
                plugin_notify(new_plugin)

                version_data = {
                    'plugin': new_plugin,
                    'min_qg_version': form.cleaned_data['qgisMinimumVersion'],
                    'version': form.cleaned_data['version'],
                    'current': True,
                    'created_by': request.user,
                    'package': form.cleaned_data['package']
                }
                new_version = PluginVersion(**version_data)
                new_version.save()
                msg = _("The Plugin has been successfully created.")
                messages.success(request, msg, fail_silently=True)
                if not request.user.has_perm('plugins.can_publish'):
                    msg = _(
                        "Your plugin is awaiting approval from a staff member and will be published as soon as possible."
                    )
                    messages.warning(request, msg, fail_silently=True)
            except (IntegrityError, ValidationError), e:
                messages.error(request, e, fail_silently=True)
                if not new_plugin.pk:
                    return render_to_response(
                        'plugins/plugin_upload.html', {'form': form},
                        context_instance=RequestContext(request))
            return HttpResponseRedirect(new_plugin.get_absolute_url())
Exemplo n.º 2
0
def plugin_upload(request):
    """
    This is the "single step" way to create new plugins:
    uploads a package and creates a new Plugin with a new PluginVersion
    """
    if request.method == 'POST':
        form = PackageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                plugin_data = {
                    'name'              : form.cleaned_data['name'],
                    'package_name'      : form.cleaned_data['package_name'],
                    'description'       : form.cleaned_data['description'],
                    'created_by'        : request.user,
                    'published'         : request.user.has_perm('plugins.can_publish'),
                    'icon'              : form.cleaned_data['icon_file'],
                }

                #import ipy; ipy.shell()

                new_plugin = Plugin(**plugin_data)
                new_plugin.save()
                plugin_notify(new_plugin)

                version_data =  {
                    'plugin'            : new_plugin,
                    'min_qg_version'    : form.cleaned_data['qgisMinimumVersion'],
                    'version'           : form.cleaned_data['version'],
                    'current'           : True,
                    'created_by'        : request.user,
                    'package'           : form.cleaned_data['package']
                }
                new_version = PluginVersion(**version_data)
                new_version.save()
                msg = _("The Plugin has been successfully created.")
                messages.success(request, msg, fail_silently=True)
            except (IntegrityError, ValidationError), e:
                messages.error(request, e, fail_silently=True)
                if not new_plugin.pk:
                    return render_to_response('plugins/plugin_upload.html', { 'form' : form }, context_instance=RequestContext(request))
            return HttpResponseRedirect(new_plugin.get_absolute_url())
Exemplo n.º 3
0
def plugin_upload(request):
    """
    This is the "single step" way to create new plugins:
    uploads a package and creates a new Plugin with a new PluginVersion
    """
    if request.method == 'POST':
        form = PackageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                plugin_data = {
                    'name'              : form.cleaned_data['name'],
                    'package_name'      : form.cleaned_data['package_name'],
                    'description'       : form.cleaned_data['description'],
                    'created_by'        : request.user,
                    'icon'              : form.cleaned_data['icon_file'],
                }
                new_plugin = Plugin(**plugin_data)
                new_plugin.save()
                plugin_notify(new_plugin)

                version_data =  {
                    'plugin'            : new_plugin,
                    'min_qg_version'    : form.cleaned_data['qgisMinimumVersion'],
                    'version'           : form.cleaned_data['version'],
                    'created_by'        : request.user,
                    'package'           : form.cleaned_data['package'],
                    'approved'          : request.user.has_perm('plugins.can_approve'),
                    'experimental'      : form.cleaned_data['experimental'],
                }
                new_version = PluginVersion(**version_data)
                new_version.save()
                msg = _("The Plugin has been successfully created.")
                messages.success(request, msg, fail_silently=True)
                if not request.user.has_perm('plugins.can_approve'):
                    msg = _("Your plugin is awaiting approval from a staff member and will be approved as soon as possible.")
                    messages.warning(request, msg, fail_silently=True)
            except (IntegrityError, ValidationError), e:
                messages.error(request, e, fail_silently=True)
                if not new_plugin.pk:
                    return render_to_response('plugins/plugin_upload.html', { 'form' : form }, context_instance=RequestContext(request))
            return HttpResponseRedirect(new_plugin.get_absolute_url())
Exemplo n.º 4
0
 def add_plugin(self, dock_image_name):
     """
     Register/add a new plugin to the system.
     """
     # get representation from the corresponding app
     app_repr = self.get_plugin_app_representation(dock_image_name)
     name = self.get_plugin_name(app_repr)
     # check wether the plugin already exist
     existing_plugin_names = [plugin.name for plugin in Plugin.objects.all()]
     if name in existing_plugin_names:
         raise ValueError("Plugin '%s' already exists in the system" % name)
     # add plugin to the db
     plugin = Plugin()
     plugin.name = name
     plugin.dock_image = dock_image_name
     plugin.type = app_repr['type']
     plugin.save()
     # add plugin's parameters to the db
     params = app_repr['parameters']
     for param in params:
         self._save_plugin_param(plugin, param)
Exemplo n.º 5
0
def plugin_upload(request):
    """
    This is the "single step" way to create new plugins:
    uploads a package and creates a new Plugin with a new PluginVersion
    can also update an existing plugin
    """
    if request.method == 'POST':
        form = PackageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                plugin_data = {
                    'name'              : form.cleaned_data['name'],
                    'package_name'      : form.cleaned_data['package_name'],
                    'description'       : form.cleaned_data['description'],
                    'created_by'        : request.user,
                    'author'            : form.cleaned_data['author'],
                    'email'             : form.cleaned_data['email'],
                    'created_by'        : request.user,
                    'icon'              : form.cleaned_data['icon_file'],
                }

                # Gets existing plugin
                try:
                    plugin = Plugin.objects.get(package_name=plugin_data['package_name'])
                    if not check_plugin_access(request.user, plugin):
                        return render_to_response('plugins/plugin_permission_deny.html', {}, context_instance=RequestContext(request))
                    # Apply new values
                    plugin.name         = plugin_data['name']
                    plugin.description  = plugin_data['description']
                    plugin.author       = plugin_data['author']
                    plugin.email        = plugin_data['email']
                    is_new = False
                except Plugin.DoesNotExist:
                    plugin = Plugin(**plugin_data)
                    is_new = True

                # Check icon, don't change if not valid
                if plugin_data['icon']:
                    plugin.icon         = plugin_data['icon']

                # Server is optional
                plugin.server = form.cleaned_data.get('server', False)

                # Other optional fields
                warnings = []

                if form.cleaned_data.get('homepage'):
                    plugin.homepage = form.cleaned_data.get('homepage')
                elif not plugin.homepage:
                    warnings.append(_('<strong>homepage</strong> field is empty, this field is not required but is recommended, please consider adding it to metadata.'))
                if form.cleaned_data.get('tracker'):
                    plugin.tracker = form.cleaned_data.get('tracker')
                elif not plugin.tracker:
                    raise ValidationError(_('"tracker" metadata is required! Please add it to <code>metadata.txt</code>.'))
                if form.cleaned_data.get('repository'):
                    plugin.repository = form.cleaned_data.get('repository')
                elif not plugin.repository:
                    raise ValidationError(_('"repository" metadata is required! Please add it to <code>metadata.txt</code>.'))
                if form.cleaned_data.get('about'):
                    plugin.about = form.cleaned_data.get('about')
                elif not plugin.about:
                    raise ValidationError(_('"about" metadata is required! Please add it to <code>metadata.txt</code>.'))


                # Save main Plugin object
                plugin.save()

                if is_new:
                    plugin_notify(plugin)

                # Takes care of tags
                if form.cleaned_data.get('tags'):
                    plugin.tags.set(*[t.strip().lower() for t in form.cleaned_data.get('tags').split(',')])

                version_data =  {
                    'plugin'            : plugin,
                    'min_qg_version'    : form.cleaned_data.get('qgisMinimumVersion'),
                    'max_qg_version'    : form.cleaned_data.get('qgisMaximumVersion'),
                    'version'           : form.cleaned_data.get('version'),
                    'created_by'        : request.user,
                    'package'           : form.cleaned_data.get('package'),
                    'approved'          : request.user.has_perm('plugins.can_approve') or plugin.approved,
                    'experimental'      : form.cleaned_data.get('experimental'),
                    'changelog'         : form.cleaned_data.get('changelog', ''),
                    'external_deps'     : form.cleaned_data.get('external_deps', ''),
                }

                new_version = PluginVersion(**version_data)
                new_version.save()
                msg = _("The Plugin has been successfully created.")
                messages.success(request, msg, fail_silently=True)
                if not new_version.approved:
                    msg = _("Your plugin is awaiting approval from a staff member and will be approved as soon as possible.")
                    warnings.append(msg)
                    if not is_new:
                        version_notify(new_version)
                if not  form.cleaned_data.get('metadata_source') == 'metadata.txt':
                    msg = _("Your plugin does not contain a metadata.txt file, metadata have been read from the __init__.py file. This is deprecated and its support will eventually cease.")
                    warnings.append(msg)

                # Grouped messages:
                if warnings:
                    messages.warning(request, _('<p><strong>Warnings:</strong></p>') + '\n'.join(["<p>%s</p>" % unicode(w) for w in warnings]), fail_silently=True)


            except (IntegrityError, ValidationError, DjangoUnicodeDecodeError), e:
                connection.close()
                messages.error(request, e, fail_silently=True)
                if not plugin.pk:
                    return render_to_response('plugins/plugin_upload.html', { 'form' : form }, context_instance=RequestContext(request))
            return HttpResponseRedirect(plugin.get_absolute_url())
Exemplo n.º 6
0
def autoimport_repo(request, name):
    repo = get_object_or_404(GitRepository, name=name)
    path = os.path.join(MEDIA_ROOT, 'repositories', '%s' % repo.name)
    if request.method == "POST":
        checkbox_prefix = 'import_plugin_'
        plugins = []
        for name, value in request.POST.items():
            if not name.startswith(checkbox_prefix):
                continue
            assert plugin_matcher.match(name[len(checkbox_prefix):])
            name = name[len(checkbox_prefix):]
            try:
                Plugin.objects.filter(name=name).get()
                errors.append('Plugin %s already exists in the database.')
                continue
            except ObjectDoesNotExist:
                pass
            plugin_path = os.path.join(path, name)
            try:
                readme = open(os.path.join(plugin_path, 'README.txt'), 'r').read()
            except IOError:
                try:
                    readme = open(os.path.join(plugin_path, 'README'), 'r').read()
                except:
                    readme = 'This plugin has no description.'
            plugin = Plugin(
                    author=request.user,
                    name=name,
                    short_description=readme[0:511].split('\n\n')[0],
                    description=readme,
                    git_repo=repo.url)
            plugins.append(plugin)
        # If everything was fine
        for plugin in plugins:
            plugin.save()
        return redirect('plugins_admin_index')

    else:
        timedelta = datetime.datetime.now() - repo.latest_fetch
        if timedelta.days * 86400 + timedelta.seconds > 3600:
            os.system('cd %s && git pull' % path)
            repo.latest_fetch = datetime.datetime.now()
            repo.save()
        raw_list = os.listdir(path)
        raw_list.sort()
        plugins = []
        class Container:
            pass
        for item in raw_list:
            if os.path.isfile(os.path.join(path, item)) or not plugin_matcher.match(item):
                continue
            plugin = Container()
            plugin.name = item
            try:
                plugin.in_database = Plugin.objects.filter(name=item).get()
            except ObjectDoesNotExist:
                pass
            plugins.append(plugin)
        context = {'user': request.user, 'repository': repo, 'plugins': plugins}
        context.update(csrf(request))
        return render_to_response('plugins/autoimport/list.tpl', context)
Exemplo n.º 7
0
    def add_plugin(self, dock_image_name):
        """
        Register/add a new plugin to the system.
        """
        # get representation from the corresponding app
        app_repr = self.get_plugin_app_representation(dock_image_name)
        name = self.get_plugin_name(app_repr)
        max_cpu_limit, min_cpu_limit                 = self.get_cpu_limit(app_repr)
        max_memory_limit, min_memory_limit           = self.get_memory_limit(app_repr)
        max_number_of_workers, min_number_of_workers = self.get_number_of_workers(app_repr)
        max_gpu_limit, min_gpu_limit                 = self.get_gpu_limit(app_repr)

        # check wether the plugin already exist
        existing_plugin_names = [plugin.name for plugin in Plugin.objects.all()]
        if name in existing_plugin_names:
            raise ValueError("Plugin '%s' already exists in the system" % name)

        # add plugin to the db
        plugin = Plugin()
        plugin.name = name
        plugin.dock_image = dock_image_name
        plugin.type          = app_repr['type']
        plugin.authors       = app_repr['authors']
        plugin.title         = app_repr['title']
        plugin.category      = app_repr['category']
        plugin.description   = app_repr['description']
        plugin.documentation = app_repr['documentation']
        plugin.license       = app_repr['license']
        plugin.version       = app_repr['version']
        plugin.max_cpu_limit         = self.insert_default(max_cpu_limit, CPUInt(Plugin.maxint))
        plugin.min_cpu_limit         = self.insert_default(min_cpu_limit,
                                                           Plugin.defaults['cpu_limit'])
        plugin.max_memory_limit      = self.insert_default(max_memory_limit, MemoryInt(Plugin.maxint))
        plugin.min_memory_limit      = self.insert_default(min_memory_limit,
                                                           Plugin.defaults['memory_limit'])
        plugin.max_number_of_workers = self.insert_default(max_number_of_workers, Plugin.maxint)
        plugin.min_number_of_workers = self.insert_default(min_number_of_workers, 1)
        plugin.max_gpu_limit         = self.insert_default(max_gpu_limit, Plugin.maxint)
        plugin.min_gpu_limit         = self.insert_default(min_gpu_limit, 0)
        plugin.save()

        # add plugin's parameters to the db
        params = app_repr['parameters']
        for param in params:
            self._save_plugin_param(plugin, param)
Exemplo n.º 8
0
def plugin_upload(request):
    """
    This is the "single step" way to create new plugins:
    uploads a package and creates a new Plugin with a new PluginVersion
    can also update an existing plugin
    """
    if request.method == 'POST':
        form = PackageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                plugin_data = {
                    'name': form.cleaned_data['name'],
                    'package_name': form.cleaned_data['package_name'],
                    'description': form.cleaned_data['description'],
                    'created_by': request.user,
                    'icon': form.cleaned_data['icon_file'],
                }

                # Gets existing plugin
                try:
                    plugin = Plugin.objects.get(
                        package_name=plugin_data['package_name'])
                    # Apply new values
                    plugin.name = plugin_data['name']
                    plugin.description = plugin_data['description']
                    plugin.icon = plugin_data['icon']
                    is_new = False
                except Plugin.DoesNotExist:
                    plugin = Plugin(**plugin_data)
                    is_new = True

                # Other optional fields
                if form.cleaned_data.get('homepage'):
                    plugin.homepage = form.cleaned_data.get('homepage')
                elif not plugin.homepage:
                    messages.warning(
                        request,
                        _('Homepage field is empty, this field is not required but is recommended, please consider adding it to metadata.'
                          ),
                        fail_silently=True)
                if form.cleaned_data.get('tracker'):
                    plugin.tracker = form.cleaned_data.get('tracker')
                elif not plugin.tracker:
                    messages.warning(
                        request,
                        _('Tracker field is empty, this field is not required but is recommended, please consider adding it to metadata.'
                          ),
                        fail_silently=True)
                if form.cleaned_data.get('repository'):
                    plugin.repository = form.cleaned_data.get('repository')
                elif not plugin.repository:
                    messages.warning(
                        request,
                        _('Repository field is empty, this field is not required but is recommended, please consider adding it to metadata.'
                          ),
                        fail_silently=True)

                plugin.save()

                if is_new:
                    plugin_notify(plugin)

                # Takes care of tags
                if form.cleaned_data.get('tags'):
                    plugin.tags.set(*form.cleaned_data.get('tags').split(','))

                version_data = {
                    'plugin':
                    plugin,
                    'min_qg_version':
                    form.cleaned_data.get('qgisMinimumVersion'),
                    'version':
                    form.cleaned_data.get('version'),
                    'created_by':
                    request.user,
                    'package':
                    form.cleaned_data.get('package'),
                    'approved':
                    request.user.has_perm('plugins.can_approve')
                    or plugin.approved,
                    'experimental':
                    form.cleaned_data.get('experimental'),
                    'changelog':
                    form.cleaned_data.get('changelog', ''),
                }

                new_version = PluginVersion(**version_data)
                new_version.save()
                msg = _("The Plugin has been successfully created.")
                messages.success(request, msg, fail_silently=True)
                if not request.user.has_perm('plugins.can_approve'):
                    msg = _(
                        "Your plugin is awaiting approval from a staff member and will be approved as soon as possible."
                    )
                    messages.warning(request, msg, fail_silently=True)
                if not form.cleaned_data.get(
                        'metadata_source') == 'metadata.txt':
                    msg = _(
                        "Your plugin does not contain a metadata.txt file, metadata have been read from the __init__.py file. This is deprecated and its support will eventually cease."
                    )
                    messages.warning(request, msg, fail_silently=True)

            except (IntegrityError, ValidationError), e:
                connection.close()
                messages.error(request, e, fail_silently=True)
                if not plugin.pk:
                    return render_to_response(
                        'plugins/plugin_upload.html', {'form': form},
                        context_instance=RequestContext(request))
            return HttpResponseRedirect(plugin.get_absolute_url())
Exemplo n.º 9
0
def plugin_upload(request):
    """
    This is the "single step" way to create new plugins:
    uploads a package and creates a new Plugin with a new PluginVersion
    can also update an existing plugin
    """
    if request.method == 'POST':
        form = PackageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                plugin_data = {
                    'name'              : form.cleaned_data['name'],
                    'package_name'      : form.cleaned_data['package_name'],
                    'description'       : form.cleaned_data['description'],
                    'created_by'        : request.user,
                    'icon'              : form.cleaned_data['icon_file'],
                }

                # Gets existing plugin
                try:
                    plugin = Plugin.objects.get(package_name=plugin_data['package_name'])
                    # Apply new values
                    plugin.name         = plugin_data['name']
                    plugin.description  = plugin_data['description']
                    plugin.icon         = plugin_data['icon']
                    is_new = False
                except Plugin.DoesNotExist:
                    plugin = Plugin(**plugin_data)
                    is_new = True

                # Other optional fields
                if form.cleaned_data.get('homepage'):
                    plugin.homepage = form.cleaned_data.get('homepage')
                elif not plugin.homepage:
                    messages.warning(request, _('Homepage field is empty, this field is not required but is recommended, please consider adding it to metadata.'), fail_silently=True)
                if form.cleaned_data.get('tracker'):
                    plugin.tracker = form.cleaned_data.get('tracker')
                elif not plugin.tracker:
                    messages.warning(request, _('Tracker field is empty, this field is not required but is recommended, please consider adding it to metadata.'), fail_silently=True)
                if form.cleaned_data.get('repository'):
                    plugin.repository = form.cleaned_data.get('repository')
                elif not plugin.repository:
                    messages.warning(request, _('Repository field is empty, this field is not required but is recommended, please consider adding it to metadata.'), fail_silently=True)

                plugin.save()

                if is_new:
                    plugin_notify(plugin)

                # Takes care of tags
                if form.cleaned_data.get('tags'):
                    plugin.tags.set(*form.cleaned_data.get('tags').split(','))

                version_data =  {
                    'plugin'            : plugin,
                    'min_qg_version'    : form.cleaned_data.get('qgisMinimumVersion'),
                    'version'           : form.cleaned_data.get('version'),
                    'created_by'        : request.user,
                    'package'           : form.cleaned_data.get('package'),
                    'approved'          : request.user.has_perm('plugins.can_approve') or plugin.approved,
                    'experimental'      : form.cleaned_data.get('experimental'),
                    'changelog'         : form.cleaned_data.get('changelog', ''),
                }

                new_version = PluginVersion(**version_data)
                new_version.save()
                msg = _("The Plugin has been successfully created.")
                messages.success(request, msg, fail_silently=True)
                if not request.user.has_perm('plugins.can_approve'):
                    msg = _("Your plugin is awaiting approval from a staff member and will be approved as soon as possible.")
                    messages.warning(request, msg, fail_silently=True)
                if not  form.cleaned_data.get('metadata_source') == 'metadata.txt':
                    msg = _("Your plugin does not contain a metadata.txt file, metadata have been read from the __init__.py file. This is deprecated and its support will eventually cease.")
                    messages.warning(request, msg, fail_silently=True)

            except (IntegrityError, ValidationError), e:
                connection.close()
                messages.error(request, e, fail_silently=True)
                if not plugin.pk:
                    return render_to_response('plugins/plugin_upload.html', { 'form' : form }, context_instance=RequestContext(request))
            return HttpResponseRedirect(plugin.get_absolute_url())