Esempio n. 1
0
    def form_valid(self, form):

        # create the object:
        self.content = PublishableContent()
        self.content.title = form.cleaned_data["title"]
        self.content.description = form.cleaned_data["description"]
        self.content.type = form.cleaned_data["type"]
        self.content.licence = self.request.user.profile.licence  # Use the preferred license of the user if it exists
        self.content.source = form.cleaned_data["source"]
        self.content.creation_date = datetime.now()

        # Creating the gallery
        gal = Gallery()
        gal.title = form.cleaned_data["title"]
        gal.slug = slugify(form.cleaned_data["title"])
        gal.pubdate = datetime.now()
        gal.save()

        self.content.gallery = gal
        self.content.save()
        # create image:
        if "image" in self.request.FILES:
            img = Image()
            img.physical = self.request.FILES["image"]
            img.gallery = gal
            img.title = self.request.FILES["image"]
            img.slug = slugify(self.request.FILES["image"].name)
            img.pubdate = datetime.now()
            img.save()
            self.content.image = img

        self.content.save()

        # We need to save the content before changing its author list since it's a many-to-many relationship
        self.content.authors.add(self.request.user)

        self.content.ensure_author_gallery()
        self.content.save()
        # Add subcategories on tutorial
        for subcat in form.cleaned_data["subcategory"]:
            self.content.subcategory.add(subcat)

        self.content.save()

        # create a new repo :
        init_new_repo(
            self.content,
            form.cleaned_data["introduction"],
            form.cleaned_data["conclusion"],
            form.cleaned_data["msg_commit"],
        )

        return super(CreateContent, self).form_valid(form)
Esempio n. 2
0
    def form_valid(self, form):

        # create the object:
        self.content = PublishableContent()
        self.content.title = form.cleaned_data["title"]
        self.content.description = form.cleaned_data["description"]
        self.content.type = form.cleaned_data["type"]
        self.content.licence = self.request.user.profile.licence  # Use the preferred license of the user if it exists
        self.content.source = form.cleaned_data["source"]
        self.content.creation_date = datetime.now()

        # Creating the gallery
        gal = create_content_gallery(form)

        # create image:
        if "image" in self.request.FILES:
            mixin = ImageCreateMixin()
            mixin.gallery = gal
            try:
                img = mixin.perform_create(str(_("Icône du contenu")),
                                           self.request.FILES["image"])
            except NotAnImage:
                form.add_error("image", _("Image invalide"))
                return super().form_invalid(form)
            img.pubdate = datetime.now()
        self.content.gallery = gal
        self.content.save()
        if "image" in self.request.FILES:
            self.content.image = img
            self.content.save()

        # We need to save the content before changing its author list since it's a many-to-many relationship
        self.content.authors.add(self.request.user)

        self.content.ensure_author_gallery()
        self.content.save()
        # Add subcategories on tutorial
        for subcat in form.cleaned_data["subcategory"]:
            self.content.subcategory.add(subcat)

        self.content.save()

        # create a new repo :
        init_new_repo(
            self.content,
            form.cleaned_data["introduction"],
            form.cleaned_data["conclusion"],
            form.cleaned_data["msg_commit"],
        )

        return super().form_valid(form)
Esempio n. 3
0
 def handle(self, *args, content: PublishableContent, is_major=False, **options):
     content.current_validation = Validation.objects.filter(content=content, status='PENDING_V').first()
     versioned = content.load_version(sha=content.current_validation.version)
     is_update = content.sha_public
     try:
         published = publish_content(content, versioned, is_major_update=is_major)
     except FailureDuringPublication as e:
         self.stdout.write('Publication failed')
         logging.getLogger(__name__).exception('Failure during publication', exc_info=e)
     else:
         save_validation_state(content, is_update, published, content.current_validation, versioned,
                               options.get('source', ''), is_major, user=content.current_validation.validator,
                               comment=_("Géré depuis la commande d'administration"))
         notify_update(content, is_update, is_major)
         self.stdout.write(_('La contenu a été validé'))
Esempio n. 4
0
    def form_valid(self, form):

        if self.request.FILES["archive"]:
            try:
                zfile = zipfile.ZipFile(self.request.FILES["archive"], "r")
            except zipfile.BadZipfile:
                messages.error(self.request,
                               _("Cette archive n'est pas au format ZIP."))
                return self.form_invalid(form)

            try:
                new_content = UpdateContentWithArchive.extract_content_from_zip(
                    zfile)
            except BadArchiveError as e:
                messages.error(self.request, e.message)
                return super(CreateContentFromArchive, self).form_invalid(form)
            except KeyError as e:
                messages.error(
                    self.request,
                    _(e.message + " n'est pas correctement renseigné."))
                return super(CreateContentFromArchive, self).form_invalid(form)
            else:

                # Warn the user if the license has been changed
                manifest = json_handler.loads(
                    str(zfile.read("manifest.json"), "utf-8"))
                if new_content.licence and "licence" in manifest and manifest[
                        "licence"] != new_content.licence.code:
                    messages.info(
                        self.request,
                        _("la licence « {} » a été appliquée.".format(
                            new_content.licence.code)))

                # first, create DB object (in order to get a slug)
                self.object = PublishableContent()
                self.object.title = new_content.title
                self.object.description = new_content.description
                self.object.licence = new_content.licence
                self.object.type = new_content.type  # change of type is then allowed !!
                self.object.creation_date = datetime.now()

                self.object.save()

                new_content.slug = self.object.slug  # new slug (choosen via DB)

                # Creating the gallery
                gal = Gallery()
                gal.title = new_content.title
                gal.slug = slugify(new_content.title)
                gal.pubdate = datetime.now()
                gal.save()

                # Attach user to gallery
                self.object.gallery = gal
                self.object.save()

                # Add subcategories on tutorial
                for subcat in form.cleaned_data["subcategory"]:
                    self.object.subcategory.add(subcat)

                # We need to save the tutorial before changing its author list since it's a many-to-many relationship
                self.object.authors.add(self.request.user)
                self.object.save()
                self.object.ensure_author_gallery()
                # ok, now we can import
                introduction = ""
                conclusion = ""

                if new_content.introduction:
                    introduction = str(zfile.read(new_content.introduction),
                                       "utf-8")
                if new_content.conclusion:
                    conclusion = str(zfile.read(new_content.conclusion),
                                     "utf-8")

                commit_message = _("Création de « {} »").format(
                    new_content.title)
                init_new_repo(self.object,
                              introduction,
                              conclusion,
                              commit_message=commit_message)

                # copy all:
                versioned = self.object.load_version()
                try:
                    UpdateContentWithArchive.update_from_new_version_in_zip(
                        versioned, new_content, zfile)
                except BadArchiveError as e:
                    self.object.delete()  # abort content creation
                    messages.error(self.request, e.message)
                    return super(CreateContentFromArchive,
                                 self).form_invalid(form)

                # and end up by a commit !!
                commit_message = form.cleaned_data["msg_commit"]

                if not commit_message:
                    commit_message = _(
                        "Importation d'une archive contenant « {} »").format(
                            new_content.title)
                versioned.slug = self.object.slug  # force slug to ensure path resolution
                sha = versioned.repo_update(
                    versioned.title,
                    versioned.get_introduction(),
                    versioned.get_conclusion(),
                    commit_message,
                    update_slug=True,
                )

                # This HAVE TO happen after commiting files (if not, content are None)
                if "image_archive" in self.request.FILES:
                    try:
                        zfile = zipfile.ZipFile(
                            self.request.FILES["image_archive"], "r")
                    except zipfile.BadZipfile:
                        messages.error(
                            self.request,
                            _("L'archive contenant les images n'est pas au format ZIP."
                              ))
                        return self.form_invalid(form)

                    UpdateContentWithArchive.use_images_from_archive(
                        self.request, zfile, versioned, self.object.gallery)

                    commit_message = _(
                        "Utilisation des images de l'archive pour « {} »"
                    ).format(new_content.title)
                    sha = versioned.commit_changes(
                        commit_message)  # another commit

                # of course, need to update sha
                self.object.sha_draft = sha
                self.object.update_date = datetime.now()
                self.object.save()

                self.success_url = reverse("content:view",
                                           args=[versioned.pk, versioned.slug])

        return super(CreateContentFromArchive, self).form_valid(form)
Esempio n. 5
0
class CreateContent(LoggedWithReadWriteHability, FormWithPreview):
    """
    Handle content creation. Since v22 a licence must be explicitly selected
    instead of defaulting to "All rights reserved". Users can however
    set a default licence in their profile.
    """

    template_name = "tutorialv2/create/content.html"
    model = PublishableContent
    form_class = ContentForm
    content = None
    created_content_type = "TUTORIAL"

    def get_form(self, form_class=ContentForm):
        form = super(CreateContent, self).get_form(form_class)
        form.initial["type"] = self.created_content_type
        return form

    def get_context_data(self, **kwargs):
        context = super(CreateContent, self).get_context_data(**kwargs)
        context["editorial_line_link"] = settings.ZDS_APP["content"][
            "editorial_line_link"]
        context["site_name"] = settings.ZDS_APP["site"]["literal_name"]
        return context

    def form_valid(self, form):

        # create the object:
        self.content = PublishableContent()
        self.content.title = form.cleaned_data["title"]
        self.content.description = form.cleaned_data["description"]
        self.content.type = form.cleaned_data["type"]
        self.content.licence = self.request.user.profile.licence  # Use the preferred license of the user if it exists
        self.content.source = form.cleaned_data["source"]
        self.content.creation_date = datetime.now()

        # Creating the gallery
        gal = Gallery()
        gal.title = form.cleaned_data["title"]
        gal.slug = slugify(form.cleaned_data["title"])
        gal.pubdate = datetime.now()
        gal.save()

        self.content.gallery = gal
        self.content.save()
        # create image:
        if "image" in self.request.FILES:
            img = Image()
            img.physical = self.request.FILES["image"]
            img.gallery = gal
            img.title = self.request.FILES["image"]
            img.slug = slugify(self.request.FILES["image"].name)
            img.pubdate = datetime.now()
            img.save()
            self.content.image = img

        self.content.save()

        # We need to save the content before changing its author list since it's a many-to-many relationship
        self.content.authors.add(self.request.user)

        self.content.ensure_author_gallery()
        self.content.save()
        # Add subcategories on tutorial
        for subcat in form.cleaned_data["subcategory"]:
            self.content.subcategory.add(subcat)

        self.content.save()

        # create a new repo :
        init_new_repo(
            self.content,
            form.cleaned_data["introduction"],
            form.cleaned_data["conclusion"],
            form.cleaned_data["msg_commit"],
        )

        return super(CreateContent, self).form_valid(form)

    def get_success_url(self):
        return reverse("content:view",
                       args=[self.content.pk, self.content.slug])
Esempio n. 6
0
    def form_valid(self, form):
        # get database representation and validated version
        db_object = self.object
        versioned = self.versioned_object

        # get initial git path
        old_git_path = db_object.get_repo_path()

        # store data for later
        authors = db_object.authors.all()
        subcats = db_object.subcategory.all()
        tags = db_object.tags.all()
        article = PublishableContent(title=db_object.title,
                                     type='ARTICLE',
                                     creation_date=datetime.now(),
                                     sha_public=db_object.sha_public,
                                     public_version=None,
                                     licence=db_object.licence,
                                     sha_validation=db_object.sha_public,
                                     sha_draft=db_object.sha_public,
                                     image=db_object.image,
                                     source=db_object.source)

        opinion_url = db_object.get_absolute_url_online()
        article.save()
        # add M2M objects
        for author in authors:
            article.authors.add(author)
        for subcat in subcats:
            article.subcategory.add(subcat)
        for tag in tags:
            article.tags.add(tag)
        article.save()
        # add information about the conversion to the original opinion
        db_object.converted_to = article
        db_object.save()

        # clone the repo
        clone_repo(old_git_path, article.get_repo_path())
        versionned_article = article.load_version(sha=article.sha_validation)
        # mandatory to avoid path collision
        versionned_article.slug = article.slug
        article.sha_validation = versionned_article.repo_update(
            versionned_article.title, versionned_article.get_introduction(),
            versionned_article.get_conclusion())
        article.sha_draft = article.sha_validation
        article.save()
        # ask for validation
        validation = Validation()
        validation.content = article
        validation.date_proposition = datetime.now()
        validation.comment_authors = _(
            'Promotion du billet « [{0}]({1}) » en article par [{2}]({3}).'.
            format(article.title, article.get_absolute_url_online(),
                   self.request.user.username,
                   self.request.user.profile.get_absolute_url()))
        validation.version = article.sha_validation
        validation.save()
        # creating the gallery
        gal = Gallery()
        gal.title = db_object.gallery.title
        gal.slug = db_object.gallery.slug
        gal.pubdate = datetime.now()
        gal.save()
        article.gallery = gal
        # save updates
        article.save()
        article.ensure_author_gallery()

        # send message to user
        msg = render_to_string('tutorialv2/messages/opinion_promotion.md', {
            'content': versioned,
            'url': opinion_url,
        })

        bot = get_object_or_404(
            User, username=settings.ZDS_APP['member']['bot_account'])
        send_mp(
            bot,
            article.authors.all(),
            _('Billet promu en article'),
            versionned_article.title,
            msg,
            True,
            direct=False,
            hat=get_hat_from_settings('validation'),
        )

        self.success_url = db_object.get_absolute_url()

        messages.success(
            self.request,
            _('Le billet a bien été promu en article et est en attente de validation.'
              ))

        return super(PromoteOpinionToArticle, self).form_valid(form)
Esempio n. 7
0
    def form_valid(self, form):
        # get database representation and validated version
        db_object = self.object
        versioned = self.versioned_object

        # get initial git path
        old_git_path = db_object.get_repo_path()

        # store data for later
        authors = db_object.authors.all()
        subcats = db_object.subcategory.all()
        tags = db_object.tags.all()
        article = PublishableContent(title=db_object.title,
                                     type='ARTICLE',
                                     creation_date=datetime.now(),
                                     sha_public=db_object.sha_public,
                                     public_version=None,
                                     licence=db_object.licence,
                                     sha_validation=db_object.sha_public,
                                     sha_draft=db_object.sha_public,
                                     image=db_object.image,
                                     source=db_object.source
                                     )

        opinion_url = db_object.get_absolute_url_online()
        article.save()
        # add M2M objects
        for author in authors:
            article.authors.add(author)
        for subcat in subcats:
            article.subcategory.add(subcat)
        for tag in tags:
            article.tags.add(tag)
        article.save()
        # add information about the conversion to the original opinion
        db_object.converted_to = article
        db_object.save()

        # clone the repo
        clone_repo(old_git_path, article.get_repo_path())
        versionned_article = article.load_version(sha=article.sha_validation)
        # mandatory to avoid path collision
        versionned_article.slug = article.slug
        article.sha_validation = versionned_article.repo_update(versionned_article.title,
                                                                versionned_article.get_introduction(),
                                                                versionned_article.get_conclusion())
        article.sha_draft = article.sha_validation
        article.save()
        # ask for validation
        validation = Validation()
        validation.content = article
        validation.date_proposition = datetime.now()
        validation.comment_authors = _('Promotion du billet « [{0}]({1}) » en article par [{2}]({3}).'.format(
            article.title,
            article.get_absolute_url_online(),
            self.request.user.username,
            self.request.user.profile.get_absolute_url()
        ))
        validation.version = article.sha_validation
        validation.save()
        # creating the gallery
        gal = Gallery()
        gal.title = db_object.gallery.title
        gal.slug = db_object.gallery.slug
        gal.pubdate = datetime.now()
        gal.save()
        article.gallery = gal
        # save updates
        article.save()
        article.ensure_author_gallery()

        # send message to user
        msg = render_to_string(
            'tutorialv2/messages/opinion_promotion.md',
            {
                'content': versioned,
                'url': opinion_url,
            })

        bot = get_object_or_404(User, username=settings.ZDS_APP['member']['bot_account'])
        send_mp(
            bot,
            article.authors.all(),
            _('Billet promu en article'),
            versionned_article.title,
            msg,
            True,
            direct=False,
            hat=get_hat_from_settings('validation'),
        )

        self.success_url = db_object.get_absolute_url()

        messages.success(self.request, _('Le billet a bien été promu en article et est en attente de validation.'))

        return super(PromoteOpinionToArticle, self).form_valid(form)