Example #1
0
def create_content_gallery(form):
    gal = Gallery()
    gal.title = form.cleaned_data["title"]
    gal.slug = slugify(form.cleaned_data["title"])
    gal.pubdate = datetime.now()
    gal.save()
    return gal
Example #2
0
def new_gallery(request):
    """Creates a new gallery."""

    if request.method == "POST":
        form = GalleryForm(request.POST)
        if form.is_valid():
            data = form.data

            # Creating the gallery

            gal = Gallery()
            gal.title = data["title"]
            gal.subtitle = data["subtitle"]
            gal.slug = slugify(data["title"])
            gal.pubdate = datetime.now()
            gal.save()

            # Attach user

            userg = UserGallery()
            userg.gallery = gal
            userg.mode = "W"
            userg.user = request.user
            userg.save()
            return redirect(gal.get_absolute_url())
        else:
            return render_template("gallery/gallery/new.html", {"form": form})
    else:
        form = GalleryForm()
        return render_template("gallery/gallery/new.html", {"form": form})
Example #3
0
def new_gallery(request):
    '''
    Creates a new gallery
    '''
    if request.method == 'POST':
        form = GalleryForm(request.POST)
        if form.is_valid():
            data = form.data
            # Creating the gallery
            gal = Gallery()
            gal.title = data['title']
            gal.subtitle = data['subtitle']
            gal.slug = slugify(data['title'])
            gal.pubdate = datetime.now()
            gal.save()

            # Attach user
            userg = UserGallery()
            userg.gallery = gal
            userg.mode = 'W'
            userg.user = request.user
            userg.save()

            return redirect(gal.get_absolute_url())

        else:
            # TODO: add errors to the form and return it
            raise Http404
    else:
        form = GalleryForm()
        return render_template('gallery/new_gallery.html', {
            'form': form
        })
Example #4
0
    def set_avatar_from_file(self, avatar, filename='avatar.png'):
        """
        Updates the avatar of this user from a file, creating a gallery on his account
        if needed and adding the avatar to the gallery.
        :param avatar: The avatar file (file-like object).
        :param filename: The file name, including the type extension.
        """
        user_gallery = UserGallery.objects.filter(gallery__title=ZDS_APP['gallery']['avatars_gallery'], user=self.user)\
            .first()

        if not user_gallery:
            gallery = Gallery()
            gallery.title = ZDS_APP['gallery']['avatars_gallery']
            gallery.subtitle = ''
            gallery.slug = slugify(ZDS_APP['gallery']['avatars_gallery'])
            gallery.pubdate = datetime.now()
            gallery.save()

            user_gallery = UserGallery()
            user_gallery.gallery = gallery
            user_gallery.mode = GALLERY_WRITE
            user_gallery.user = self.user
            user_gallery.save()

        image = Image()
        image.title = _('Avatar')
        image.legend = _('Avatar importé')
        image.gallery = user_gallery.gallery
        image.physical = get_thumbnailer(avatar, relative_name=filename)
        image.pubdate = datetime.now()
        image.save()

        self.avatar_url = image.get_absolute_url()
Example #5
0
def new_gallery(request):
    """Creates a new gallery."""

    if request.method == "POST":
        form = GalleryForm(request.POST)
        if form.is_valid():
            data = form.data

            # Creating the gallery

            gal = Gallery()
            gal.title = data["title"]
            gal.subtitle = data["subtitle"]
            gal.slug = slugify(data["title"])
            gal.pubdate = datetime.now()
            gal.save()

            # Attach user

            userg = UserGallery()
            userg.gallery = gal
            userg.mode = "W"
            userg.user = request.user
            userg.save()
            return redirect(gal.get_absolute_url())
        else:
            return render_template("gallery/gallery/new.html", {"form": form})
    else:
        form = GalleryForm()
        return render_template("gallery/gallery/new.html", {"form": form})
Example #6
0
    def perform_create(self, title, user, subtitle=""):
        """Create gallery

        :param title: title
        :type title: str
        :param user:  the user
        :type user: zds.member.models.User
        :param subtitle: subtitle
        :type subtitle: str
        :rtype: Gallery
        """
        gallery = Gallery(title=title)
        gallery.subtitle = subtitle
        gallery.slug = slugify(title)
        gallery.pubdate = datetime.datetime.now()
        gallery.save()

        user_gallery = UserGallery(gallery=gallery,
                                   user=user,
                                   mode=GALLERY_WRITE)
        user_gallery.save()

        self.gallery = gallery
        self.users_and_permissions = {user.pk: {"read": True, "write": True}}

        return self.gallery
Example #7
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)
Example #8
0
    def form_valid(self, form):
        gallery = Gallery()
        gallery.title = form.cleaned_data['title']
        gallery.subtitle = form.cleaned_data['subtitle']
        gallery.slug = slugify(form.cleaned_data['title'])
        gallery.pubdate = datetime.now()
        gallery.save()

        # Attach user :
        userg = UserGallery()
        userg.gallery = gallery
        userg.mode = 'W'
        userg.user = self.request.user
        userg.save()

        return HttpResponseRedirect(gallery.get_absolute_url())
Example #9
0
def create_gallery_for_article(content):
    # Creating the gallery
    gal = Gallery()
    gal.title = content.title
    gal.slug = slugify(content.title)
    gal.pubdate = datetime.now()
    gal.save()

    # Attach user to gallery
    for user in content.authors.all():
        userg = UserGallery()
        userg.gallery = gal
        userg.mode = "W"  # write mode
        userg.user = user
        userg.save()
    content.gallery = gal

    if not os.path.exists(gal.get_gallery_path()):
        os.makedirs(gal.get_gallery_path())

    return gal
Example #10
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)
Example #11
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)
Example #12
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)