コード例 #1
0
ファイル: nav.py プロジェクト: BillTheBest/MetaNAS
    def __init__(self, *args, **kwargs):
        super(AdminAccount, self).__init__(*args, **kwargs)

        chpw = TreeNode('ChangePass')
        chpw.name = _('Change Password')
        chpw.type = 'openaccount'
        chpw.icon = u'ChangePasswordIcon'

        chad = TreeNode('ChangeAdmin')
        chad.name = _('Change Admin User')
        chad.type = 'openaccount'
        chad.icon = u'ChangeAdminIcon'
        self.append_children([chpw, chad])
コード例 #2
0
ファイル: nav.py プロジェクト: BillTheBest/MetaNAS
    def __init__(self, *args, **kwargs):
        super(AdminAccount, self).__init__(*args, **kwargs)

        chpw = TreeNode("ChangePass")
        chpw.name = _("Change Password")
        chpw.type = "openaccount"
        chpw.icon = u"ChangePasswordIcon"

        chad = TreeNode("ChangeAdmin")
        chad.name = _("Change Admin User")
        chad.type = "openaccount"
        chad.icon = u"ChangeAdminIcon"
        self.append_children([chpw, chad])
コード例 #3
0
ファイル: navtree.py プロジェクト: BillTheBest/MetaNAS
    def generate(self, request=None):
        """
        Tree Menu Auto Generate

        Every app listed at INSTALLED_APPS is scanned
        1st - app_name.forms is imported. All its objects/classes are scanned
            looking for ModelForm classes
        2nd - app_name.nav is imported. TreeNode classes are scanned for
            hard-coded menu entries or overwriting
        3rd - app_name.models is imported. models.Model classes are scanned,
        if a related ModelForm is found several entries are Added to the Menu
                - Objects
                - Add (Model)
                - View (Model)
        """

        self._generated = True
        self._navs.clear()
        tree_roots.clear()
        _childs_of = []
        for app in settings.INSTALLED_APPS:

            # If the app is listed at settings.BLACKLIST_NAV, skip it!
            if app in getattr(settings, 'BLACKLIST_NAV', []):
                continue

            # Thats the root node for the app tree menu
            nav = TreeRoot(app)

            modnav = self._get_module(app, 'nav')
            if hasattr(modnav, 'BLACKLIST'):
                BLACKLIST = modnav.BLACKLIST
            else:
                BLACKLIST = []

            if hasattr(modnav, 'ICON'):
                nav.icon = modnav.ICON

            if hasattr(modnav, 'NAME'):
                nav.name = modnav.NAME
            else:
                nav.name = self.titlecase(app)

            if modnav:
                modname = "%s.nav" % app
                for c in dir(modnav):
                    navc = getattr(modnav, c)
                    try:
                        subclass = issubclass(navc, TreeNode)
                    except TypeError:
                        continue
                    if navc.__module__ == modname and subclass:
                        obj = navc()

                        if obj.skip is True:
                            continue
                        if not obj.append_to:
                            self.register_option(obj, nav, replace=True)
                        else:
                            self._navs[obj.append_to + '.' + obj.gname] = obj

                tree_roots.register(nav)  # We register it to the tree root
                if hasattr(modnav, 'init'):
                    modnav.init(tree_roots, nav)

            else:
                log.debug("App %s has no nav.py module, skipping", app)
                continue

            modmodels = self._get_module(app, 'models')
            if modmodels:

                modname = '%s.models' % app
                for c in dir(modmodels):
                    model = getattr(modmodels, c)
                    try:
                        if not issubclass(model, models.Model) or \
                            model._meta.app_label != app:
                            continue
                    except TypeError:
                        continue

                    if c in BLACKLIST:
                        log.debug("Model %s from app %s blacklisted, skipping",
                            c,
                            app,
                            )
                        continue

                    if not(model.__module__ in (modname,
                                'metanasUI.' + modname) \
                            and model in self._modelforms
                          ):
                        log.debug("Model %s does not have a ModelForm", model)
                        continue

                    if model._admin.deletable is False:
                        navopt = TreeNode(str(model._meta.object_name),
                            name=model._meta.verbose_name,
                            model=c, app_name=app, type='dialog')
                        try:
                            navopt.kwargs = {'app': app, 'model': c, 'oid': \
                                model.objects.order_by("-id")[0].id}
                            navopt.view = 'freeadmin_model_edit'
                        except:
                            navopt.view = 'freeadmin_model_add'
                            navopt.kwargs = {'app': app, 'model': c}

                    else:
                        navopt = TreeNode(str(model._meta.object_name))
                        navopt.name = model._meta.verbose_name_plural
                        navopt.model = c
                        navopt.app_name = app
                        navopt.order_child = False

                    for key in model._admin.nav_extra.keys():
                        navopt.__setattr__(key,
                            model._admin.nav_extra.get(key))
                    if model._admin.icon_model is not None:
                        navopt.icon = model._admin.icon_model

                    if model._admin.menu_child_of is not None:
                        _childs_of.append((navopt, model))
                        reg = True
                    else:
                        reg = self.register_option(navopt, nav)

                    if reg and not navopt.type:

                        qs = model.objects.filter(
                            **model._admin.object_filters).order_by('-id')
                        if qs.count() > 0:
                            if model._admin.object_num > 0:
                                qs = qs[:model._admin.object_num]
                            for e in qs:
                                subopt = TreeNode('Edit')
                                subopt.type = 'editobject'
                                subopt.view = u'freeadmin_model_edit'
                                if model._admin.icon_object is not None:
                                    subopt.icon = model._admin.icon_object
                                subopt.model = c
                                subopt.app_name = app
                                subopt.kwargs = {
                                    'app': app,
                                    'model': c,
                                    'oid': e.id,
                                    }
                                try:
                                    subopt.name = unicode(e)
                                except:
                                    subopt.name = 'Object'
                                navopt.append_child(subopt)

                        # Node to add an instance of model
                        subopt = TreeNode('Add')
                        subopt.name = _(u'Add %s') % model._meta.verbose_name
                        subopt.view = u'freeadmin_model_add'
                        subopt.kwargs = {'app': app, 'model': c}
                        subopt.order = 500
                        subopt.type = 'dialog'
                        if model._admin.icon_add is not None:
                            subopt.icon = model._admin.icon_add
                        subopt.model = c
                        subopt.app_name = app
                        self.register_option(subopt, navopt)

                        # Node to view all instances of model
                        subopt = TreeNode('View')
                        subopt.name = _(u'View %s') % (
                            model._meta.verbose_name_plural,
                            )
                        subopt.view = u'freeadmin_model_datagrid'
                        if model._admin.icon_view is not None:
                            subopt.icon = model._admin.icon_view
                        subopt.model = c
                        subopt.app_name = app
                        subopt.kwargs = {'app': app, 'model': c}
                        subopt.order = 501
                        subopt.type = 'viewmodel'
                        self.register_option(subopt, navopt)

        nav = TreeRoot('display',
            name=_('Display System Processes'),
            action='displayprocs',
            icon='TopIcon')
        tree_roots.register(nav)

        nav = TreeRoot('shell',
            name=_('Shell'),
            icon='TopIcon',
            action='shell')
        tree_roots.register(nav)

        nav = TreeRoot('reboot',
            name=_('Reboot'),
            action='reboot',
            icon='RebootIcon',
            type='scary_dialog',
            view='system_reboot_dialog')
        tree_roots.register(nav)

        nav = TreeRoot('shutdown',
            name=_('Shutdown'),
            icon='ShutdownIcon',
            type='scary_dialog',
            view='system_shutdown_dialog')
        tree_roots.register(nav)

        for opt, model in _childs_of:
            for nav in tree_roots:
                exists = nav.find_gname(model._admin.menu_child_of)
                if exists is not False:
                    exists.append_child(opt)
                    break
            if exists is False:
                log.debug("Could not find %s to attach %r",
                    model._admin.menu_child_of,
                    opt)

        self.replace_navs(tree_roots)

        """
        Plugin nodes
        TODO: It is a blocking operation, we could use green threads
        """
        host = get_base_url(request)

        for plugin in Plugins.objects.filter(plugin_enabled=True):

            try:
                url = "%s/plugins/%s/_s/treemenu" % (host, plugin.plugin_name)
                opener = urllib2.build_opener()
                opener.addheaders = [('Cookie', 'sessionid=%s' % request.COOKIES.get("sessionid", ''))]
                response = opener.open(url, None, 1)
                data = response.read()
                if not data:
                    log.warn(_("Empty data returned from %s") % (url,))
                    continue
            except Exception, e:
                log.warn(_("Couldn't retrieve %(url)s: %(error)s") % {
                    'url': url,
                    'error': e,
                    })
                continue

            try:
                data = simplejson.loads(data)

                nodes = unserialize_tree(data)
                for node in nodes:
                    #We have our TreeNode's, find out where to place them

                    found = False
                    if node.append_to:
                        log.debug("Plugin %s requested to be appended to %s",
                            plugin.plugin_name, node.append_to)
                        places = node.append_to.split('.')
                        places.reverse()
                        for root in tree_roots:
                            find = root.find_place(list(places))
                            if find:
                                find.append_child(node)
                                found = True
                                break
                    else:
                        log.debug("Plugin %s didn't request to be appended anywhere specific",
                            plugin.plugin_name)

                    if not found:
                        node.tree_root = 'main'
                        tree_roots.register(node)

            except Exception, e:
                log.warn(_("An error occurred while unserializing from "
                    "%(url)s: %(error)s") % {'url': url, 'error': e})
                continue
コード例 #4
0
ファイル: nav.py プロジェクト: BillTheBest/MetaNAS
    def __init__(self, *args, **kwargs):

        super(ISCSIExt, self).__init__(*args, **kwargs)
        for ext in models.iSCSITargetExtent.objects.filter(iscsi_target_extent_type__exact='File').order_by('-id'):
            nav = TreeNode(ext.id)
            nav.name = unicode(ext)
            nav.view = u'freeadmin_model_edit'
            nav.type = 'object'
            nav.kwargs = {'app': 'services', 'model': 'iSCSITargetExtent', 'oid': ext.id}
            nav.icon = u'ExtentIcon'
            self.append_child(nav)

        extadd = TreeNode('Add')
        extadd.name = _(u'Add File Extent')
        extadd.type = u'object'
        extadd.view = u'freeadmin_model_add'
        extadd.kwargs = {'app': 'services', 'model': 'iSCSITargetExtent'}
        extadd.icon = u'AddExtentIcon'

        extview = TreeNode('View')
        extview.name = _(u'View File Extents')
        extview.type = u'iscsi'
        extview.view = u'freeadmin_model_datagrid'
        extview.kwargs = {'app': 'services', 'model': 'iSCSITargetExtent'}
        extview.icon = u'ViewAllExtentsIcon'
        extview.app_name = 'services'
        extview.model = 'Extents'

        self.append_children([extadd, extview])
コード例 #5
0
ファイル: nav.py プロジェクト: BillTheBest/MetaNAS
    def __init__(self, *args, **kwargs):

        super(ISCSIDevice, self).__init__(*args, **kwargs)
        for ext in models.iSCSITargetExtent.objects.filter(iscsi_target_extent_type__in=['Disk','ZVOL']).order_by('-id'):
            nav = TreeNode(ext.id)
            nav.name = unicode(ext)
            nav.view = u'freeadmin_model_edit'
            nav.type = 'object'
            nav.kwargs = {'app': 'services', 'model': 'iSCSITargetExtent', 'oid': ext.id, 'mf': 'iSCSITargetDeviceExtentForm'}
            nav.icon = u'ExtentIcon'
            self.insert_child(0, nav)

        devadd = TreeNode('Add')
        devadd.name = _(u'Add Device Extent')
        devadd.type = u'object'
        devadd.view = u'freeadmin_model_add'
        devadd.kwargs = {'app': 'services', 'model': 'iSCSITargetExtent', 'mf': 'iSCSITargetDeviceExtentForm'}
        devadd.icon = u'AddExtentIcon'

        devview = TreeNode('View')
        devview.name = _(u'View Device Extents')
        devview.type = u'iscsi'
        devview.icon = u'ViewAllExtentsIcon'
        devview.append_app = False
        devview.app_name = 'services'
        devview.model = 'DExtents'

        self.append_children([devadd, devview])
コード例 #6
0
    def __init__(self, *args, **kwargs):

        super(Volumes, self).__init__(*args, **kwargs)
        self.append_children([
            AddVolume(),
            ImportVolume(),
            AutoImportVolume(),
            ViewVolumes(),
            ViewDisks(),
        ])

        en_dataset = models.MountPoint.objects.filter(
            mp_volume__vol_fstype__exact='ZFS').count() > 0

        has_multipath = models.Disk.objects.exclude(
            disk_multipath_name='').exists()
        if has_multipath:
            self.append_child(ViewMultipaths())

        mp = models.MountPoint.objects.select_related().order_by('-id')
        for i in mp:
            nav = TreeNode(i.mp_volume.id)
            nav.name = i.mp_path
            nav.order = -i.id
            nav.model = 'Volume'
            nav.kwargs = {'oid': i.mp_volume.id, 'model': 'Volume'}
            nav.icon = u'VolumesIcon'

            if i.mp_volume.vol_fstype == 'ZFS':
                ds = TreeNode('Dataset')
                ds.name = _(u'Create ZFS Dataset')
                ds.view = 'storage_dataset'
                ds.icon = u'AddDatasetIcon'
                ds.type = 'object'
                append_app = False
                ds.kwargs = {'fs': i.mp_volume.vol_name}
                nav.append_child(ds)

                zv = AddZVol()
                zv.kwargs = {'volume_name': i.mp_volume.vol_name}
                nav.append_child(zv)

            subnav = TreeNode('ChangePermissions')
            subnav.name = _('Change Permissions')
            subnav.type = 'editobject'
            subnav.view = 'storage_mp_permission'
            subnav.kwargs = {'path': i.mp_path}
            subnav.model = 'Volume'
            subnav.icon = u'ChangePasswordIcon'
            subnav.app_name = 'storage'

            datasets = i.mp_volume.get_datasets(hierarchical=True)
            if datasets:
                for name, d in datasets.items():
                    # TODO: non-recursive algo
                    self._gen_dataset(nav, d)

            nav.append_child(subnav)
            self.insert_child(0, nav)
コード例 #7
0
    def _gen_dataset(self, node, dataset):

        nav = TreeNode(dataset.name)
        nav.name = dataset.mountpoint
        nav.icon = u'VolumesIcon'

        ds = TreeNode('Dataset')
        ds.name = _(u'Create ZFS Dataset')
        ds.view = 'storage_dataset'
        ds.icon = u'AddDatasetIcon'
        ds.type = 'object'
        ds.kwargs = {'fs': dataset.path}
        nav.append_child(ds)

        subnav = TreeNode('ChangePermissions')
        subnav.name = _(u'Change Permissions')
        subnav.type = 'editobject'
        subnav.view = 'storage_mp_permission'
        subnav.kwargs = {'path': dataset.mountpoint}
        subnav.model = 'Volumes'
        subnav.icon = u'ChangePasswordIcon'
        subnav.app_name = 'storage'

        node.append_child(nav)
        nav.append_child(subnav)
        for child in dataset.children:
            self._gen_dataset(nav, child)
コード例 #8
0
ファイル: nav.py プロジェクト: BillTheBest/MetaNAS
    def __init__(self, *args, **kwargs):

        super(Linkss, self).__init__(*args, **kwargs)

        laggadd = TreeNode('Add')
        laggadd.name = _(u'Create Link Aggregation')
        laggadd.view = 'network_lagg_add'
        laggadd.type = 'object'
        laggadd.icon = u'AddLAGGIcon'
        laggadd.model = 'LAGGInterface'
        laggadd.app_name = 'network'

        laggview = TreeNode('View')
        laggview.gname = 'View'
        laggview.name = _(u'View Link Aggregations')
        laggview.type = 'opennetwork'
        laggview.icon = u'ViewAllLAGGsIcon'
        laggview.model = 'LAGGInterface'
        laggview.app_name = 'network'
        self.append_children([laggadd, laggview])

        for value, name in LAGGType:

            laggs = models.LAGGInterface.objects.filter(lagg_protocol__exact=value)
            if laggs.count() > 0:
                nav = TreeNode()
                nav.name = name
                nav.icon = u'LAGGIcon'
                nav._children = []
                self.append_child(nav)

            for lagg in laggs:

                subnav = TreeNode()
                subnav.name = lagg.lagg_interface.int_name
                subnav.icon = u'LAGGIcon'
                subnav._children = []
                nav.append_child(subnav)

                laggm = models.LAGGInterfaceMembers.objects.filter(\
                        lagg_interfacegroup__exact=lagg.id).order_by('lagg_ordernum')
                for member in laggm:
                    subsubnav = TreeNode()
                    subsubnav.name = member.lagg_physnic
                    subsubnav.type = 'editobject'
                    subsubnav.icon = u'LAGGIcon'
                    subsubnav.view = 'freeadmin_model_edit'
                    subsubnav.app_name = 'network'
                    subsubnav.model = 'LAGGInterfaceMembers'+lagg.lagg_interface.int_name
                    subsubnav.kwargs = {'app': 'network', 'model': 'LAGGInterfaceMembers', \
                            'oid': member.id}
                    subsubnav.append_url = '?deletable=false'
                    subsubnav._children = []
                    subnav.append_child(subsubnav)
コード例 #9
0
    def __init__(self, *args, **kwargs):

        super(ISCSIDevice, self).__init__(*args, **kwargs)
        for ext in models.iSCSITargetExtent.objects.filter(
                iscsi_target_extent_type__in=['Disk', 'ZVOL']).order_by('-id'):
            nav = TreeNode(ext.id)
            nav.name = unicode(ext)
            nav.view = u'freeadmin_model_edit'
            nav.type = 'object'
            nav.kwargs = {
                'app': 'services',
                'model': 'iSCSITargetExtent',
                'oid': ext.id,
                'mf': 'iSCSITargetDeviceExtentForm'
            }
            nav.icon = u'ExtentIcon'
            self.insert_child(0, nav)

        devadd = TreeNode('Add')
        devadd.name = _(u'Add Device Extent')
        devadd.type = u'object'
        devadd.view = u'freeadmin_model_add'
        devadd.kwargs = {
            'app': 'services',
            'model': 'iSCSITargetExtent',
            'mf': 'iSCSITargetDeviceExtentForm'
        }
        devadd.icon = u'AddExtentIcon'

        devview = TreeNode('View')
        devview.name = _(u'View Device Extents')
        devview.type = u'iscsi'
        devview.icon = u'ViewAllExtentsIcon'
        devview.append_app = False
        devview.app_name = 'services'
        devview.model = 'DExtents'

        self.append_children([devadd, devview])
コード例 #10
0
    def __init__(self, *args, **kwargs):

        super(ISCSIExt, self).__init__(*args, **kwargs)
        for ext in models.iSCSITargetExtent.objects.filter(
                iscsi_target_extent_type__exact='File').order_by('-id'):
            nav = TreeNode(ext.id)
            nav.name = unicode(ext)
            nav.view = u'freeadmin_model_edit'
            nav.type = 'object'
            nav.kwargs = {
                'app': 'services',
                'model': 'iSCSITargetExtent',
                'oid': ext.id
            }
            nav.icon = u'ExtentIcon'
            self.append_child(nav)

        extadd = TreeNode('Add')
        extadd.name = _(u'Add File Extent')
        extadd.type = u'object'
        extadd.view = u'freeadmin_model_add'
        extadd.kwargs = {'app': 'services', 'model': 'iSCSITargetExtent'}
        extadd.icon = u'AddExtentIcon'

        extview = TreeNode('View')
        extview.name = _(u'View File Extents')
        extview.type = u'iscsi'
        extview.view = u'freeadmin_model_datagrid'
        extview.kwargs = {'app': 'services', 'model': 'iSCSITargetExtent'}
        extview.icon = u'ViewAllExtentsIcon'
        extview.app_name = 'services'
        extview.model = 'Extents'

        self.append_children([extadd, extview])
コード例 #11
0
    def __init__(self, *args, **kwargs):

        super(Linkss, self).__init__(*args, **kwargs)

        laggadd = TreeNode('Add')
        laggadd.name = _(u'Create Link Aggregation')
        laggadd.view = 'network_lagg_add'
        laggadd.type = 'object'
        laggadd.icon = u'AddLAGGIcon'
        laggadd.model = 'LAGGInterface'
        laggadd.app_name = 'network'

        laggview = TreeNode('View')
        laggview.gname = 'View'
        laggview.name = _(u'View Link Aggregations')
        laggview.type = 'opennetwork'
        laggview.icon = u'ViewAllLAGGsIcon'
        laggview.model = 'LAGGInterface'
        laggview.app_name = 'network'
        self.append_children([laggadd, laggview])

        for value, name in LAGGType:

            laggs = models.LAGGInterface.objects.filter(
                lagg_protocol__exact=value)
            if laggs.count() > 0:
                nav = TreeNode()
                nav.name = name
                nav.icon = u'LAGGIcon'
                nav._children = []
                self.append_child(nav)

            for lagg in laggs:

                subnav = TreeNode()
                subnav.name = lagg.lagg_interface.int_name
                subnav.icon = u'LAGGIcon'
                subnav._children = []
                nav.append_child(subnav)

                laggm = models.LAGGInterfaceMembers.objects.filter(\
                        lagg_interfacegroup__exact=lagg.id).order_by('lagg_ordernum')
                for member in laggm:
                    subsubnav = TreeNode()
                    subsubnav.name = member.lagg_physnic
                    subsubnav.type = 'editobject'
                    subsubnav.icon = u'LAGGIcon'
                    subsubnav.view = 'freeadmin_model_edit'
                    subsubnav.app_name = 'network'
                    subsubnav.model = 'LAGGInterfaceMembers' + lagg.lagg_interface.int_name
                    subsubnav.kwargs = {'app': 'network', 'model': 'LAGGInterfaceMembers', \
                            'oid': member.id}
                    subsubnav.append_url = '?deletable=false'
                    subsubnav._children = []
                    subnav.append_child(subsubnav)
コード例 #12
0
ファイル: nav.py プロジェクト: BillTheBest/MetaNAS
    def __init__(self, *args, **kwargs):

        super(Volumes, self).__init__(*args, **kwargs)
        self.append_children([AddVolume(),
                                ImportVolume(),
                                AutoImportVolume(),
                                ViewVolumes(),
                                ViewDisks(),
                             ])

        en_dataset = models.MountPoint.objects.filter(mp_volume__vol_fstype__exact='ZFS').count() > 0

        has_multipath = models.Disk.objects.exclude(disk_multipath_name='').exists()
        if has_multipath:
            self.append_child(ViewMultipaths())

        mp = models.MountPoint.objects.select_related().order_by('-id')
        for i in mp:
            nav = TreeNode(i.mp_volume.id)
            nav.name = i.mp_path
            nav.order = -i.id
            nav.model = 'Volume'
            nav.kwargs = {'oid': i.mp_volume.id, 'model': 'Volume'}
            nav.icon = u'VolumesIcon'

            if i.mp_volume.vol_fstype == 'ZFS':
                ds = TreeNode('Dataset')
                ds.name = _(u'Create ZFS Dataset')
                ds.view = 'storage_dataset'
                ds.icon = u'AddDatasetIcon'
                ds.type = 'object'
                append_app = False
                ds.kwargs = {'fs': i.mp_volume.vol_name}
                nav.append_child(ds)

                zv = AddZVol()
                zv.kwargs = {'volume_name': i.mp_volume.vol_name}
                nav.append_child(zv)

            subnav = TreeNode('ChangePermissions')
            subnav.name = _('Change Permissions')
            subnav.type = 'editobject'
            subnav.view = 'storage_mp_permission'
            subnav.kwargs = {'path': i.mp_path}
            subnav.model = 'Volume'
            subnav.icon = u'ChangePasswordIcon'
            subnav.app_name = 'storage'

            datasets = i.mp_volume.get_datasets(hierarchical=True)
            if datasets:
                for name, d in datasets.items():
                    # TODO: non-recursive algo
                    self._gen_dataset(nav, d)

            nav.append_child(subnav)
            self.insert_child(0, nav)
コード例 #13
0
ファイル: nav.py プロジェクト: BillTheBest/MetaNAS
    def _gen_dataset(self, node, dataset):

        nav = TreeNode(dataset.name)
        nav.name = dataset.mountpoint
        nav.icon = u'VolumesIcon'

        ds = TreeNode('Dataset')
        ds.name = _(u'Create ZFS Dataset')
        ds.view = 'storage_dataset'
        ds.icon = u'AddDatasetIcon'
        ds.type = 'object'
        ds.kwargs = {'fs': dataset.path}
        nav.append_child(ds)

        subnav = TreeNode('ChangePermissions')
        subnav.name = _(u'Change Permissions')
        subnav.type = 'editobject'
        subnav.view = 'storage_mp_permission'
        subnav.kwargs = {'path': dataset.mountpoint}
        subnav.model = 'Volumes'
        subnav.icon = u'ChangePasswordIcon'
        subnav.app_name = 'storage'

        node.append_child(nav)
        nav.append_child(subnav)
        for child in dataset.children:
            self._gen_dataset(nav, child)
コード例 #14
0
    def generate(self, request=None):
        """
        Tree Menu Auto Generate

        Every app listed at INSTALLED_APPS is scanned
        1st - app_name.forms is imported. All its objects/classes are scanned
            looking for ModelForm classes
        2nd - app_name.nav is imported. TreeNode classes are scanned for
            hard-coded menu entries or overwriting
        3rd - app_name.models is imported. models.Model classes are scanned,
        if a related ModelForm is found several entries are Added to the Menu
                - Objects
                - Add (Model)
                - View (Model)
        """

        self._generated = True
        self._navs.clear()
        tree_roots.clear()
        _childs_of = []
        for app in settings.INSTALLED_APPS:

            # If the app is listed at settings.BLACKLIST_NAV, skip it!
            if app in getattr(settings, 'BLACKLIST_NAV', []):
                continue

            # Thats the root node for the app tree menu
            nav = TreeRoot(app)

            modnav = self._get_module(app, 'nav')
            if hasattr(modnav, 'BLACKLIST'):
                BLACKLIST = modnav.BLACKLIST
            else:
                BLACKLIST = []

            if hasattr(modnav, 'ICON'):
                nav.icon = modnav.ICON

            if hasattr(modnav, 'NAME'):
                nav.name = modnav.NAME
            else:
                nav.name = self.titlecase(app)

            if modnav:
                modname = "%s.nav" % app
                for c in dir(modnav):
                    navc = getattr(modnav, c)
                    try:
                        subclass = issubclass(navc, TreeNode)
                    except TypeError:
                        continue
                    if navc.__module__ == modname and subclass:
                        obj = navc()

                        if obj.skip is True:
                            continue
                        if not obj.append_to:
                            self.register_option(obj, nav, replace=True)
                        else:
                            self._navs[obj.append_to + '.' + obj.gname] = obj

                tree_roots.register(nav)  # We register it to the tree root
                if hasattr(modnav, 'init'):
                    modnav.init(tree_roots, nav)

            else:
                log.debug("App %s has no nav.py module, skipping", app)
                continue

            modmodels = self._get_module(app, 'models')
            if modmodels:

                modname = '%s.models' % app
                for c in dir(modmodels):
                    model = getattr(modmodels, c)
                    try:
                        if not issubclass(model, models.Model) or \
                            model._meta.app_label != app:
                            continue
                    except TypeError:
                        continue

                    if c in BLACKLIST:
                        log.debug(
                            "Model %s from app %s blacklisted, skipping",
                            c,
                            app,
                        )
                        continue

                    if not(model.__module__ in (modname,
                                'metanasUI.' + modname) \
                            and model in self._modelforms
                          ):
                        log.debug("Model %s does not have a ModelForm", model)
                        continue

                    if model._admin.deletable is False:
                        navopt = TreeNode(str(model._meta.object_name),
                                          name=model._meta.verbose_name,
                                          model=c,
                                          app_name=app,
                                          type='dialog')
                        try:
                            navopt.kwargs = {'app': app, 'model': c, 'oid': \
                                model.objects.order_by("-id")[0].id}
                            navopt.view = 'freeadmin_model_edit'
                        except:
                            navopt.view = 'freeadmin_model_add'
                            navopt.kwargs = {'app': app, 'model': c}

                    else:
                        navopt = TreeNode(str(model._meta.object_name))
                        navopt.name = model._meta.verbose_name_plural
                        navopt.model = c
                        navopt.app_name = app
                        navopt.order_child = False

                    for key in model._admin.nav_extra.keys():
                        navopt.__setattr__(key,
                                           model._admin.nav_extra.get(key))
                    if model._admin.icon_model is not None:
                        navopt.icon = model._admin.icon_model

                    if model._admin.menu_child_of is not None:
                        _childs_of.append((navopt, model))
                        reg = True
                    else:
                        reg = self.register_option(navopt, nav)

                    if reg and not navopt.type:

                        qs = model.objects.filter(
                            **model._admin.object_filters).order_by('-id')
                        if qs.count() > 0:
                            if model._admin.object_num > 0:
                                qs = qs[:model._admin.object_num]
                            for e in qs:
                                subopt = TreeNode('Edit')
                                subopt.type = 'editobject'
                                subopt.view = u'freeadmin_model_edit'
                                if model._admin.icon_object is not None:
                                    subopt.icon = model._admin.icon_object
                                subopt.model = c
                                subopt.app_name = app
                                subopt.kwargs = {
                                    'app': app,
                                    'model': c,
                                    'oid': e.id,
                                }
                                try:
                                    subopt.name = unicode(e)
                                except:
                                    subopt.name = 'Object'
                                navopt.append_child(subopt)

                        # Node to add an instance of model
                        subopt = TreeNode('Add')
                        subopt.name = _(u'Add %s') % model._meta.verbose_name
                        subopt.view = u'freeadmin_model_add'
                        subopt.kwargs = {'app': app, 'model': c}
                        subopt.order = 500
                        subopt.type = 'dialog'
                        if model._admin.icon_add is not None:
                            subopt.icon = model._admin.icon_add
                        subopt.model = c
                        subopt.app_name = app
                        self.register_option(subopt, navopt)

                        # Node to view all instances of model
                        subopt = TreeNode('View')
                        subopt.name = _(u'View %s') % (
                            model._meta.verbose_name_plural, )
                        subopt.view = u'freeadmin_model_datagrid'
                        if model._admin.icon_view is not None:
                            subopt.icon = model._admin.icon_view
                        subopt.model = c
                        subopt.app_name = app
                        subopt.kwargs = {'app': app, 'model': c}
                        subopt.order = 501
                        subopt.type = 'viewmodel'
                        self.register_option(subopt, navopt)

        nav = TreeRoot('display',
                       name=_('Display System Processes'),
                       action='displayprocs',
                       icon='TopIcon')
        tree_roots.register(nav)

        nav = TreeRoot('shell',
                       name=_('Shell'),
                       icon='TopIcon',
                       action='shell')
        tree_roots.register(nav)

        nav = TreeRoot('reboot',
                       name=_('Reboot'),
                       action='reboot',
                       icon='RebootIcon',
                       type='scary_dialog',
                       view='system_reboot_dialog')
        tree_roots.register(nav)

        nav = TreeRoot('shutdown',
                       name=_('Shutdown'),
                       icon='ShutdownIcon',
                       type='scary_dialog',
                       view='system_shutdown_dialog')
        tree_roots.register(nav)

        for opt, model in _childs_of:
            for nav in tree_roots:
                exists = nav.find_gname(model._admin.menu_child_of)
                if exists is not False:
                    exists.append_child(opt)
                    break
            if exists is False:
                log.debug("Could not find %s to attach %r",
                          model._admin.menu_child_of, opt)

        self.replace_navs(tree_roots)
        """
        Plugin nodes
        TODO: It is a blocking operation, we could use green threads
        """
        host = get_base_url(request)

        for plugin in Plugins.objects.filter(plugin_enabled=True):

            try:
                url = "%s/plugins/%s/_s/treemenu" % (host, plugin.plugin_name)
                opener = urllib2.build_opener()
                opener.addheaders = [
                    ('Cookie',
                     'sessionid=%s' % request.COOKIES.get("sessionid", ''))
                ]
                response = opener.open(url, None, 1)
                data = response.read()
                if not data:
                    log.warn(_("Empty data returned from %s") % (url, ))
                    continue
            except Exception, e:
                log.warn(
                    _("Couldn't retrieve %(url)s: %(error)s") % {
                        'url': url,
                        'error': e,
                    })
                continue

            try:
                data = simplejson.loads(data)

                nodes = unserialize_tree(data)
                for node in nodes:
                    #We have our TreeNode's, find out where to place them

                    found = False
                    if node.append_to:
                        log.debug("Plugin %s requested to be appended to %s",
                                  plugin.plugin_name, node.append_to)
                        places = node.append_to.split('.')
                        places.reverse()
                        for root in tree_roots:
                            find = root.find_place(list(places))
                            if find:
                                find.append_child(node)
                                found = True
                                break
                    else:
                        log.debug(
                            "Plugin %s didn't request to be appended anywhere specific",
                            plugin.plugin_name)

                    if not found:
                        node.tree_root = 'main'
                        tree_roots.register(node)

            except Exception, e:
                log.warn(
                    _("An error occurred while unserializing from "
                      "%(url)s: %(error)s") % {
                          'url': url,
                          'error': e
                      })
                continue