Skip to content

Commit

Permalink
правка топиков с изображениями (WIP)
Browse files Browse the repository at this point in the history
  • Loading branch information
maxcom committed Dec 18, 2024
1 parent 08f21dc commit 36a539c
Show file tree
Hide file tree
Showing 6 changed files with 159 additions and 170 deletions.
85 changes: 0 additions & 85 deletions src/main/java/ru/org/linux/topic/AddTopicRequestValidator.java

This file was deleted.

45 changes: 3 additions & 42 deletions src/main/scala/ru/org/linux/topic/AddTopicController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import org.springframework.web.util.UriComponentsBuilder
import ru.org.linux.auth.*
import ru.org.linux.auth.AuthUtil.MaybeAuthorized
import ru.org.linux.csrf.{CSRFNoAuto, CSRFProtectionService}
import ru.org.linux.gallery.{ImageService, UploadedImagePreview}
import ru.org.linux.gallery.UploadedImagePreview
import ru.org.linux.group.{Group, GroupDao, GroupPermissionService}
import ru.org.linux.markup.MessageTextService
import ru.org.linux.poll.{Poll, PollVariant}
Expand Down Expand Up @@ -89,7 +89,7 @@ object AddTopicController {
class AddTopicController(searchQueueSender: SearchQueueSender, captcha: CaptchaService, sectionService: SectionService,
tagService: TagService, userService: UserService, prepareService: TopicPrepareService,
permissionService: GroupPermissionService, addTopicRequestValidator: AddTopicRequestValidator,
imageService: ImageService, topicService: TopicService,
topicService: TopicService,
@Qualifier("realtimeHubWS") realtimeHubWS: ActorRef[RealtimeEventHub.Protocol],
renderService: MarkdownFormatter, groupDao: GroupDao, dupeProtector: FloodProtector,
ipBlockDao: IPBlockDao, servletContext: ServletContext) {
Expand Down Expand Up @@ -142,45 +142,6 @@ class AddTopicController(searchQueueSender: SearchQueueSender, captcha: CaptchaS
params.result()
}

private def processUploads(form: AddTopicRequest, errors: BindingResult)
(implicit postingUser: AuthorizedSession): (Option[UploadedImagePreview], Seq[UploadedImagePreview]) = {
val section = sectionService.getSection(form.group.sectionId)

val additionalImagesNonNull = Option(form.additionalImage).getOrElse(Array.empty)
val additionalImagesLimit = permissionService.additionalImageLimit(section)

val (imagePreview: Option[UploadedImagePreview], additionalImagePreviews: Seq[UploadedImagePreview]) =
if (permissionService.isImagePostingAllowed(section) &&
permissionService.isTopicPostingAllowed(form.group)) {
val main = imageService.processUpload(Option(form.uploadedImage), form.image, errors)

val additionalImagePreviews =
Option(form.additionalUploadedImages)
.getOrElse(Array.empty)
.view
.zipAll(additionalImagesNonNull, null, null)
.take(additionalImagesLimit)
.flatMap { case (existing, upload) =>
imageService.processUpload(Option(existing), upload, errors)
}.toVector

(main, additionalImagePreviews)
} else {
(None, Seq.empty)
}

form.setUploadedImage(imagePreview.map(_.mainFile.getName).orNull)

form.setAdditionalUploadedImages((additionalImagePreviews.map(_.mainFile.getName) ++
Vector.fill(additionalImagesLimit - additionalImagePreviews.size)(null)).toArray)

if (section.isImagepost && imagePreview.isEmpty) {
errors.reject(null, "Изображение отсутствует")
}

(imagePreview, additionalImagePreviews)
}

@RequestMapping(value = Array("/add.jsp"), method = Array(RequestMethod.POST))
@CSRFNoAuto
def doAdd(request: HttpServletRequest, @Valid @ModelAttribute("form") form: AddTopicRequest, errors: BindingResult,
Expand Down Expand Up @@ -220,7 +181,7 @@ class AddTopicController(searchQueueSender: SearchQueueSender, captcha: CaptchaS

val (imagePreview, additionalImagePreviews) = postingUser.opt match {
case Some(authorized) =>
processUploads(form, errors)(authorized)
topicService.processUploads(form, group, errors)(authorized)
case None =>
(None, Seq.empty)
}
Expand Down
33 changes: 32 additions & 1 deletion src/main/scala/ru/org/linux/topic/AddTopicRequest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,19 @@ import ru.org.linux.group.Group
import ru.org.linux.poll.Poll
import ru.org.linux.user.User

import java.util
import scala.beans.{BeanProperty, BooleanBeanProperty}

trait ImageTopicRequest {
def additionalImage: Array[MultipartFile]
def uploadedImage: String
def image: MultipartFile
def additionalUploadedImages: Array[String]

def uploadedImage_=(value: String): Unit
def additionalUploadedImages_=(value: Array[String]): Unit
}

class AddTopicRequest(
@BeanProperty var title: String = null,
@BeanProperty var msg: String = null,
Expand All @@ -39,9 +50,29 @@ class AddTopicRequest(
@BeanProperty var draft: String = null,
@BooleanBeanProperty var allowAnonymous: Boolean = true,
@BeanProperty var image: MultipartFile = null,
@BeanProperty var uploadedImage: String = null) {
@BeanProperty var uploadedImage: String = null) extends ImageTopicRequest {
def this() = this(title = null) // нужен конструктор по умолчанию для spring

def isPreviewMode: Boolean = preview != null
def isDraftMode: Boolean = draft != null
}

class EditTopicRequest(
@BeanProperty var url: String = null,
@BeanProperty var linktext: String = null,
@BeanProperty var title: String = null,
@BeanProperty var msg: String = null,
@BooleanBeanProperty var minor: Boolean = false,
@BeanProperty var bonus: Int = 3,
@BeanProperty var tags: String = null,
@BeanProperty var poll: util.Map[Integer, String] = null,
@BeanProperty var editorBonus: util.Map[Integer, Integer] = null,
@BeanProperty var newPoll: Array[String] = new Array[String](3),
@BooleanBeanProperty var multiselect: Boolean = false,
@BeanProperty var fromHistory: Integer = null,
@BeanProperty var image: MultipartFile = null,
@BeanProperty var uploadedImage: String = null,
@BeanProperty var additionalUploadedImages: Array[String] = new Array[String](0),
@BeanProperty var additionalImage: Array[MultipartFile] = null) extends ImageTopicRequest {
def this() = this(title = null) // нужен конструктор по умолчанию для spring
}
81 changes: 81 additions & 0 deletions src/main/scala/ru/org/linux/topic/AddTopicRequestValidator.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* Copyright 1998-2024 Linux.org.ru
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ru.org.linux.topic

import com.google.common.base.Strings
import org.jdom2.Verifier
import org.springframework.stereotype.Component
import org.springframework.validation.Errors
import org.springframework.validation.Validator
import ru.org.linux.tag.TagName
import ru.org.linux.util.URLUtil

@Component
object AddTopicRequestValidator {
private val MaxTitleLength = 140
private val MaxUrlLength = 255
}

@Component
class AddTopicRequestValidator extends Validator {
override def supports(clazz: Class[?]): Boolean = classOf[AddTopicRequest] == clazz

override def validate(target: AnyRef, errors: Errors): Unit = {
val form = target.asInstanceOf[AddTopicRequest]

if (form.group == null) {
errors.rejectValue("group", null, "Группа не задана")
}

val title = form.title

if (title != null) {
if (title.trim.isEmpty) {
errors.rejectValue("title", null, "заголовок сообщения не может быть пустым")
}
if (title.length > AddTopicRequestValidator.MaxTitleLength) {
errors.rejectValue("title", null, "Слишком большой заголовок")
}
if (title.trim.startsWith("[")) {
errors.rejectValue("title", null, "Не добавляйте теги в заголовки, используйте предназначенное для тегов поле ввода")
}
}

if (form.msg != null) {
val error = Verifier.checkCharacterData(form.msg)
if (error != null) {
errors.rejectValue("msg", null, error)
}
}

if (!Strings.isNullOrEmpty(form.url)) {
if (form.url.length > AddTopicRequestValidator.MaxUrlLength) {
errors.rejectValue("url", null, "Слишком длинный URL")
}

if (!URLUtil.isUrl(form.url)) {
errors.rejectValue("url", null, "Некорректный URL")
}

if (form.linktext == null || form.linktext.isEmpty) {
errors.rejectValue("linktext", null, "URL указан без текста ссылки")
}
}

if (form.tags != null) {
TagName.parseAndValidateTags(form.tags, errors, TagName.MaxTagsPerTopic)
}
}
}
40 changes: 0 additions & 40 deletions src/main/scala/ru/org/linux/topic/EditTopicRequest.scala

This file was deleted.

Loading

0 comments on commit 36a539c

Please sign in to comment.