Example #1
0
def presentation_detail(request, id):
    p = Presentation.get_by_id_for_request(id, request)
    if not p:
        return dict(result='error')

    flash = request.GET.get('flash') == '1'

    # Propagate the flash URL paramater into all image URLs to control the "Vary: cookie" header
    # that breaks caching in Flash/Firefox.  Also add the username from the request to make sure
    # different users don't use each other's cached images.
    def add_flash_parameter(url, request):
        u = create_proxy_url_if_needed(url, request)
        if flash:
            u = u + ('&' if u.find('?') > -1 else '?') \
                  + ('flash=1&user=%s' % (request.user.id if request.user.is_authenticated() else -1))
        return u

    return dict(id=p.id,
                name=p.name,
                title=p.title,
                hidden=p.hidden,
                description=p.description,
                created=p.created.isoformat(),
                modified=p.modified.isoformat(),
                content=_presentation_items_as_json(p.items.select_related('record').filter(hidden=False),
                                         owner=request.user if request.user.is_authenticated() else None,
                                         process_url=lambda url:add_flash_parameter(url, request))
            )
Example #2
0
def download(request, id, template):

    return_url = request.GET.get('next', reverse('presentation-browse'))
    presentation = Presentation.get_by_id_for_request(id, request)
    if not presentation:
        return HttpResponseRedirect(return_url)

    g = PowerPointGenerator(presentation, request.user)
    filename = os.tempnam()
    try:
        g.generate(template, filename)
        with open(filename, mode="rb") as f:
            response = HttpResponse(
                content=f.read(),
                mimetype=
                'application/vnd.openxmlformats-officedocument.presentationml.presentation'
            )
        response[
            'Content-Disposition'] = 'attachment; filename=%s.pptx' % presentation.name
        return response
    finally:
        try:
            os.unlink(filename)
        except:
            pass
Example #3
0
def download(request, id):

    return_url = validate_next_link(request.GET.get('next'),
                                    reverse('presentation-browse'))
    presentation = Presentation.get_by_id_for_request(id, request)
    if not presentation:
        return HttpResponseRedirect(return_url)

    color = request.GET.get('color')
    if not color in COLORS.keys():
        color = sorted(COLORS.keys())[0]
    titles = request.GET.get('titles', 'yes') == 'yes'
    metadata = not (request.GET.get('metadata', 'no') != 'yes')

    g = PowerPointGenerator(presentation, request.user)
    with tempfile.TemporaryFile() as zipfile:
        g.generate(zipfile, color, titles, metadata)
        zipfile.seek(0)
        response = HttpResponse(
            content=zipfile.read(),
            content_type='application/vnd.openxmlformats-officedocument'
            '.presentationml.presentation')
        response['Content-Disposition'] = \
            'attachment; filename=%s.pptx' % presentation.name
        return response
Example #4
0
def presentation_detail(request, id):
    p = Presentation.get_by_id_for_request(id, request)
    if not p:
        return dict(result='error')

    flash = request.GET.get('flash') == '1'

    # Propagate the flash URL paramater into all image URLs to control the
    # "Vary: cookie" header that breaks caching in Flash/Firefox.  Also add
    # the username from the request to make sure
    # different users don't use each other's cached images.
    def add_flash_parameter(url, request):
        u = create_proxy_url_if_needed(url, request)
        if flash:
            userid = request.user.id if request.user.is_authenticated() else -1
            joiner = '&' if u.find('?') > -1 else '?'
            u = u + joiner + ('flash=1&user=%s' % userid)
        return u

    content = _presentation_items_as_json(
        p.items.select_related('record').filter(hidden=False),
        owner=request.user if request.user.is_authenticated() else None,
        process_url=lambda url: add_flash_parameter(url, request))

    return dict(
        id=p.id,
        name=p.name,
        title=p.title,
        hidden=p.hidden,
        description=p.description,
        created=p.created.isoformat(),
        modified=p.modified.isoformat(),
        content=content,
    )
Example #5
0
def get_media_for_record(recordid, user=None, passwords={}):
    """
    Returns all media accessible to the user either directly through collections
    or indirectly through presentations.
    A user always must have access to the storage where the media is stored.
    """
    from rooibos.presentation.models import Presentation
    
    print str(recordid)
    #record_id = getattr(record, 'id', record)
    print 'recordid '+ str(recordid)
    if isinstance(recordid, Record):
        record_id = recordid.id        
    else:
        record_id = recordid
    if DEBUG:
        print "RECORD ID: " + str(record_id)
    record = Record.filter_one_by_access(user, record_id)
    if DEBUG:
        print "record filtered"

    if not record:
        print "not record in storage/init/get_media"
        # Try to get to record through an accessible presentation -
        # own presentations don't count, since it's already established that owner
        # doesn't have access to the record.
        pw_q = Q(
            # Presentation must not have password
            Q(password=None) | Q(password='') |
            # or must know password
            Q(id__in=Presentation.check_passwords(passwords))
        )
        access_q = Q(
            # Must have access to presentation
            id__in=filter_by_access(user, Presentation),
            # and presentation must not be archived
            hidden=False
        )
        accessible_presentations = Presentation.objects.filter(
            pw_q, access_q, items__record__id=record_id)
        # Now get all the presentation owners so we can check if any of them have access
        # to the record
        owners = User.objects.filter(id__in=accessible_presentations.values('owner'))
        if not any(Record.filter_one_by_access(owner, record_id) for owner in owners):
            if DEBUG:
                print "Media.objects.none() is being returned"
            return Media.objects.none()
        #print "how many media objects: "+str(Media.objects.count())
        #print "data: "+str(Media.objects.all().values("record__id", "url"))
    print "media filter filtered"
    media_filter = Media.objects.filter(
        record__id=record_id,
        #storage__id__in=filter_by_access(user, Storage),
        )
    if not media_filter:
        print "oh no, no media there on line 82 of storage/__init__"
        print str(Media.objects.all())
        print "Count: " + str(Media.objects.count())
    return media_filter
Example #6
0
def powerpointexportviewer(obj, request, objid=None):
    if obj:
        if not isinstance(obj, Presentation):
            return None
    else:
        obj = Presentation.get_by_id_for_request(objid, request)
        if not obj:
            return None
    return PowerPointExportViewer(obj, request.user)
Example #7
0
def powerpointexportviewer(obj, request, objid=None):
    if obj:
        if not isinstance(obj, Presentation):
            return None
    else:
        obj = Presentation.get_by_id_for_request(objid, request)
        if not obj:
            return None
    return PowerPointExportViewer(obj, request.user)
Example #8
0
def megazine(obj, request, objid=None):
    if not getattr(settings, 'MEGAZINE_PUBLIC_KEY', None):
        return None
    if obj:
        if not isinstance(obj, Presentation):
            return None
    else:
        obj = Presentation.get_by_id_for_request(objid, request)
        if not obj:
            return None
    return MegazineViewer(obj, request.user)
Example #9
0
def megazine(obj, request, objid=None):
    if not getattr(settings, 'MEGAZINE_PUBLIC_KEY', None):
        return None
    if obj:
        if not isinstance(obj, Presentation):
            return None
    else:
        obj = Presentation.get_by_id_for_request(objid, request)
        if not obj:
            return None
    return MegazineViewer(obj, request.user)
Example #10
0
    def view_content(self, request, id, name):
        presentation = Presentation.get_by_id_for_request(id, request)
        if not presentation:
            raise Http404()

        items = presentation.items.select_related('record').filter(hidden=False)

        return render_to_response('megazine/megazine-content.mz3',
                                  {'items': items,
                                   'licensekey': getattr(settings, 'MEGAZINE_PUBLIC_KEY', None),
                                   },
                                  context_instance=RequestContext(request))
Example #11
0
    def view(self, request, id, name, template='megazine/megazine.html'):
        return_url = request.GET.get('next', reverse('presentation-browse'))
        presentation = Presentation.get_by_id_for_request(id, request)
        if not presentation:
            if not request.user.is_authenticated():
                return HttpResponseRedirect(reverse('login') + '?next=' + request.get_full_path())
            else:
                return HttpResponseRedirect(return_url)

        return render_to_response(template,
                                  {'presentation': presentation,
                                   'next': request.GET.get('next'),
                                   },
                                  context_instance=RequestContext(request))
Example #12
0
    def view(self, request, id, name):
        return_url = request.GET.get("next", reverse("presentation-browse"))
        presentation = Presentation.get_by_id_for_request(id, request)
        if not presentation:
            if not request.user.is_authenticated():
                return HttpResponseRedirect(reverse("login") + "?next=" + request.get_full_path())
            else:
                return HttpResponseRedirect(return_url)

        return render_to_response(
            "presentations/mediaviewer.html",
            {"presentation": presentation, "return_url": return_url},
            context_instance=RequestContext(request),
        )
Example #13
0
def content(request, presentation_id):
    presentation = Presentation.get_by_id_for_request(presentation_id, request)
    if not presentation:
        raise Http404()

    try:
        width = int(request.GET.get('width', 1000))
    except ValueError:
        width = 1000

    items = presentation.items.select_related('record').filter(hidden=False)

    return render_to_response('megazine_content.mz3',
        {'items': items,
         'licensekey': getattr(settings, 'MEGAZINE_PUBLIC_KEY', None),
         'width': width / 2 - 100,
         'height': width - 200,
         },
        context_instance=RequestContext(request))
Example #14
0
def get_media_for_record(record, user=None, passwords={}):
    """
    Returns all media accessible to the user either directly through collections
    or indirectly through presentations.
    A user always must have access to the storage where the media is stored.
    """
    from rooibos.presentation.models import Presentation

    record_id = getattr(record, 'id', record)
    record = Record.filter_one_by_access(user, record_id)
	
    if not record:
        print "Media is not a record"
     	# Try to get to record through an accessible presentation -
        # own presentations don't count, since it's already established that owner
        # doesn't have access to the record.
        pw_q = Q(
            # Presentation must not have password
            Q(password=None) | Q(password='') |
            # or must know password
            Q(id__in=Presentation.check_passwords(passwords))
        )
        access_q = Q(
            # Must have access to presentation
            id__in=filter_by_access(user, Presentation),
            # and presentation must not be archived
            hidden=False
        )
        accessible_presentations = Presentation.objects.filter(
            pw_q, access_q, items__record__id=record_id)
        # Now get all the presentation owners so we can check if any of them have access
        # to the record
        owners = User.objects.filter(id__in=accessible_presentations.values('owner'))
        if not any(Record.filter_one_by_access(owner, record_id) for owner in owners):
            return Media.objects.none()	
        
    print record_id
    print filter_by_access(user, Storage)

    return Media.objects.filter(
        record__id=record_id,
        storage__id__in=filter_by_access(user, Storage),
    )
Example #15
0
def get_media_for_record(record, user=None, passwords={}):
    """
    Returns all media accessible to the user either directly through
    collections or indirectly through presentations.
    A user always must have access to the storage where the media is stored.
    """
    from rooibos.presentation.models import Presentation

    record_id = getattr(record, 'id', record)
    record = Record.filter_one_by_access(user, record_id)

    if not record:
        # Try to get to record through an accessible presentation -
        # own presentations don't count, since it's already established
        # that owner doesn't have access to the record.
        pw_q = Q(
            # Presentation must not have password
            Q(password=None) | Q(password='') |
            # or must know password
            Q(id__in=Presentation.check_passwords(passwords))
        )
        access_q = Q(
            # Must have access to presentation
            id__in=filter_by_access(user, Presentation),
            # and presentation must not be archived
            hidden=False
        )
        accessible_presentations = Presentation.objects.filter(
            pw_q, access_q, items__record__id=record_id)
        # Now get all the presentation owners so we can check if any of them
        # have access to the record
        owners = User.objects.filter(
            id__in=accessible_presentations.values('owner'))
        if not any(
                Record.filter_one_by_access(owner, record_id)
                for owner in owners):
            return Media.objects.none()

    return Media.objects.filter(
        record__id=record_id,
        storage__id__in=filter_by_access(user, Storage),
    )
Example #16
0
def download(request, id, template):

    return_url = request.GET.get('next', reverse('presentation-browse'))
    presentation = Presentation.get_by_id_for_request(id, request)
    if not presentation:
        return HttpResponseRedirect(return_url)

    g = PowerPointGenerator(presentation, request.user)
    filename = os.tempnam()
    try:
        g.generate(template, filename)
        with open(filename, mode="rb") as f:
            response = HttpResponse(content=f.read(),
                mimetype='application/vnd.openxmlformats-officedocument.presentationml.presentation')
        response['Content-Disposition'] = 'attachment; filename=%s.pptx' % presentation.name
        return response
    finally:
        try:
            os.unlink(filename)
        except:
            pass
Example #17
0
    def view(self, request, id, name):
        return_url = request.GET.get('next', reverse('presentation-browse'))
        presentation = Presentation.get_by_id_for_request(id, request)
        if not presentation:
            if not request.user.is_authenticated():
                return HttpResponseRedirect(reverse('login') + '?next=' + request.get_full_path())
            else:
                return HttpResponseRedirect(return_url)

        passwords = request.session.get('passwords', dict())

        response = HttpResponse(mimetype='application/pdf')

        pagesize = getattr(pagesizes, settings.PDF_PAGESIZE)
        width, height = pagesize

        class DocTemplate(BaseDocTemplate):
            def afterPage(self):
                self.handle_nextPageTemplate('Later')

        def column_frame(left):
            return Frame(left, inch / 2,
                           width=width / 2 - 0.75 * inch, height = height - inch,
                          leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, showBoundary=False)

        def prepare_first_page(canvas, document):
            p1 = Paragraph(presentation.title, styles['Heading'])
            p2 = Paragraph(presentation.owner.get_full_name(), styles['SubHeading'])
            avail_width = width - inch
            avail_height = height - inch
            w1, h1 = p1.wrap(avail_width, avail_height)
            w2, h2 = p2.wrap(avail_width, avail_height)
            f = Frame(inch / 2, inch / 2, width - inch, height - inch,
                      leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0)
            f.addFromList([p1, p2], canvas)

            document.pageTemplate.frames[0].height -= h1 + h2 + inch / 2
            document.pageTemplate.frames[1].height -= h1 + h2 + inch / 2

            canvas.saveState()
            canvas.setStrokeColorRGB(0, 0, 0)
            canvas.line(width / 2, inch / 2, width / 2, height - inch - h1 - h2)
            canvas.restoreState()

        def prepare_later_page(canvas, document):
            canvas.saveState()
            canvas.setStrokeColorRGB(0, 0, 0)
            canvas.line(width / 2, inch / 2, width / 2, height - inch / 2)
            canvas.restoreState()


        styles = getStyleSheet()

        items = presentation.items.filter(hidden=False)

        content = []

        for index, item in enumerate(items):
            text = []
            values = item.get_fieldvalues(owner=request.user)
            for value in values:
                text.append('<b>%s</b>: %s<br />' % (value.resolved_label, value.value))
            annotation = item.annotation
            if annotation:
                text.append('<b>%s</b>: %s<br />' % ('Annotation', annotation))
            try:
                p = Paragraph(''.join(text), styles['Normal'])
            except (AttributeError, KeyError, IndexError):
                # this sometimes triggers an error in reportlab
                p = None
            if p:
                image = get_image_for_record(item.record, presentation.owner, 100, 100, passwords)
                if image:
                    try:
                        i = flowables.Image(image, kind='proportional',
                                            width=1 * inch, height=1 * inch)
                        p = flowables.ParagraphAndImage(p, i)
                    except IOError:
                        pass
                content.append(flowables.KeepTogether(
                    [Paragraph('%s/%s' % (index + 1, len(items)), styles['SlideNumber']), p]))

        first_template = PageTemplate(id='First',
                                      frames=[column_frame(inch / 2), column_frame(width / 2 + 0.25 * inch)],
                                      pagesize=pagesize,
                                      onPage=prepare_first_page)
        later_template = PageTemplate(id='Later',
                                      frames=[column_frame(inch / 2), column_frame(width / 2 + 0.25 * inch)],
                                      pagesize=pagesize,
                                      onPage=prepare_later_page)

        doc = DocTemplate(response)
        doc.addPageTemplates([first_template, later_template])
        doc.build(content)

        return response
Example #18
0
 def create_instance(self, row):
     if not self.users.has_key(str(row.UserID)):
         return None
     return Presentation()
Example #19
0
 def assert_published(self):
     presentations = Presentation.objects.filter(Presentation.published_q(),
                                                 owner=self.user)
     self.assertEqual(1, presentations.count())
     self.assertEqual(self.presentation.id, presentations[0].id)
Example #20
0
 def assertNotPublished(self):
     presentations = Presentation.objects.filter(Presentation.published_Q(), owner=self.user)
     self.assertEqual(0,presentations.count())
Example #21
0
    def view(self, request, id, name):
        return_url = request.GET.get("next", reverse("presentation-browse"))
        presentation = Presentation.get_by_id_for_request(id, request)
        if not presentation:
            if not request.user.is_authenticated():
                return HttpResponseRedirect(reverse("login") + "?next=" + request.get_full_path())
            else:
                return HttpResponseRedirect(return_url)

        passwords = request.session.get("passwords", dict())

        response = HttpResponse(mimetype="application/pdf")

        pagesize = getattr(pagesizes, settings.PDF_PAGESIZE)
        width, height = pagesize

        p = canvas.Canvas(response, pagesize=pagesize)
        styles = getStyleSheet()

        items = presentation.items.filter(hidden=False)

        def decoratePage():
            p.saveState()
            p.setDash(2, 2)
            p.setStrokeColorRGB(0.8, 0.8, 0.8)
            p.line(width / 2, inch / 2, width / 2, height - inch / 2)
            p.line(inch / 2, height / 3, width - inch / 2, height / 3)
            p.line(inch / 2, height / 3 * 2, width - inch / 2, height / 3 * 2)
            p.setFont("Helvetica", 8)
            p.setFillColorRGB(0.8, 0.8, 0.8)
            p.drawString(inch, height / 3 - 3 * inch / 72, "Cut here")
            p.drawString(inch, height / 3 * 2 - 3 * inch / 72, "Cut here")
            p.translate(width / 2 - 3 * inch / 72, height - inch)
            p.rotate(270)
            p.drawString(0, 0, "Fold here")
            p.restoreState()

        def getParagraph(*args, **kwargs):
            try:
                return Paragraph(*args, **kwargs)
            except (AttributeError, IndexError):
                return None

        def drawCard(index, item):
            p.saveState()
            p.translate(0, height / 3 * (2 - index % 3))

            # retrieve record while making sure it's accessible to presentation owner
            record = Record.filter_one_by_access(presentation.owner, item.record.id)

            if record:
                image = get_image_for_record(record, presentation.owner, 800, 800, passwords)
                if image:
                    p.drawImage(
                        image,
                        inch / 2,
                        inch / 2,
                        width=width / 2 - inch,
                        height=height / 3 - inch,
                        preserveAspectRatio=True,
                    )
                f = Frame(
                    width / 2 + inch / 2,
                    inch / 2,
                    width=width / 2 - inch,
                    height=height / 3 - inch,
                    leftPadding=0,
                    bottomPadding=0,
                    rightPadding=0,
                    topPadding=0,
                )
                data = []
                data.append(getParagraph("%s/%s" % (index + 1, len(items)), styles["SlideNumber"]))
                values = item.get_fieldvalues(owner=request.user)
                for value in values:
                    v = value.value if len(value.value) < 100 else value.value[:100] + "..."
                    data.append(getParagraph("<b>%s:</b> %s" % (value.resolved_label, v), styles["Data"]))
                annotation = item.annotation
                if annotation:
                    data.append(getParagraph("<b>%s:</b> %s" % ("Annotation", annotation), styles["Data"]))
                data = filter(None, data)
                f.addFromList(data, p)
                if data:
                    p.setFont("Helvetica", 8)
                    p.setFillColorRGB(0, 0, 0)
                    p.drawRightString(width - inch / 2, inch / 2, "...")

            p.restoreState()

        for index, item in enumerate(items):
            if index % 3 == 0:
                if index > 0:
                    p.showPage()
                decoratePage()
            drawCard(index, item)

        p.showPage()
        p.save()
        return response
Example #22
0
 def assert_published(self):
     presentations = Presentation.objects.filter(
         Presentation.published_q(), owner=self.user)
     self.assertEqual(1, presentations.count())
     self.assertEqual(self.presentation.id, presentations[0].id)