Exemplo n.º 1
0
def clone_workspace(workspace, for_user, request=None):
    """
    Clones entire workspace.

    :param dash.models.DashboardWorkspace:
    :param django.contrib.auth.models.User:
    :return dash.models.DashboardWorkspace: Cloned workspace instance.
    """
    # Cloning workspace object.
    cloned_workspace = copy.copy(workspace)
    cloned_workspace.pk = None
    cloned_workspace.user = for_user
    cloned_workspace.is_public = False
    cloned_workspace.is_clonable = False
    cloned_workspace.name = "{0} cloned on {1}".format(cloned_workspace.name, \
                                                       datetime.datetime.now())

    cloned_workspace.save()

    # Cloning workspace entries.
    dashboard_entries = DashboardEntry._default_manager \
                                      .filter(workspace=workspace)

    buf = []

    for dashboard_entry in dashboard_entries:
        cloned_plugin_data = clone_plugin_data(dashboard_entry,
                                               request=request)
        cloned_dashboard_entry = DashboardEntry(
            user=for_user,
            workspace=cloned_workspace,
            layout_uid=dashboard_entry.layout_uid,
            placeholder_uid=dashboard_entry.placeholder_uid,
            plugin_uid=dashboard_entry.plugin_uid,
            plugin_data=cloned_plugin_data,
            position=dashboard_entry.position,
        )

        buf.append(cloned_dashboard_entry)

    DashboardEntry._default_manager.bulk_create(buf)

    return cloned_workspace
Exemplo n.º 2
0
def create_news_and_rss_dashboard_entries(user, workspace):
    """
    Dashboard entries for news page.

    :param django.contrib.auth.models.User user:
    :param dash.models.DashboardWorkspace workspace:
    """
    buf = []

    # *********************************
    # *********************************
    # ***** Shortcuts placeholder *****
    # *********************************
    # *********************************

    # URL plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidShortcutsPlaceholder.uid,
        plugin_uid='url_1x1',
        plugin_data=clean_extra_spaces(
            """{"url": "http://delusionalinsanity.com/portfolio/",
            "image": "icon-picture", "external": true, "title": "Delusional Insanity"}"""
        ),
        position=1)
    buf.append(dashboard_entry)

    # LargeDummy portrait plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidShortcutsPlaceholder.uid,
        plugin_uid='dummy_1x2',
        plugin_data=clean_extra_spaces(
            """{"text": "", "lipsum_language": "en", "show_title": false,
            "generate_lipsum": false}"""),
        position=2)
    buf.append(dashboard_entry)

    # LargeDummy portrait plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidShortcutsPlaceholder.uid,
        plugin_uid='dummy_1x2',
        plugin_data=clean_extra_spaces(
            """{"text": "", "lipsum_language": "en", "show_title": false,
            "generate_lipsum": false}"""),
        position=4)
    buf.append(dashboard_entry)

    # LargeDummy portrait plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidShortcutsPlaceholder.uid,
        plugin_uid='dummy_1x2',
        plugin_data=clean_extra_spaces(
            """{"text": "", "lipsum_language": "en", "show_title": false,
            "generate_lipsum": false}"""),
        position=6)
    buf.append(dashboard_entry)

    # LargeDummy portrait plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidShortcutsPlaceholder.uid,
        plugin_uid='dummy_1x2',
        plugin_data=clean_extra_spaces(
            """{"text": "", "lipsum_language": "en", "show_title": false,
            "generate_lipsum": false}"""),
        position=6)
    buf.append(dashboard_entry)

    # LargeDummy portait plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidShortcutsPlaceholder.uid,
        plugin_uid='dummy_1x2',
        plugin_data=clean_extra_spaces(
            """{"text": "", "lipsum_language": "en", "show_title": false,
            "generate_lipsum": false}"""),
        position=8)
    buf.append(dashboard_entry)

    # *********************************
    # *********************************
    # ******** Main placeholder *******
    # *********************************
    # *********************************

    # News plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidMainPlaceholder.uid,
        plugin_uid='news_4x5',
        plugin_data=clean_extra_spaces(
            """{"truncate_after": 35, "max_items": 5, "show_title": true,
            "cache_for": 3600}"""),
        position=1)
    buf.append(dashboard_entry)

    # RSS feed plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidMainPlaceholder.uid,
        plugin_uid='read_rss_feed_2x3',
        plugin_data=clean_extra_spaces(
            """{"custom_feed_title": "News feed", "truncate_after": 35,
            "feed_url": "http://foreverchild.info/rss/", "cache_for": 3600, "show_feed_title": true,
            "max_items": 6}"""),
        position=5)
    buf.append(dashboard_entry)

    # LargeDummy plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidMainPlaceholder.uid,
        plugin_uid='dummy_2x1',
        plugin_data=clean_extra_spaces(
            """{"text": "\u03a3\u03bfc\u03b9\u03b9\u03c3 \u03b5\u03b3\u03b5\u03c4
            \u03c4\u03b9\u03bdc\u03b9\u03b4\u03b8\u03bd\u03c4 \u03b1c,
            \u03c6\u03c1\u03b9\u03bd\u03b3\u03b9\u03bb\u03bb\u03b1 \u03b1c. V\u03b5 \u03b1\u03b8c\u03c4\u03bf\u03c1
            \u03b8\u03c4 \u03c0\u03c1\u03b1\u03b5\u03c3\u03b5\u03bd\u03c4 v\u03b1\u03c1\u03b9\u03b8\u03c3,
            \u03bf\u03c1\u03bd\u03b1\u03c1\u03b5 \u03bd\u03b5c, \u03b1\u03b8c\u03c4\u03bf\u03c1, \u03b1\u03b4,
            \u03bb\u03bf\u03c1\u03b5\u03bc c\u03bf\u03bd\u03b4\u03b9\u03bc\u03b5\u03bd\u03c4\u03b8\u03bc.
            \u03a0\u03bf\u03c4\u03b5\u03bd\u03c4\u03b9. \u0391\u03bb\u03b9q\u03b8\u03b1\u03bc.
            \u03a3\u03bf\u03bb\u03bb\u03b9c\u03b9\u03c4\u03b8\u03b4\u03b9\u03bd
            \u03b4\u03b9c\u03c4\u03b8\u03bc \u03b8\u03c4 \u03bd\u03bf\u03c3\u03c4\u03c1\u03b1 \u03b4\u03b9\u03c3.
            \u0391\u03bd\u03c4\u03b5 c\u03bf\u03bd\u03b8\u03b2\u03b9\u03b1 \u03c1\u03b8\u03c4\u03c1\u03b8\u03bc,
            \u03c0\u03b7\u03b1\u03c3\u03b5\u03bb\u03bb\u03b8\u03c3 ...", "lipsum_max_chars": 200,
            "lipsum_language": "el", "show_title": false, "generate_lipsum": true}"""
        ),
        position=23)
    buf.append(dashboard_entry)

    # LargeDummy plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidMainPlaceholder.uid,
        plugin_uid='dummy_2x1',
        plugin_data=clean_extra_spaces(
            """{"text": "Quis inceptos. Urna libero tortor nonummy pretium. Lectus.
            Platea eu, ligula lacinia dis, parturient consequat. Nunc tempor pretium natoque cubilia nunc. Ligula
            at, nulla. Congue at. Mauris. Luctus...", "lipsum_max_chars": 200, "lipsum_language": "en",
            "show_title": false, "generate_lipsum": true}"""),
        position=29)
    buf.append(dashboard_entry)

    # Bulk insert
    DashboardEntry._default_manager.bulk_create(buf)
Exemplo n.º 3
0
def create_dashboard_entries(user, workspace=None, mixed_order=False):
    """
    Create dashboard entries.

    :param django.contrib.auth.models.User user:
    :param dash.models.DashboardWorkspace workspace:
    :param bool mixed_order:
    """
    # *********************************
    # *********************************
    # ******** Main placeholder *******
    # *********************************
    # *********************************
    buf = []

    # URL plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidMainPlaceholder.uid,
        plugin_uid='url_1x1',
        plugin_data=clean_extra_spaces(
            """{"url": "http://delusionalinsanity.com/portfolio/", "image": "icon-picture",
            "external": true, "title": "Photography"}"""),
        position=2 if mixed_order else 1)
    buf.append(dashboard_entry)

    # URL plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidMainPlaceholder.uid,
        plugin_uid='url_1x1',
        plugin_data=clean_extra_spaces(
            """{"url": "http://f0reverchild.livejournal.com/", "image": "icon-book",
            "external": true, "title": "Livejournal"}"""),
        position=1 if mixed_order else 2)
    buf.append(dashboard_entry)

    # URL plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidMainPlaceholder.uid,
        plugin_uid='url_1x1',
        plugin_data=clean_extra_spaces(
            """{"url": "http://www.modelmayhem.com/95855", "image": "icon-camera",
            "external": true, "title": "Model Mayhem"}"""),
        position=30 if mixed_order else 3)
    buf.append(dashboard_entry)

    # TinyMCE plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidMainPlaceholder.uid,
        plugin_uid='tinymce_memo_3x3',
        plugin_data=clean_extra_spaces(
            '{\"text\": \"<p>Python is my personal (and primary) programming language of choice and also happens to '
            'be the primary programming language at my beloved company, Goldmund, Wyldebeast &amp; Wunderliebe. So, '
            'when starting to work with a new technology, I prefer to use a clean and easy (Pythonic!) API.<br />'
            '<br />After studying tons of articles on the web, reading (and writing) white papers, and doing basic '
            'performance tests (sometimes hard if you\'re on a tight schedule), my company recently selected '
            'Cloudera for our Big Data platform (including using Apache HBase as our data store for Apache '
            'Hadoop), with Cloudera Manager serving a role as \\\"one console to rule them all.\\\"...'
            '<a href=\\\"http://blog.cloudera.com/blog/2013/10/hello-starbase-a-python-wrapper-for-the-hbase-rest-api/\\\" '
            'target=\\\"_blank\\\">(read more)</a></p>\", \"title\": \"Starbase: A Python Wrapper for the HBase '
            'REST API\"}'),
        position=7 if mixed_order else 4)
    buf.append(dashboard_entry)

    # BigVideo plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidMainPlaceholder.uid,
        plugin_uid='video_3x3',
        plugin_data=clean_extra_spaces(
            """{"url": "http://www.youtube.com/watch?v=8GVIui0JK0M",
            "title": "Test 3x3 video"}"""),
        position=4 if mixed_order else 7)
    buf.append(dashboard_entry)

    # Memo plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidMainPlaceholder.uid,
        plugin_uid='memo_2x2',
        plugin_data=clean_extra_spaces(
            """{"text": "(1) Dragging of widgets (within the Placeholder),
            (2) Reset dashboards triggers/hoocks, (3) Pre-defined template system for workspaces (with
            plugins in), (4) Copy/paste widgets between workspaces.", "title": "django-dash TODOs"}"""
        ),
        position=22)
    buf.append(dashboard_entry)

    # URL plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidMainPlaceholder.uid,
        plugin_uid='url_1x1',
        plugin_data=clean_extra_spaces(
            """{"url": "https://github.com/barseghyanartur",
            "image": "icon-github", "external": true, "title": "GitHub"}"""),
        position=27 if mixed_order else 24)
    buf.append(dashboard_entry)

    # URL plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidMainPlaceholder.uid,
        plugin_uid='url_1x1',
        plugin_data=clean_extra_spaces(
            """{"url": "https://barseghyanartur.blogspot.com/", "image": "icon-info-sign",
            "external": true, "title": "Blogspot"}"""),
        position=24 if mixed_order else 27)
    buf.append(dashboard_entry)

    # URL plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidMainPlaceholder.uid,
        plugin_uid='url_1x1',
        plugin_data=clean_extra_spaces(
            """{"url": "https://bitbucket.org/barseghyanartur", "image": "icon-bitbucket",
            "external": true, "title": "BitBucket"}"""),
        position=3 if mixed_order else 30)
    buf.append(dashboard_entry)

    # *********************************
    # *********************************
    # ***** Shortcuts placeholder *****
    # *********************************
    # *********************************

    # URL plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidShortcutsPlaceholder.uid,
        plugin_uid='url_1x1',
        plugin_data=clean_extra_spaces(
            """{"url": "http://www.goldmund-wyldebeast-wunderliebe.com/",
            "image": "icon-thumbs-up", "external": true, "title": "Goldmund, Wyldebeast & Wunderliebe"}"""
        ),
        position=2 if mixed_order else 1)
    buf.append(dashboard_entry)

    # URL plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidShortcutsPlaceholder.uid,
        plugin_uid='url_1x1',
        plugin_data=clean_extra_spaces(
            """{"url": "http://foreverchild.info/", "image": "icon-star",
            "external": true, "title": "Forever Child"}"""),
        position=1 if mixed_order else 2)
    buf.append(dashboard_entry)

    # URL plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidShortcutsPlaceholder.uid,
        plugin_uid='url_1x1',
        plugin_data=clean_extra_spaces("""
            {"url": "http://www.youtube.com/watch?v=gDyujx0BZSg&list=PLsn9xS2-yuBvKTsko_TPM16ebCiA1pHfZ",
            "image": "icon-youtube", "external": true, "title": "Cocteau Twins - Treasure"}"""
                                       ),
        position=3)
    buf.append(dashboard_entry)

    # Dummy plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidShortcutsPlaceholder.uid,
        plugin_uid='dummy_1x1',
        plugin_data=clean_extra_spaces(
            """{"text": "", "lipsum_language": "en", "show_title": false,
            "generate_lipsum": false}"""),
        position=4)
    buf.append(dashboard_entry)

    # URL plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidShortcutsPlaceholder.uid,
        plugin_uid='url_1x1',
        plugin_data=clean_extra_spaces(
            """{"url": "http://www.youtube.com/watch?v=tiYr-464-Nc",
            "image": "icon-youtube", "external": true, "title": "Portishead - Third"}"""
        ),
        position=5)
    buf.append(dashboard_entry)

    # Dummy plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidShortcutsPlaceholder.uid,
        plugin_uid='dummy_1x1',
        plugin_data=clean_extra_spaces(
            """{"text": "", "lipsum_language": "en", "show_title": false,
            "generate_lipsum": false}"""),
        position=6)
    buf.append(dashboard_entry)

    # URL plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidShortcutsPlaceholder.uid,
        plugin_uid='url_1x1',
        plugin_data=clean_extra_spaces(
            """{"url": "http://www.youtube.com/watch?v=7SFf2sQb4H4",
            "image": "icon-youtube", "external": true, "title": "Lais - Kanneke (tiens bien)"}"""
        ),
        position=7)
    buf.append(dashboard_entry)

    # LargeDummy portrait plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidShortcutsPlaceholder.uid,
        plugin_uid='dummy_1x2',
        plugin_data=clean_extra_spaces(
            """{"text": "", "lipsum_language": "en", "show_title": false,
            "generate_lipsum": false}"""),
        position=8)
    buf.append(dashboard_entry)

    # URL plugin
    dashboard_entry = DashboardEntry(
        user=user,
        workspace=workspace,
        layout_uid=AndroidLayout.uid,
        placeholder_uid=AndroidShortcutsPlaceholder.uid,
        plugin_uid='url_1x1',
        plugin_data=clean_extra_spaces(
            """    {"url": "http://www.youtube.com/watch?v=67JH3e7d1r4",
            "image": "icon-youtube", "external": true, "title": "Paradise Lost - Draconian Times"}"""
        ),
        position=10)
    buf.append(dashboard_entry)

    # Bulk insert
    DashboardEntry._default_manager.bulk_create(buf)
Exemplo n.º 4
0
def add_dashboard_entry(request, placeholder_uid, plugin_uid, workspace=None, \
                        position=None, \
                        template_name='dash/add_dashboard_entry.html', \
                        template_name_ajax='dash/add_dashboard_entry_ajax.html'):
    """
    Add dashboard entry.

    :param django.http.HttpRequest request:
    :param string placeholder_uid: Placeholder UID.
    :param string plugin_uid: Plugin UID.
    :param string workspace: Workspace slug.
    :param int position: If given, provided as position for the
        plugin (conflict resolution should take place).
    :param string template_name:
    :param string template_name_ajax: Template used for AJAX requests.
    :return django.http.HttpResponse:
    """
    # Getting dashboard settings for the user. Then get users' layout.
    dashboard_settings = get_or_create_dashboard_settings(request.user)
    layout = get_layout(
        layout_uid=dashboard_settings.layout_uid, as_instance=True
        )

    if not validate_placeholder_uid(layout, placeholder_uid):
        raise Http404(_("Invalid placeholder: {0}").format(placeholder_uid))

    if not validate_plugin_uid(plugin_uid):
        raise Http404(_("Invalid plugin name: {0}").format(plugin_uid))

    plugin = plugin_registry.get(plugin_uid)(layout.uid, placeholder_uid)
    plugin.request = request

    if plugin.add_form_template:
        template_name = plugin.add_form_template

    # Template context
    context = {
        'layout': layout,
        'dashboard_settings': dashboard_settings
    }

    obj = DashboardEntry()
    obj.layout_uid = layout.uid
    obj.placeholder_uid = placeholder_uid
    obj.plugin_uid = plugin_uid
    obj.user = request.user

    occupied_cells = build_cells_matrix(
            request.user,
            layout,
            placeholder=layout.get_placeholder(placeholder_uid),
            workspace=workspace
            )

    # If plugin has form, it is configurable which means we have to load the
    # plugin form and validate user input.
    plugin_form = plugin.get_form()
    if plugin_form:
        # If POST request and form data is valid, save the data and redirect
        # to the dashboard edit.
        if 'POST' == request.method:
            form = plugin.get_initialised_create_form_or_404(
                data=request.POST, files=request.FILES
                )
            if form.is_valid():
                # Saving the plugin form data.
                form.save_plugin_data(request=request)

                # Getting the plugin data.
                obj.plugin_data = form.get_plugin_data(request=request)

                # Handling the workspace.
                workspace_id = None
                obj.workspace = workspace_id
                if workspace:
                    workspace_slug = slugify_workspace(workspace)
                    workspace_id = DashboardWorkspace.objects.get(name=workspace).pk
                    try:
                        obj.workspace = DashboardWorkspace._default_manager.get(
                            slug = workspace_slug,
                            user = request.user,
                            layout_uid = layout.uid
                            )
                    except ObjectDoesNotExist as e:
                        messages.info(
                            request,
                            _('The workspace with slug "{0}" does not belong to '
                              'layout "{1}".').format(workspace_slug, layout.name)
                            )
                        return redirect('dash.edit_dashboard')

                # If position given, use it.
                try:
                    position = int(position)
                except Exception as e:
                    position = None

                if position:
                    obj.position = position

                # Save the object.
                obj.save()
                if int(position) in occupied_cells:
                    if not DashboardEntry.objects.filter(position=int(position), layout_uid=layout.uid,
                                                         workspace_id=workspace_id,
                                                         plugin_uid__startswith='WidgetSwitcher').exists():
                        pattern = re.compile(r'\d+x\d+')
                        dimensions = pattern.search(str(plugin_uid))
                        switcher = DashboardEntry()
                        switcher.layout_uid = layout.uid
                        switcher.placeholder_uid = placeholder_uid
                        switcher.plugin_uid = 'WidgetSwitcher_'+dimensions.group()
                        switcher.user = request.user
                        switcher.plugin_data = json.dumps({"timer": 10})
                        switcher.position = int(position)
                        switcher.workspace = None
                        if workspace:
                            switcher.workspace = DashboardWorkspace._default_manager.get(
                                    slug=workspace_slug,
                                    user=request.user,
                                    layout_uid=layout.uid
                                    )
                        switcher.save()

                messages.info(request, _('The dashboard widget "{0}" was added '
                                         'successfully.').format(plugin.name))

                # Redirect to the dashboard view.
                if obj.workspace:
                    return redirect(
                        'dash.edit_dashboard', workspace=obj.workspace.slug
                        )
                else:
                    return redirect('dash.edit_dashboard')

        # If POST but data invalid, show the form with errors.
        else:
            form = plugin.get_initialised_create_form_or_404()

        context.update(
            {'form': form, 'plugin_uid': plugin_uid, 'plugin': plugin}
            )

    # If plugin is not configurable, it's just saved as is.
    else:
        obj.save()
        return redirect('dash.edit_dashboard')

    if request.is_ajax():
        template_name = template_name_ajax

    return render_to_response(
        template_name, context, context_instance=RequestContext(request)
        )
Exemplo n.º 5
0
def add_dashboard_entry(request, placeholder_uid, plugin_uid, workspace=None, \
                        position=None, \
                        template_name='dash/add_dashboard_entry.html', \
                        template_name_ajax='dash/add_dashboard_entry_ajax.html'):
    """
    Add dashboard entry.

    :param django.http.HttpRequest request:
    :param string placeholder_uid: Placeholder UID.
    :param string plugin_uid: Plugin UID.
    :param string workspace: Workspace slug.
    :param int position: If given, provided as position for the
        plugin (conflict resolution should take place).
    :param string template_name:
    :param string template_name_ajax: Template used for AJAX requests.
    :return django.http.HttpResponse:
    """
    # Getting dashboard settings for the user. Then get users' layout.
    dashboard_settings = get_or_create_dashboard_settings(request.user)

    if workspace:
        workspace_slug = slugify_workspace(workspace)
        filters = {
            'slug': workspace_slug,
            'user': request.user,
        }
        if not dashboard_settings.allow_different_layouts:
            filters.update({
                'layout_uid': dashboard_settings.layout_uid,
            })
        try:
            workspace = DashboardWorkspace._default_manager.get(**filters)
        except ObjectDoesNotExist as e:
            if dashboard_settings.allow_different_layouts:
                message = _('The workspace with slug "{0}" was not foundi.').format(workspace_slug)
            else:
                message = __('The workspace with slug "{0}" does not belong to '
                'layout "{1}".').format(workspace_slug, layout.name)
            messages.info(request, message)
            return redirect('dash.edit_dashboard')

    if dashboard_settings.allow_different_layouts and workspace:
        layout_uid = workspace.layout_uid
    else:
        layout_uid = dashboard_settings.layout_uid

    layout = get_layout(layout_uid=layout_uid, as_instance=True)

    if not validate_placeholder_uid(layout, placeholder_uid):
        raise Http404(_("Invalid placeholder: {0}").format(placeholder))

    if not validate_plugin_uid(plugin_uid):
        raise Http404(_("Invalid plugin name: {0}").format(plugin_uid))

    plugin = plugin_registry.get(plugin_uid)(layout.uid, placeholder_uid)
    plugin.request = request

    if plugin.add_form_template:
        template_name = plugin.add_form_template

    # Template context
    context = {
        'layout': layout,
        'dashboard_settings': dashboard_settings
    }

    obj = DashboardEntry()
    obj.layout_uid = layout.uid
    obj.placeholder_uid = placeholder_uid
    obj.plugin_uid = plugin_uid
    obj.user = request.user
    obj.workspace = workspace

    # If plugin has form, it is configurable which means we have to load the
    # plugin form and validate user input.
    plugin_form = plugin.get_form()
    if plugin_form:
        # If POST request and form data is valid, save the data and redirect
        # to the dashboard edit.
        if 'POST' == request.method:
            form = plugin.get_initialised_create_form_or_404(
                data=request.POST, files=request.FILES
                )
            if form.is_valid():
                # Saving the plugin form data.
                form.save_plugin_data(request=request)

                # Getting the plugin data.
                obj.plugin_data = form.get_plugin_data(request=request)

                # If position given, use it.
                try:
                    position = int(position)
                except Exception as e:
                    position = None

                if position:
                    obj.position = position

                # Save the object.
                obj.save()

                messages.info(request, _('The dashboard widget "{0}" was added '
                                         'successfully.').format(plugin.name))

                # Redirect to the dashboard view.
                if obj.workspace:
                    return redirect(
                        'dash.edit_dashboard', workspace=obj.workspace.slug
                        )
                else:
                    return redirect('dash.edit_dashboard')

        # If POST but data invalid, show the form with errors.
        else:
            form = plugin.get_initialised_create_form_or_404()

        context.update(
            {'form': form, 'plugin_uid': plugin_uid, 'plugin': plugin}
            )

    # If plugin is not configurable, it's just saved as is.
    else:
        obj.save()
        return redirect('dash.edit_dashboard')

    if request.is_ajax():
        template_name = template_name_ajax

    return render_to_response(
        template_name, context, context_instance=RequestContext(request)
        )
Exemplo n.º 6
0
def paste_entry_from_clipboard(request, layout, placeholder_uid, position, \
                         workspace=None, entries=[], check_only=False, \
                         clear_clipboard=True):
    """
    Pastes entry from clipboard to the given placeholder of a workspace
    selected.

    :param django.http.HttpRequest request:
    :param str layout_uid: Placeholder UID.
    :param str placeholder_uid: Placeholder UID.
    :param int position: Position.
    :param mixed workspace: Either str or ``dash.models.DashboardWorkspace``
        instance. If str is given, a database hit occurs in order to obtain
        the ``dash.models.DashboardWorkspace`` instance. Thus, if you have the
        workspace instance already, provide it as is, in order to minify
        database hits.
    :param iterable entries: If given, entries are not fetched but the
        existing iterable is used. Each item in the iterable should be an
        instance of ``dash.models.DashboardEntry``.
    :param bool check_only: If set to True, it's only checked if it's possible
        to paste from clipboard (the ``dashboard_entry.save()`` part is
        skipped, which means that the entry is not saved in the database).
    :return tuple (str, bool): (Plugin name, boolean True) tuple on success
        and (error message, boolean False) on failure.
    """
    clipboard_plugin_data = get_plugin_data_from_clipboard(request, layout.uid)
    if not clipboard_plugin_data:
        return (_("Clipboard is empty!"), False)

    if not validate_placeholder_uid(layout, placeholder_uid):
        return (_("Invalid placeholder `{0}`.").format(placeholder_uid), False)

    user_plugin_uids = get_user_plugin_uids(request.user)

    if isinstance(workspace, DashboardWorkspace):
        workspace_obj = workspace
    else:
        if workspace:
            try:
                workspace_obj = DashboardWorkspace._default_manager \
                                                  .get(slug=workspace)
            except ObjectDoesNotExist as e:
                workspace_obj = None
        else:
            workspace_obj = None

    dashboard_entry = DashboardEntry(
        user=request.user,
        workspace=workspace_obj,
        layout_uid=layout.uid,
        placeholder_uid=placeholder_uid,
        plugin_uid=clipboard_plugin_data['plugin_uid'],
        plugin_data=clipboard_plugin_data['plugin_data'],
        position=position)

    # We should now check if we have a space for pasting the plugin. For that
    # we should get the plugin and see if there's a space available for
    # the (workspace, placeholder, user) triple given.

    # Get the plugin.
    plugin = dashboard_entry.get_plugin()

    if not plugin.uid in user_plugin_uids:
        return (_("You're not allowed to "
                  "use the {0} plugin.".format(safe_text(plugin.name))), False)

    # Getting occupied cells
    placeholder = layout.get_placeholder(placeholder_uid)
    occupied_cells = build_cells_matrix(request.user,
                                        layout,
                                        placeholder,
                                        workspace=workspace)

    # Get cells occupied by plugin widget.
    widget_occupied_cells = get_occupied_cells(layout,
                                               placeholder,
                                               plugin.uid,
                                               position,
                                               check_boundaries=True)

    if widget_occupied_cells is not False \
       and not lists_overlap(widget_occupied_cells, occupied_cells):

        try:
            if not check_only:
                # Save data
                dashboard_entry.save()

                # Clear the clipboard
                clear_clipboard_data(request, layout.uid)

            return (plugin.uid, True)
        except Exception as e:
            return (str(e), False)
Exemplo n.º 7
0
def paste_entry_from_clipboard(request, layout, placeholder_uid, position, \
                         workspace=None, entries=[], check_only=False, \
                         clear_clipboard=True):
    """
    Pastes entry from clipboard to the given placeholder of a workspace
    selected.

    :param django.http.HttpRequest request:
    :param str layout_uid: Placeholder UID.
    :param str placeholder_uid: Placeholder UID.
    :param int position: Position.
    :param mixed workspace: Either str or ``dash.models.DashboardWorkspace``
        instance. If str is given, a database hit occurs in order to obtain
        the ``dash.models.DashboardWorkspace`` instance. Thus, if you have the
        workspace instance already, provide it as is, in order to minify
        database hits.
    :param iterable entries: If given, entries are not fetched but the
        existing iterable is used. Each item in the iterable should be an
        instance of ``dash.models.DashboardEntry``.
    :param bool check_only: If set to True, it's only checked if it's possible
        to paste from clipboard (the ``dashboard_entry.save()`` part is
        skipped, which means that the entry is not saved in the database).
    :return tuple (str, bool): (Plugin name, boolean True) tuple on success
        and (error message, boolean False) on failure.
    """
    clipboard_plugin_data = get_plugin_data_from_clipboard(request, layout.uid)
    if not clipboard_plugin_data:
        return (_("Clipboard is empty!"), False)

    if not validate_placeholder_uid(layout, placeholder_uid):
        return (_("Invalid placeholder `{0}`.").format(placeholder_uid), False)

    user_plugin_uids = get_user_plugin_uids(request.user)

    if isinstance(workspace, DashboardWorkspace):
        workspace_obj = workspace
    else:
        if workspace:
            try:
                workspace_obj = DashboardWorkspace._default_manager \
                                                  .get(slug=workspace)
            except ObjectDoesNotExist as e:
                workspace_obj = None
        else:
            workspace_obj = None

    dashboard_entry = DashboardEntry(
        user = request.user,
        workspace = workspace_obj,
        layout_uid = layout.uid,
        placeholder_uid = placeholder_uid,
        plugin_uid = clipboard_plugin_data['plugin_uid'],
        plugin_data = clipboard_plugin_data['plugin_data'],
        position = position
        )

    # We should now check if we have a space for pasting the plugin. For that
    # we should get the plugin and see if there's a space available for
    # the (workspace, placeholder, user) triple given.

    # Get the plugin.
    plugin = dashboard_entry.get_plugin()

    if not plugin.uid in user_plugin_uids:
        return (_("You're not allowed to "
                  "use the {0} plugin.".format(safe_text(plugin.name))), False)

    # Getting occupied cells
    placeholder = layout.get_placeholder(placeholder_uid)
    occupied_cells = build_cells_matrix(
        request.user,
        layout,
        placeholder,
        workspace = workspace
        )

    # Get cells occupied by plugin widget.
    widget_occupied_cells = get_occupied_cells(
        layout, placeholder, plugin.uid, position, check_boundaries=True
        )

    if widget_occupied_cells is not False \
       and not lists_overlap(widget_occupied_cells, occupied_cells):

        try:
            if not check_only:
                # Save data
                dashboard_entry.save()

                # Clear the clipboard
                clear_clipboard_data(request, layout.uid)

            return (plugin.uid, True)
        except Exception as e:
            return (str(e), False)