chibenwa commented on code in PR #2896: URL: https://github.com/apache/james-project/pull/2896#discussion_r2661027425
########## server/protocols/jmap-rfc-8621-integration-tests/jmap-rfc-8621-integration-tests-common/src/main/scala/org/apache/james/jmap/rfc8621/contract/BlobCopyContract.scala: ########## @@ -0,0 +1,265 @@ +/**************************************************************** + * Licensed to the Apache Software Foundation (ASF) under one * + * or more contributor license agreements. See the NOTICE file * + * distributed with this work for additional information * + * regarding copyright ownership. The ASF licenses this file * + * to you 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 org.apache.james.jmap.rfc8621.contract + +import java.io.ByteArrayInputStream +import java.nio.charset.StandardCharsets + +import io.netty.handler.codec.http.HttpHeaderNames.ACCEPT +import io.restassured.RestAssured.{`given`, requestSpecification} +import io.restassured.http.ContentType +import net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson +import org.apache.http.HttpStatus.{SC_CREATED, SC_OK} +import org.apache.james.GuiceJamesServer +import org.apache.james.jmap.core.AccountId +import org.apache.james.jmap.http.UserCredential +import org.apache.james.jmap.rfc8621.contract.BlobCopyContract.BYTES +import org.apache.james.jmap.rfc8621.contract.Fixture.{ACCEPT_RFC8621_VERSION_HEADER, ALICE, ALICE_PASSWORD, BOB, BOB_PASSWORD, DOMAIN, _2_DOT_DOMAIN, authScheme, baseRequestSpecBuilder, ACCOUNT_ID => BOB_ACCOUNT_ID} +import org.apache.james.junit.categories.BasicFeature +import org.apache.james.utils.DataProbeImpl +import org.assertj.core.api.Assertions.assertThat +import org.junit.experimental.categories.Category +import org.junit.jupiter.api.{BeforeEach, Test} +import play.api.libs.json.{JsObject, JsString, Json} + +object BlobCopyContract { + val BYTES: Array[Byte] = "123456789\r\n".repeat(1024 * 64).getBytes(StandardCharsets.UTF_8) +} + +trait BlobCopyContract { + @BeforeEach + def setUp(server: GuiceJamesServer): Unit = { + server.getProbe(classOf[DataProbeImpl]) + .fluent + .addDomain(DOMAIN.asString) + .addDomain(_2_DOT_DOMAIN.asString()) + .addUser(BOB.asString, BOB_PASSWORD) + .addUser(ALICE.asString(), ALICE_PASSWORD) + + requestSpecification = baseRequestSpecBuilder(server) + .setAuth(authScheme(UserCredential(BOB, BOB_PASSWORD))) + .build + } + + @Category(Array(classOf[BasicFeature])) + @Test + def shouldCopyBlobBetweenAccountsWhenDelegated(server: GuiceJamesServer): Unit = { + // Alice delegates Bob to access her account + server.getProbe(classOf[DataProbeImpl]).addAuthorizedUser(ALICE, BOB) + + // Bob uploads a blob to his account + val uploadResponse: String = `given` + .basePath("") + .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER) + .contentType(ContentType.BINARY) + .body(BYTES) + .when + .post(s"/upload/$BOB_ACCOUNT_ID") + .`then` + .statusCode(SC_CREATED) + .extract + .body + .asString + + val bobBlobId: String = Json.parse(uploadResponse).\("blobId").get.asInstanceOf[JsString].value + + val aliceAccountId: String = AccountId.from(ALICE).toOption.get.id.value + + // Bob copies the blob from his account to Alice's account + val request: String = + s"""{ + | "using": [ "urn:ietf:params:jmap:core" ], + | "methodCalls": [[ + | "Blob/copy", + | { + | "fromAccountId": "$BOB_ACCOUNT_ID", + | "accountId": "$aliceAccountId", + | "blobIds": [ "$bobBlobId" ] + | }, + | "c1"]] + |}""".stripMargin + + val response: String = `given` + .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER) + .body(request) + .when + .post + .`then` + .statusCode(SC_OK) + .contentType(ContentType.JSON) + .extract + .body + .asString + + val copied: JsObject = (Json.parse(response) \ "methodResponses")(0)(1).\("copied").get.as[JsObject] + val copiedBlobId: String = copied.value(bobBlobId).as[JsString].value Review Comment: I think using restassured JSON extraction would be less boiler plate, easier and more idiomatic of our code base. ########## server/protocols/jmap-rfc-8621-integration-tests/jmap-rfc-8621-integration-tests-common/src/main/scala/org/apache/james/jmap/rfc8621/contract/BlobCopyContract.scala: ########## @@ -0,0 +1,265 @@ +/**************************************************************** + * Licensed to the Apache Software Foundation (ASF) under one * + * or more contributor license agreements. See the NOTICE file * + * distributed with this work for additional information * + * regarding copyright ownership. The ASF licenses this file * + * to you 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 org.apache.james.jmap.rfc8621.contract + +import java.io.ByteArrayInputStream +import java.nio.charset.StandardCharsets + +import io.netty.handler.codec.http.HttpHeaderNames.ACCEPT +import io.restassured.RestAssured.{`given`, requestSpecification} +import io.restassured.http.ContentType +import net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson +import org.apache.http.HttpStatus.{SC_CREATED, SC_OK} +import org.apache.james.GuiceJamesServer +import org.apache.james.jmap.core.AccountId +import org.apache.james.jmap.http.UserCredential +import org.apache.james.jmap.rfc8621.contract.BlobCopyContract.BYTES +import org.apache.james.jmap.rfc8621.contract.Fixture.{ACCEPT_RFC8621_VERSION_HEADER, ALICE, ALICE_PASSWORD, BOB, BOB_PASSWORD, DOMAIN, _2_DOT_DOMAIN, authScheme, baseRequestSpecBuilder, ACCOUNT_ID => BOB_ACCOUNT_ID} +import org.apache.james.junit.categories.BasicFeature +import org.apache.james.utils.DataProbeImpl +import org.assertj.core.api.Assertions.assertThat +import org.junit.experimental.categories.Category +import org.junit.jupiter.api.{BeforeEach, Test} +import play.api.libs.json.{JsObject, JsString, Json} + +object BlobCopyContract { + val BYTES: Array[Byte] = "123456789\r\n".repeat(1024 * 64).getBytes(StandardCharsets.UTF_8) +} + +trait BlobCopyContract { Review Comment: We get a few more tests to cover Alice delegates to Bob Alice uploads a blob to her account Alice copies it into bob account Alice delegates to bob Cedric delegates to bob Cedric uploads a blob Bob copies it from Cedric account onto Bob account Can we be adding those missing tests? ########## server/protocols/jmap-rfc-8621-integration-tests/jmap-rfc-8621-integration-tests-common/src/main/scala/org/apache/james/jmap/rfc8621/contract/BlobCopyContract.scala: ########## @@ -0,0 +1,265 @@ +/**************************************************************** + * Licensed to the Apache Software Foundation (ASF) under one * + * or more contributor license agreements. See the NOTICE file * + * distributed with this work for additional information * + * regarding copyright ownership. The ASF licenses this file * + * to you 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 org.apache.james.jmap.rfc8621.contract + +import java.io.ByteArrayInputStream +import java.nio.charset.StandardCharsets + +import io.netty.handler.codec.http.HttpHeaderNames.ACCEPT +import io.restassured.RestAssured.{`given`, requestSpecification} +import io.restassured.http.ContentType +import net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson +import org.apache.http.HttpStatus.{SC_CREATED, SC_OK} +import org.apache.james.GuiceJamesServer +import org.apache.james.jmap.core.AccountId +import org.apache.james.jmap.http.UserCredential +import org.apache.james.jmap.rfc8621.contract.BlobCopyContract.BYTES +import org.apache.james.jmap.rfc8621.contract.Fixture.{ACCEPT_RFC8621_VERSION_HEADER, ALICE, ALICE_PASSWORD, BOB, BOB_PASSWORD, DOMAIN, _2_DOT_DOMAIN, authScheme, baseRequestSpecBuilder, ACCOUNT_ID => BOB_ACCOUNT_ID} +import org.apache.james.junit.categories.BasicFeature +import org.apache.james.utils.DataProbeImpl +import org.assertj.core.api.Assertions.assertThat +import org.junit.experimental.categories.Category +import org.junit.jupiter.api.{BeforeEach, Test} +import play.api.libs.json.{JsObject, JsString, Json} + +object BlobCopyContract { + val BYTES: Array[Byte] = "123456789\r\n".repeat(1024 * 64).getBytes(StandardCharsets.UTF_8) +} + +trait BlobCopyContract { Review Comment: Please have 1 test regarding quota exceeded on the target account and ensure that we delete older blobs in order to make room for the new one ########## server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/method/BlobCopyMethod.scala: ########## @@ -0,0 +1,151 @@ +/**************************************************************** + * Licensed to the Apache Software Foundation (ASF) under one * + * or more contributor license agreements. See the NOTICE file * + * distributed with this work for additional information * + * regarding copyright ownership. The ASF licenses this file * + * to you 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 org.apache.james.jmap.method + +import eu.timepit.refined.auto._ +import jakarta.inject.Inject +import org.apache.james.core.Username +import org.apache.james.jmap.api.model.UploadId +import org.apache.james.jmap.api.upload.UploadService +import org.apache.james.jmap.core.CapabilityIdentifier.{CapabilityIdentifier, JMAP_CORE} +import org.apache.james.jmap.core.Invocation.{Arguments, MethodName} +import org.apache.james.jmap.core.SetError.SetErrorDescription +import org.apache.james.jmap.core.{BlobCopyRequest, BlobCopyResponse, ErrorCode, Invocation, JmapRfc8621Configuration, SessionTranslator, SetError} +import org.apache.james.jmap.json.BlobCopySerializer +import org.apache.james.jmap.mail.BlobId +import org.apache.james.jmap.mail.MDNParse.UnparsedBlobId +import org.apache.james.jmap.routes.{Blob, BlobNotFoundException, BlobResolvers, SessionSupplier} +import org.apache.james.mailbox.{MailboxSession, SessionProvider} +import org.apache.james.metrics.api.MetricFactory +import org.apache.james.util.ReactorUtils +import org.reactivestreams.Publisher +import org.slf4j.{Logger, LoggerFactory} +import reactor.core.scala.publisher.{SFlux, SMono} + +import scala.jdk.OptionConverters._ + +sealed trait CopyResult { + def sourceBlobId: BlobId +} +case class Copied(sourceBlobId: BlobId, copied: BlobId) extends CopyResult +case class NotCopied(sourceBlobId: BlobId, error: SetError) extends CopyResult +case class CopyResults(results: Seq[CopyResult]) { + def copied: Option[Map[BlobId, BlobId]] = + Option(results.collect { case Copied(source, copied) => source -> copied }.toMap).filter(_.nonEmpty) + + def notCopied: Option[Map[BlobId, SetError]] = + Option(results.collect { case NotCopied(source, error) => source -> error }.toMap).filter(_.nonEmpty) +} + +case class FromAccountNotFoundException() extends RuntimeException + +class BlobCopyMethod @Inject()(val metricFactory: MetricFactory, + val sessionSupplier: SessionSupplier, + val sessionTranslator: SessionTranslator, + val sessionProvider: SessionProvider, + val blobResolvers: BlobResolvers, + val uploadService: UploadService, + val serializer: BlobCopySerializer, + val configuration: JmapRfc8621Configuration) extends MethodRequiringAccountId[BlobCopyRequest] { + private val LOGGER: Logger = LoggerFactory.getLogger(classOf[BlobCopyMethod]) + + override val methodName: MethodName = MethodName("Blob/copy") + override val requiredCapabilities: Set[CapabilityIdentifier] = Set(JMAP_CORE) + + override def doProcess(capabilities: Set[CapabilityIdentifier], invocation: InvocationWithContext, mailboxSession: MailboxSession, request: BlobCopyRequest): Publisher[InvocationWithContext] = + resolveSourceSession(request, mailboxSession) + .flatMap(sourceSession => copyBlobs(request, sourceSession, targetSession = mailboxSession)) + .map(response => asInvocation(response, invocation)) + .onErrorResume { + case _: FromAccountNotFoundException => + SMono.just(asErrorInvocation(ErrorCode.FromAccountNotFound, invocation)) + case e => + LOGGER.error("Failed to copy blob", e) + SMono.just(asErrorInvocation(ErrorCode.ServerFail, e.getMessage, invocation)) + } + + private def resolveSourceSession(request: BlobCopyRequest, mailboxSession: MailboxSession): SMono[MailboxSession] = + if (request.fromAccountId.equals(request.accountId)) { + SMono.just(mailboxSession) + } else { + mailboxSession.getLoggedInUser.toScala + .filter(loggedInUser => sessionTranslator.hasAccountId(request.fromAccountId)(loggedInUser)) + .map(createSourceSession) + .getOrElse(SMono.error(FromAccountNotFoundException())) + } + + private def createSourceSession(loggedInUser: Username): SMono[MailboxSession] = + SMono.fromCallable(() => sessionProvider.authenticate(loggedInUser).withoutDelegation()) + .subscribeOn(ReactorUtils.BLOCKING_CALL_WRAPPER) + + private def asInvocation(response: BlobCopyResponse, invocation: InvocationWithContext): InvocationWithContext = + InvocationWithContext( + Invocation( + methodName = methodName, + arguments = Arguments(serializer.serializeBlobCopyResponse(response)), + methodCallId = invocation.invocation.methodCallId), + invocation.processingContext) + + private def asErrorInvocation(errorCode: ErrorCode, invocation: InvocationWithContext): InvocationWithContext = + InvocationWithContext( + Invocation.error(errorCode, invocation.invocation.methodCallId), + invocation.processingContext) + + private def asErrorInvocation(errorCode: ErrorCode, description: String = "", invocation: InvocationWithContext): InvocationWithContext = + InvocationWithContext( + Invocation.error(errorCode, description, invocation.invocation.methodCallId), + invocation.processingContext) + + override def getRequest(mailboxSession: MailboxSession, invocation: Invocation): Either[Exception, BlobCopyRequest] = + serializer.deserializeBlobCopyRequest(invocation.arguments.value).asEitherRequest + .flatMap(request => request.validate(configuration).map(_ => request)) + + private def copyBlobs(request: BlobCopyRequest, sourceSession: MailboxSession, targetSession: MailboxSession): SMono[BlobCopyResponse] = + SFlux.fromIterable(request.blobIds.value) + .flatMap(blobId => copyBlob(blobId, sourceSession, targetSession), ReactorUtils.DEFAULT_CONCURRENCY) + .collectSeq() + .map(CopyResults) + .map(results => BlobCopyResponse(request.fromAccountId, request.accountId, results.copied, results.notCopied)) + + private def copyBlob(unparsedBlobId: UnparsedBlobId, sourceSession: MailboxSession, targetSession: MailboxSession): SMono[CopyResult] = + SMono.fromTry(BlobId.of(unparsedBlobId)) + .flatMap { sourceBlobId => + blobResolvers.resolve(sourceBlobId, sourceSession) + .flatMap(blob => uploadBlob(sourceBlobId, blob, targetSession)) + .onErrorResume(e => SMono.just(NotCopied(sourceBlobId, asSetError(sourceBlobId, sourceSession, targetSession, e)))) + } + + private def uploadBlob(sourceBlobId: BlobId, blob: Blob, targetSession: MailboxSession): SMono[CopyResult] = + SMono.fromPublisher(uploadService.upload(blob.content, blob.contentType, targetSession.getUser)) + .map(upload => Copied(sourceBlobId, asBlobId(upload.uploadId))) + + private def asBlobId(uploadId: UploadId): BlobId = + BlobId.of(s"uploads-${uploadId.asString()}").get Review Comment: This line is fishy and seems copy and pasted from somewhere else. I'd like it is shared so that wedo not suffer from "coupling" pitfall ########## server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/method/BlobCopyMethod.scala: ########## @@ -0,0 +1,151 @@ +/**************************************************************** + * Licensed to the Apache Software Foundation (ASF) under one * + * or more contributor license agreements. See the NOTICE file * + * distributed with this work for additional information * + * regarding copyright ownership. The ASF licenses this file * + * to you 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 org.apache.james.jmap.method + +import eu.timepit.refined.auto._ +import jakarta.inject.Inject +import org.apache.james.core.Username +import org.apache.james.jmap.api.model.UploadId +import org.apache.james.jmap.api.upload.UploadService +import org.apache.james.jmap.core.CapabilityIdentifier.{CapabilityIdentifier, JMAP_CORE} +import org.apache.james.jmap.core.Invocation.{Arguments, MethodName} +import org.apache.james.jmap.core.SetError.SetErrorDescription +import org.apache.james.jmap.core.{BlobCopyRequest, BlobCopyResponse, ErrorCode, Invocation, JmapRfc8621Configuration, SessionTranslator, SetError} +import org.apache.james.jmap.json.BlobCopySerializer +import org.apache.james.jmap.mail.BlobId +import org.apache.james.jmap.mail.MDNParse.UnparsedBlobId +import org.apache.james.jmap.routes.{Blob, BlobNotFoundException, BlobResolvers, SessionSupplier} +import org.apache.james.mailbox.{MailboxSession, SessionProvider} +import org.apache.james.metrics.api.MetricFactory +import org.apache.james.util.ReactorUtils +import org.reactivestreams.Publisher +import org.slf4j.{Logger, LoggerFactory} +import reactor.core.scala.publisher.{SFlux, SMono} + +import scala.jdk.OptionConverters._ + +sealed trait CopyResult { + def sourceBlobId: BlobId +} +case class Copied(sourceBlobId: BlobId, copied: BlobId) extends CopyResult +case class NotCopied(sourceBlobId: BlobId, error: SetError) extends CopyResult +case class CopyResults(results: Seq[CopyResult]) { + def copied: Option[Map[BlobId, BlobId]] = + Option(results.collect { case Copied(source, copied) => source -> copied }.toMap).filter(_.nonEmpty) + + def notCopied: Option[Map[BlobId, SetError]] = + Option(results.collect { case NotCopied(source, error) => source -> error }.toMap).filter(_.nonEmpty) +} + +case class FromAccountNotFoundException() extends RuntimeException + +class BlobCopyMethod @Inject()(val metricFactory: MetricFactory, + val sessionSupplier: SessionSupplier, + val sessionTranslator: SessionTranslator, + val sessionProvider: SessionProvider, + val blobResolvers: BlobResolvers, + val uploadService: UploadService, + val serializer: BlobCopySerializer, + val configuration: JmapRfc8621Configuration) extends MethodRequiringAccountId[BlobCopyRequest] { + private val LOGGER: Logger = LoggerFactory.getLogger(classOf[BlobCopyMethod]) + + override val methodName: MethodName = MethodName("Blob/copy") + override val requiredCapabilities: Set[CapabilityIdentifier] = Set(JMAP_CORE) + + override def doProcess(capabilities: Set[CapabilityIdentifier], invocation: InvocationWithContext, mailboxSession: MailboxSession, request: BlobCopyRequest): Publisher[InvocationWithContext] = + resolveSourceSession(request, mailboxSession) + .flatMap(sourceSession => copyBlobs(request, sourceSession, targetSession = mailboxSession)) + .map(response => asInvocation(response, invocation)) + .onErrorResume { + case _: FromAccountNotFoundException => + SMono.just(asErrorInvocation(ErrorCode.FromAccountNotFound, invocation)) + case e => + LOGGER.error("Failed to copy blob", e) + SMono.just(asErrorInvocation(ErrorCode.ServerFail, e.getMessage, invocation)) + } + + private def resolveSourceSession(request: BlobCopyRequest, mailboxSession: MailboxSession): SMono[MailboxSession] = + if (request.fromAccountId.equals(request.accountId)) { + SMono.just(mailboxSession) + } else { + mailboxSession.getLoggedInUser.toScala + .filter(loggedInUser => sessionTranslator.hasAccountId(request.fromAccountId)(loggedInUser)) + .map(createSourceSession) + .getOrElse(SMono.error(FromAccountNotFoundException())) + } + + private def createSourceSession(loggedInUser: Username): SMono[MailboxSession] = + SMono.fromCallable(() => sessionProvider.authenticate(loggedInUser).withoutDelegation()) + .subscribeOn(ReactorUtils.BLOCKING_CALL_WRAPPER) + + private def asInvocation(response: BlobCopyResponse, invocation: InvocationWithContext): InvocationWithContext = + InvocationWithContext( + Invocation( + methodName = methodName, + arguments = Arguments(serializer.serializeBlobCopyResponse(response)), + methodCallId = invocation.invocation.methodCallId), + invocation.processingContext) + + private def asErrorInvocation(errorCode: ErrorCode, invocation: InvocationWithContext): InvocationWithContext = + InvocationWithContext( + Invocation.error(errorCode, invocation.invocation.methodCallId), + invocation.processingContext) + + private def asErrorInvocation(errorCode: ErrorCode, description: String = "", invocation: InvocationWithContext): InvocationWithContext = + InvocationWithContext( + Invocation.error(errorCode, description, invocation.invocation.methodCallId), + invocation.processingContext) + + override def getRequest(mailboxSession: MailboxSession, invocation: Invocation): Either[Exception, BlobCopyRequest] = + serializer.deserializeBlobCopyRequest(invocation.arguments.value).asEitherRequest + .flatMap(request => request.validate(configuration).map(_ => request)) + + private def copyBlobs(request: BlobCopyRequest, sourceSession: MailboxSession, targetSession: MailboxSession): SMono[BlobCopyResponse] = + SFlux.fromIterable(request.blobIds.value) + .flatMap(blobId => copyBlob(blobId, sourceSession, targetSession), ReactorUtils.DEFAULT_CONCURRENCY) + .collectSeq() + .map(CopyResults) + .map(results => BlobCopyResponse(request.fromAccountId, request.accountId, results.copied, results.notCopied)) + + private def copyBlob(unparsedBlobId: UnparsedBlobId, sourceSession: MailboxSession, targetSession: MailboxSession): SMono[CopyResult] = + SMono.fromTry(BlobId.of(unparsedBlobId)) + .flatMap { sourceBlobId => + blobResolvers.resolve(sourceBlobId, sourceSession) + .flatMap(blob => uploadBlob(sourceBlobId, blob, targetSession)) + .onErrorResume(e => SMono.just(NotCopied(sourceBlobId, asSetError(sourceBlobId, sourceSession, targetSession, e)))) + } + + private def uploadBlob(sourceBlobId: BlobId, blob: Blob, targetSession: MailboxSession): SMono[CopyResult] = + SMono.fromPublisher(uploadService.upload(blob.content, blob.contentType, targetSession.getUser)) + .map(upload => Copied(sourceBlobId, asBlobId(upload.uploadId))) Review Comment: ```suggestion .map(Copied(sourceBlobId, asBlobId(_.uploadId))) ``` ? ########## server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/core/BlobCopy.scala: ########## @@ -0,0 +1,40 @@ +/**************************************************************** + * Licensed to the Apache Software Foundation (ASF) under one * + * or more contributor license agreements. See the NOTICE file * + * distributed with this work for additional information * + * regarding copyright ownership. The ASF licenses this file * + * to you 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 org.apache.james.jmap.core + +import org.apache.james.jmap.mail.{BlobId, BlobIds, RequestTooLargeException} +import org.apache.james.jmap.method.{ValidableRequest, WithAccountId} + +case class BlobCopyRequest(fromAccountId: AccountId, + accountId: AccountId, + blobIds: BlobIds) extends WithAccountId with ValidableRequest { + override def validate(configuration: JmapRfc8621Configuration): Either[Exception, BlobCopyRequest] = + if (blobIds.value.size > configuration.maxObjectsInSet.value.value) { + Left(RequestTooLargeException(s"Too many items in a Blob/copy request. " + + s"Got ${blobIds.value.size} items instead of maximum ${configuration.maxObjectsInSet.value.value}.")) Review Comment: ```suggestion Left(RequestTooLargeException(s"""Too many items in a Blob/copy request. Got ${blobIds.value.size} items instead of maximum ${configuration.maxObjectsInSet.value.value}.""")) ``` (nitpick) -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
