diff --git a/app/Global.scala b/app/Global.scala index 192284b392..b9952cd472 100755 --- a/app/Global.scala +++ b/app/Global.scala @@ -5,7 +5,7 @@ import com.scalableminds.util.accesscontext.GlobalAccessContext import com.typesafe.config.Config import com.typesafe.scalalogging.LazyLogging import controllers.InitialDataService -import models.annotation.AnnotationSQLDAO +import models.annotation.AnnotationDAO import net.liftweb.common.{Failure, Full} import oxalis.cleanup.CleanUpService import oxalis.security.WebknossosSilhouette @@ -45,7 +45,7 @@ object Global extends GlobalSettings with LazyLogging{ } CleanUpService.register("deletion of old annotations in initializing state", 1 day) { - AnnotationSQLDAO.deleteOldInitializingAnnotations + AnnotationDAO.deleteOldInitializingAnnotations } super.onStart(app) diff --git a/app/controllers/AnnotationController.scala b/app/controllers/AnnotationController.scala index c3af70c967..7b2b87cec6 100755 --- a/app/controllers/AnnotationController.scala +++ b/app/controllers/AnnotationController.scala @@ -6,10 +6,10 @@ import com.scalableminds.util.accesscontext.{DBAccessContext, GlobalAccessContex import com.scalableminds.util.tools.{Fox, FoxImplicits} import com.scalableminds.webknossos.datastore.tracings.TracingType import models.annotation._ -import models.binary.{DataSetSQL, DataSetSQLDAO} -import models.task.TaskSQLDAO +import models.binary.{DataSet, DataSetDAO} +import models.task.TaskDAO import models.user.time._ -import models.user.{UserSQL, UserSQLDAO} +import models.user.{User, UserDAO} import oxalis.security.WebknossosSilhouette.{SecuredAction, SecuredRequest, UserAwareAction} import play.api.i18n.{Messages, MessagesApi} import play.api.libs.json.{JsArray, _} @@ -59,7 +59,7 @@ class AnnotationController @Inject()(val messagesApi: MessagesApi) mergedAnnotation <- AnnotationMerger.mergeTwoByIds(identifierA, identifierB, true) restrictions = AnnotationRestrictions.defaultAnnotationRestrictions(mergedAnnotation) _ <- restrictions.allowAccess(request.identity) ?~> Messages("notAllowed") ~> BAD_REQUEST - _ <- AnnotationSQLDAO.insertOne(mergedAnnotation) + _ <- AnnotationDAO.insertOne(mergedAnnotation) js <- mergedAnnotation.publicWrites(Some(request.identity), Some(restrictions)) } yield { JsonOk(js, Messages("annotation.merge.success")) @@ -72,7 +72,7 @@ class AnnotationController @Inject()(val messagesApi: MessagesApi) annotation <- provideAnnotation(typ, id)(securedRequestToUserAwareRequest) restrictions <- restrictionsFor(typ, id)(securedRequestToUserAwareRequest) _ <- restrictions.allowAccess(request.identity) ?~> Messages("notAllowed") ~> BAD_REQUEST - loggedTimeAsMap <- TimeSpanService.loggedTimeOfAnnotation(annotation._id, TimeSpanSQL.groupByMonth) + loggedTimeAsMap <- TimeSpanService.loggedTimeOfAnnotation(annotation._id, TimeSpan.groupByMonth) } yield { Ok(Json.arr( loggedTimeAsMap.map { @@ -92,7 +92,7 @@ class AnnotationController @Inject()(val messagesApi: MessagesApi) dataSet <- annotation.dataSet dataStoreHandler <- dataSet.dataStoreHandler newTracingReference <- dataStoreHandler.duplicateSkeletonTracing(annotation.tracing, Some(version.toString)) - _ <- AnnotationSQLDAO.updateTracingReference(annotation._id, newTracingReference) + _ <- AnnotationDAO.updateTracingReference(annotation._id, newTracingReference) } yield { logger.info(s"REVERTED [$typ - $id, $version]") JsonOk("annotation.reverted") @@ -112,7 +112,7 @@ class AnnotationController @Inject()(val messagesApi: MessagesApi) } def reopen(typ: String, id: String) = SecuredAction.async { implicit request => - def isReopenAllowed(user: UserSQL, annotation: AnnotationSQL) = for { + def isReopenAllowed(user: User, annotation: Annotation) = for { isAdminOrTeamManager <- user.isTeamManagerOrAdminOf(annotation._team) } yield (annotation._user == user._id || isAdminOrTeamManager) @@ -135,7 +135,7 @@ class AnnotationController @Inject()(val messagesApi: MessagesApi) def createExplorational(dataSetName: String) = SecuredAction.async(validateJson[CreateExplorationalParameters]) { implicit request => for { - dataSetSQL <- DataSetSQLDAO.findOneByName(dataSetName) ?~> Messages("dataSet.notFound", dataSetName) + dataSetSQL <- DataSetDAO.findOneByName(dataSetName) ?~> Messages("dataSet.notFound", dataSetName) tracingType <- TracingType.values.find(_.toString == request.body.typ).toFox annotation <- AnnotationService.createExplorationalFor(request.identity, dataSetSQL._id, tracingType, request.body.withFallback.getOrElse(true)) ?~> Messages("annotation.create.failed") json <- annotation.publicWrites(Some(request.identity)) @@ -144,7 +144,7 @@ class AnnotationController @Inject()(val messagesApi: MessagesApi) } } - private def finishAnnotation(typ: String, id: String, user: UserSQL)(implicit request: SecuredRequest[_]): Fox[(AnnotationSQL, String)] = { + private def finishAnnotation(typ: String, id: String, user: User)(implicit request: SecuredRequest[_]): Fox[(Annotation, String)] = { for { annotation <- provideAnnotation(typ, id)(securedRequestToUserAwareRequest) restrictions <- restrictionsFor(typ, id)(securedRequestToUserAwareRequest) @@ -194,7 +194,7 @@ class AnnotationController @Inject()(val messagesApi: MessagesApi) def annotationsForTask(taskId: String) = SecuredAction.async { implicit request => for { taskIdValidated <- ObjectId.parse(taskId) - task <- TaskSQLDAO.findOne(taskIdValidated) ?~> Messages("task.notFound") + task <- TaskDAO.findOne(taskIdValidated) ?~> Messages("task.notFound") project <- task.project _ <- ensureTeamAdministration(request.identity, project._team) annotations <- task.annotations @@ -206,7 +206,7 @@ class AnnotationController @Inject()(val messagesApi: MessagesApi) def cancel(typ: String, id: String) = SecuredAction.async { implicit request => - def tryToCancel(annotation: AnnotationSQL) = { + def tryToCancel(annotation: Annotation) = { annotation match { case t if t.typ == AnnotationTypeSQL.Task => annotation.muta.cancel.map { _ => @@ -231,7 +231,7 @@ class AnnotationController @Inject()(val messagesApi: MessagesApi) _ <- restrictions.allowFinish(request.identity) ?~> Messages("notAllowed") newUserId <- (request.body \ "userId").asOpt[String].toFox newUserIdValidated <- ObjectId.parse(newUserId) - newUser <- UserSQLDAO.findOne(newUserIdValidated) ?~> Messages("user.notFound") + newUser <- UserDAO.findOne(newUserIdValidated) ?~> Messages("user.notFound") _ <- annotation.muta.transferToUser(newUser) updated <- provideAnnotation(typ, id)(securedRequestToUserAwareRequest) json <- updated.publicWrites(Some(request.identity), Some(restrictions)) @@ -251,9 +251,9 @@ class AnnotationController @Inject()(val messagesApi: MessagesApi) } } - private def duplicateAnnotation(annotation: AnnotationSQL, user: UserSQL)(implicit ctx: DBAccessContext): Fox[AnnotationSQL] = { + private def duplicateAnnotation(annotation: Annotation, user: User)(implicit ctx: DBAccessContext): Fox[Annotation] = { for { - dataSet: DataSetSQL <- annotation.dataSet + dataSet: DataSet <- annotation.dataSet oldTracingReference = annotation.tracing _ <- bool2Fox(dataSet.isUsable) ?~> "DataSet is not imported." dataStoreHandler <- dataSet.dataStoreHandler diff --git a/app/controllers/AnnotationIOController.scala b/app/controllers/AnnotationIOController.scala index 6c292002c0..3aaefc78fa 100755 --- a/app/controllers/AnnotationIOController.scala +++ b/app/controllers/AnnotationIOController.scala @@ -10,8 +10,8 @@ import com.typesafe.scalalogging.LazyLogging import models.annotation.AnnotationState._ import models.annotation.nml.{NmlService, NmlWriter} import models.annotation._ -import models.binary.{DataSetSQL, DataSetSQLDAO} -import models.project.ProjectSQLDAO +import models.binary.{DataSet, DataSetDAO} +import models.project.ProjectDAO import models.task._ import models.user._ import oxalis.security.WebknossosSilhouette.{SecuredAction, UserAwareRequest} @@ -56,7 +56,7 @@ class AnnotationIOController @Inject()(val messagesApi: MessagesApi) } } - def storeMergedSkeletonTracing(tracings: List[SkeletonTracing], dataSet: DataSetSQL): Fox[TracingReference] = { + def storeMergedSkeletonTracing(tracings: List[SkeletonTracing], dataSet: DataSet): Fox[TracingReference] = { for { dataStoreHandler <- dataSet.dataStoreHandler newTracingReference <- dataStoreHandler.mergeSkeletonTracingsByContents(SkeletonTracings(tracings), persistTracing=true) @@ -80,7 +80,7 @@ class AnnotationIOController @Inject()(val messagesApi: MessagesApi) val description = descriptionForNMLs(parseSuccess.map(_.description)) if (volumeTracings.nonEmpty) { for { - dataSet <- DataSetSQLDAO.findOneByName(volumeTracings.head._1.dataSetName).toFox ?~> Messages("dataSet.notFound", volumeTracings.head._1.dataSetName) + dataSet <- DataSetDAO.findOneByName(volumeTracings.head._1.dataSetName).toFox ?~> Messages("dataSet.notFound", volumeTracings.head._1.dataSetName) dataStoreHandler <- dataSet.dataStoreHandler tracingReference <- dataStoreHandler.saveVolumeTracing(volumeTracings.head._1, parsedFiles.otherFiles.get(volumeTracings.head._2).map(_.file)) annotation <- AnnotationService.createFrom( @@ -91,7 +91,7 @@ class AnnotationIOController @Inject()(val messagesApi: MessagesApi) ) } else if (skeletonTracings.nonEmpty) { for { - dataSet <- DataSetSQLDAO.findOneByName(skeletonTracings.head.dataSetName).toFox ?~> Messages("dataSet.notFound", skeletonTracings.head.dataSetName) + dataSet <- DataSetDAO.findOneByName(skeletonTracings.head.dataSetName).toFox ?~> Messages("dataSet.notFound", skeletonTracings.head.dataSetName) mergedTracingReference <- storeMergedSkeletonTracing(skeletonTracings, dataSet) annotation <- AnnotationService.createFrom( request.identity, dataSet, mergedTracingReference, AnnotationTypeSQL.Explorational, name, description) @@ -121,9 +121,9 @@ class AnnotationIOController @Inject()(val messagesApi: MessagesApi) } yield result } - def downloadExplorational(annotationId: String, typ: String, user: UserSQL)(implicit request: UserAwareRequest[_]) = { + def downloadExplorational(annotationId: String, typ: String, user: User)(implicit request: UserAwareRequest[_]) = { - def skeletonToDownloadStream(dataSet: DataSetSQL, annotation: AnnotationSQL, name: String) = { + def skeletonToDownloadStream(dataSet: DataSet, annotation: Annotation, name: String) = { for { dataStoreHandler <- dataSet.dataStoreHandler tracing <- dataStoreHandler.getSkeletonTracing(annotation.tracing) @@ -132,7 +132,7 @@ class AnnotationIOController @Inject()(val messagesApi: MessagesApi) } } - def volumeToDownloadStream(dataSet: DataSetSQL, annotation: AnnotationSQL, name: String) = { + def volumeToDownloadStream(dataSet: DataSet, annotation: Annotation, name: String) = { for { dataStoreHandler <- dataSet.dataStoreHandler (tracing, data) <- dataStoreHandler.getVolumeTracing(annotation.tracing) @@ -147,7 +147,7 @@ class AnnotationIOController @Inject()(val messagesApi: MessagesApi) } } - def tracingToDownloadStream(dataSet: DataSetSQL, annotation: AnnotationSQL, name: String) = { + def tracingToDownloadStream(dataSet: DataSet, annotation: Annotation, name: String) = { annotation.tracing.typ match { case TracingType.skeleton => skeletonToDownloadStream(dataSet, annotation, name) @@ -172,36 +172,36 @@ class AnnotationIOController @Inject()(val messagesApi: MessagesApi) } } - def downloadProject(projectId: String, user: UserSQL)(implicit ctx: DBAccessContext) = { + def downloadProject(projectId: String, user: User)(implicit ctx: DBAccessContext) = { for { projectIdValidated <- ObjectId.parse(projectId) - project <- ProjectSQLDAO.findOne(projectIdValidated) ?~> Messages("project.notFound", projectId) + project <- ProjectDAO.findOne(projectIdValidated) ?~> Messages("project.notFound", projectId) _ <- Fox.assertTrue(user.isTeamManagerOrAdminOf(project._team)) - annotations <- AnnotationSQLDAO.findAllFinishedForProject(projectIdValidated) + annotations <- AnnotationDAO.findAllFinishedForProject(projectIdValidated) zip <- AnnotationService.zipAnnotations(annotations, project.name + "_nmls.zip") } yield { Ok.sendFile(zip.file) } } - def downloadTask(taskId: String, user: UserSQL)(implicit ctx: DBAccessContext) = { - def createTaskZip(task: TaskSQL): Fox[TemporaryFile] = task.annotations.flatMap { annotations => + def downloadTask(taskId: String, user: User)(implicit ctx: DBAccessContext) = { + def createTaskZip(task: Task): Fox[TemporaryFile] = task.annotations.flatMap { annotations => val finished = annotations.filter(_.state == Finished) AnnotationService.zipAnnotations(finished, task._id.toString + "_nmls.zip") } for { - task <- TaskSQLDAO.findOne(ObjectId(taskId)).toFox ?~> Messages("task.notFound") + task <- TaskDAO.findOne(ObjectId(taskId)).toFox ?~> Messages("task.notFound") project <- task.project ?~> Messages("project.notFound") _ <- ensureTeamAdministration(user, project._team) ?~> Messages("notAllowed") zip <- createTaskZip(task) } yield Ok.sendFile(zip.file) } - def downloadTaskType(taskTypeId: String, user: UserSQL)(implicit ctx: DBAccessContext) = { - def createTaskTypeZip(taskType: TaskTypeSQL) = + def downloadTaskType(taskTypeId: String, user: User)(implicit ctx: DBAccessContext) = { + def createTaskTypeZip(taskType: TaskType) = for { - tasks <- TaskSQLDAO.findAllByTaskType(taskType._id) + tasks <- TaskDAO.findAllByTaskType(taskType._id) annotations <- Fox.serialCombined(tasks)(_.annotations).map(_.flatten).toFox finishedAnnotations = annotations.filter(_.state == Finished) zip <- AnnotationService.zipAnnotations(finishedAnnotations, taskType.summary + "_nmls.zip") @@ -209,7 +209,7 @@ class AnnotationIOController @Inject()(val messagesApi: MessagesApi) for { taskTypeIdValidated <- ObjectId.parse(taskTypeId) - tasktype <- TaskTypeSQLDAO.findOne(taskTypeIdValidated) ?~> Messages("taskType.notFound") + tasktype <- TaskTypeDAO.findOne(taskTypeIdValidated) ?~> Messages("taskType.notFound") _ <- ensureTeamAdministration(user, tasktype._team) ?~> Messages("notAllowed") zip <- createTaskTypeZip(tasktype) } yield Ok.sendFile(zip.file) diff --git a/app/controllers/Application.scala b/app/controllers/Application.scala index 2d8b22566f..0c6720e160 100755 --- a/app/controllers/Application.scala +++ b/app/controllers/Application.scala @@ -4,7 +4,7 @@ import com.scalableminds.util.tools.{Fox, FoxImplicits} import javax.inject.Inject import com.typesafe.config.ConfigRenderOptions import oxalis.security.WebknossosSilhouette.UserAwareAction -import models.analytics.{AnalyticsEntrySQL, AnalyticsSQLDAO} +import models.analytics.{AnalyticsEntry, AnalyticsSQL} import models.binary.DataStoreHandlingStrategy import play.api.i18n.MessagesApi import play.api.Play.current @@ -21,7 +21,7 @@ class Application @Inject()(val messagesApi: MessagesApi) extends Controller { if (user.isSuperUser) Some(DataStoreHandlingStrategy.webKnossosToken) else None } for { - schemaVersion <- ReleaseInformationSQLDAO.getSchemaVersion.futureBox + schemaVersion <- ReleaseInformationDAO.getSchemaVersion.futureBox } yield { Ok(Json.obj( "webknossos" -> webknossos.BuildInfo.toMap.mapValues(_.toString), @@ -33,8 +33,8 @@ class Application @Inject()(val messagesApi: MessagesApi) extends Controller { } def analytics(namespace: String) = UserAwareAction(parse.json(1024 * 1024)) { implicit request => - AnalyticsSQLDAO.insertOne( - AnalyticsEntrySQL( + AnalyticsSQL.insertOne( + AnalyticsEntry( ObjectId.generate, request.identity.map(_._id), namespace, @@ -49,7 +49,7 @@ class Application @Inject()(val messagesApi: MessagesApi) extends Controller { } -object ReleaseInformationSQLDAO extends SimpleSQLDAO with FoxImplicits { +object ReleaseInformationDAO extends SimpleSQLDAO with FoxImplicits { def getSchemaVersion = { for { rList <- run(sql"select schemaVersion from webknossos.releaseInformation".as[Int]) diff --git a/app/controllers/Authentication.scala b/app/controllers/Authentication.scala index 8e2f4eb0d7..0505ff975d 100755 --- a/app/controllers/Authentication.scala +++ b/app/controllers/Authentication.scala @@ -11,7 +11,7 @@ import com.scalableminds.util.mail._ import com.scalableminds.util.accesscontext.GlobalAccessContext import com.scalableminds.util.rpc.RPC import com.scalableminds.util.tools.{Fox, FoxImplicits} -import models.binary.{DataStoreSQL, DataStoreSQLDAO} +import models.binary.{DataStore, DataStoreDAO} import models.team._ import models.user.UserService.{Mailer => _, _} import models.user._ @@ -162,7 +162,7 @@ class Authentication @Inject()( Fox.successful(BadRequest(Json.obj("messages" -> Json.toJson(errors.map(t => Json.obj("error" -> t)))))) } else { for { - organization <- OrganizationSQLDAO.findOneByName(signUpData.organization)(GlobalAccessContext) + organization <- OrganizationDAO.findOneByName(signUpData.organization)(GlobalAccessContext) user <- UserService.insert(organization._id, email, firstName, lastName, signUpData.password, automaticUserActivation, roleOnRegistration, loginInfo, passwordHasher.hash(signUpData.password)) brainDBResult <- BrainTracing.registerIfNeeded(user).toFox @@ -254,7 +254,7 @@ class Authentication @Inject()( bearerTokenAuthenticatorService.userForToken(passwords.token.trim)(GlobalAccessContext).futureBox.flatMap { case Full(user) => for { - _ <- UserSQLDAO.updatePasswordInfo(user._id, passwordHasher.hash(passwords.password1))(GlobalAccessContext) + _ <- UserDAO.updatePasswordInfo(user._id, passwordHasher.hash(passwords.password1))(GlobalAccessContext) _ <- bearerTokenAuthenticatorService.remove(passwords.token.trim) } yield Ok case _ => @@ -406,7 +406,7 @@ class Authentication @Inject()( ) } - private def creatingOrganizationsIsAllowed(requestingUser: Option[UserSQL]) = { + private def creatingOrganizationsIsAllowed(requestingUser: Option[User]) = { val noOrganizationPresent = InitialDataService.assertNoOrganizationsPresent val configurationFlagSet = Play.configuration.getBoolean("application.allowOrganzationCreation").getOrElse(false) ?~> "allowOrganzationCreation.notEnabled" val userIsSuperUser = requestingUser.exists(_.isSuperUser).toFox @@ -417,10 +417,10 @@ class Authentication @Inject()( private def createOrganization(organizationDisplayName: String) = for { organizationName <- normalizeName(organizationDisplayName).toFox ?~> "invalid organization name" - organization = OrganizationSQL(ObjectId.generate, organizationName.replaceAll(" ", "_"), "", "", organizationDisplayName) - organizationTeam = TeamSQL(ObjectId.generate, organization._id, organization.name, isOrganizationTeam = true) - _ <- OrganizationSQLDAO.insertOne(organization)(GlobalAccessContext) - _ <- TeamSQLDAO.insertOne(organizationTeam)(GlobalAccessContext) + organization = Organization(ObjectId.generate, organizationName.replaceAll(" ", "_"), "", "", organizationDisplayName) + organizationTeam = Team(ObjectId.generate, organization._id, organization.name, isOrganizationTeam = true) + _ <- OrganizationDAO.insertOne(organization)(GlobalAccessContext) + _ <- TeamDAO.insertOne(organizationTeam)(GlobalAccessContext) _ <- InitialDataService.insertLocalDataStoreIfEnabled } yield { organization @@ -428,7 +428,7 @@ class Authentication @Inject()( private def createOrganizationFolder(organizationName: String, loginInfo: LoginInfo)(implicit request: RequestHeader) = { - def sendRPCToDataStore(dataStore: DataStoreSQL, token: String) = { + def sendRPCToDataStore(dataStore: DataStore, token: String) = { RPC(s"${dataStore.url}/data/triggers/newOrganizationFolder") .withQueryString("token" -> token, "organizationName" -> organizationName) .get @@ -436,7 +436,7 @@ class Authentication @Inject()( for { token <- env.combinedAuthenticatorService.tokenAuthenticatorService.createAndInit(loginInfo, TokenType.DataStore, deleteOld = false).toFox - datastores <- DataStoreSQLDAO.findAll(GlobalAccessContext) + datastores <- DataStoreDAO.findAll(GlobalAccessContext) _ <- Fox.combined(datastores.map(sendRPCToDataStore(_, token))) } yield Full(()) diff --git a/app/controllers/ConfigurationController.scala b/app/controllers/ConfigurationController.scala index 791a10fb19..ae8c9c121c 100755 --- a/app/controllers/ConfigurationController.scala +++ b/app/controllers/ConfigurationController.scala @@ -2,9 +2,9 @@ package controllers import com.scalableminds.util.tools.Fox import javax.inject.Inject -import models.binary.{DataSetSQL, DataSetSQLDAO} +import models.binary.{DataSet, DataSetDAO} import models.configuration.{DataSetConfiguration, UserConfiguration} -import models.user.{UserDataSetConfigurationSQLDAO, UserService} +import models.user.{UserDataSetConfigurationDAO, UserService} import oxalis.security.WebknossosSilhouette.{SecuredAction, UserAwareAction} import play.api.i18n.{Messages, MessagesApi} import play.api.libs.concurrent.Execution.Implicits._ @@ -38,10 +38,10 @@ class ConfigurationController @Inject()(val messagesApi: MessagesApi) extends Co def readDataSet(dataSetName: String) = UserAwareAction.async { implicit request => request.identity.toFox.flatMap { user => for { - configurationJson: JsValue <- UserDataSetConfigurationSQLDAO.findOneForUserAndDataset(user._id, dataSetName) + configurationJson: JsValue <- UserDataSetConfigurationDAO.findOneForUserAndDataset(user._id, dataSetName) } yield DataSetConfiguration(configurationJson.validate[Map[String, JsValue]].getOrElse(Map.empty)) } - .orElse(DataSetSQLDAO.findOneByName(dataSetName).flatMap(_.defaultConfiguration)) + .orElse(DataSetDAO.findOneByName(dataSetName).flatMap(_.defaultConfiguration)) .getOrElse(DataSetConfiguration.constructInitialDefault(List())) .map(configuration => Ok(toJson(configuration.configurationOrDefaults))) } @@ -57,7 +57,7 @@ class ConfigurationController @Inject()(val messagesApi: MessagesApi) extends Co } def readDataSetDefault(dataSetName: String) = SecuredAction.async { implicit request => - DataSetSQLDAO.findOneByName(dataSetName).flatMap { dataSet: DataSetSQL => + DataSetDAO.findOneByName(dataSetName).flatMap { dataSet: DataSet => dataSet.defaultConfiguration match { case Some(c) => Fox.successful(Ok(toJson(c.configurationOrDefaults))) case _ => DataSetConfiguration.constructInitialDefault(dataSet).map(c => Ok(toJson(c.configurationOrDefaults))) @@ -67,11 +67,11 @@ class ConfigurationController @Inject()(val messagesApi: MessagesApi) extends Co def updateDataSetDefault(dataSetName: String) = SecuredAction.async(parse.json(maxLength = 20480)) { implicit request => for { - dataset <- DataSetSQLDAO.findOneByName(dataSetName) ?~> Messages("dataset.notFound") + dataset <- DataSetDAO.findOneByName(dataSetName) ?~> Messages("dataset.notFound") _ <- Fox.assertTrue(request.identity.isTeamManagerOrAdminOfOrg(dataset._organization)) ?~> Messages("notAllowed") jsConfiguration <- request.body.asOpt[JsObject] ?~> Messages("user.configuration.dataset.invalid") conf = jsConfiguration.fields.toMap - _ <- DataSetSQLDAO.updateDefaultConfigurationByName(dataSetName, DataSetConfiguration(conf)) + _ <- DataSetDAO.updateDefaultConfigurationByName(dataSetName, DataSetConfiguration(conf)) } yield { JsonOk(Messages("user.configuration.dataset.updated")) } diff --git a/app/controllers/Controller.scala b/app/controllers/Controller.scala index cb2399fe8c..bfff249ad3 100755 --- a/app/controllers/Controller.scala +++ b/app/controllers/Controller.scala @@ -4,7 +4,7 @@ import com.scalableminds.webknossos.datastore.controllers.ValidationHelpers import com.scalableminds.util.mvc.ExtendedController import com.scalableminds.util.tools.{Converter, Fox} import com.typesafe.scalalogging.LazyLogging -import models.user.UserSQL +import models.user.User import net.liftweb.common.{Box, Failure, Full, ParamFailure} import oxalis.view.ProvidesSessionData import play.api.i18n.{I18nSupport, Messages, MessagesApi} @@ -26,7 +26,7 @@ trait Controller extends PlayController implicit def AuthenticatedRequest2Request[T](r: SecuredRequest[T]): Request[T] = r.request - def ensureTeamAdministration(user: UserSQL, teamId: ObjectId): Fox[Unit] = + def ensureTeamAdministration(user: User, teamId: ObjectId): Fox[Unit] = Fox.assertTrue(user.isTeamManagerOrAdminOf(teamId)) ?~> Messages("team.admin.notAllowed") case class Filter[A, T](name: String, predicate: (A, T) => Fox[Boolean], default: Option[String] = None)(implicit converter: Converter[String, A]) { diff --git a/app/controllers/DataSetController.scala b/app/controllers/DataSetController.scala index fa089b7596..c86e7a1317 100755 --- a/app/controllers/DataSetController.scala +++ b/app/controllers/DataSetController.scala @@ -5,7 +5,7 @@ import com.scalableminds.util.geometry.Point3D import com.scalableminds.util.tools.DefaultConverters._ import com.scalableminds.util.tools.{Fox, JsonHelper} import models.binary._ -import models.team.TeamSQLDAO +import models.team.TeamDAO import models.user.UserService import oxalis.security.URLSharing import oxalis.security.WebknossosSilhouette.{SecuredAction, UserAwareAction} @@ -38,7 +38,7 @@ class DataSetController @Inject()(val messagesApi: MessagesApi) extends Controll def thumbnail(dataSetName: String, dataLayerName: String, w: Option[Int], h: Option[Int]) = UserAwareAction.async { implicit request => - def imageFromCacheIfPossible(dataSet: DataSetSQL) = { + def imageFromCacheIfPossible(dataSet: DataSet) = { val width = Math.clamp(w.getOrElse(DefaultThumbnailWidth), 1, MaxThumbnailHeight) val height = Math.clamp(h.getOrElse(DefaultThumbnailHeight), 1, MaxThumbnailHeight) Cache.get(s"thumbnail-$dataSetName*$dataLayerName-$width-$height") match { @@ -60,7 +60,7 @@ class DataSetController @Inject()(val messagesApi: MessagesApi) extends Controll } for { - dataSet <- DataSetSQLDAO.findOneByName(dataSetName) ?~> Messages("dataSet.notFound", dataSetName) + dataSet <- DataSetDAO.findOneByName(dataSetName) ?~> Messages("dataSet.notFound", dataSetName) layer <- dataSet.getDataLayerByName(dataLayerName) ?~> Messages("dataLayer.notFound", dataLayerName) image <- imageFromCacheIfPossible(dataSet) } yield { @@ -73,13 +73,13 @@ class DataSetController @Inject()(val messagesApi: MessagesApi) extends Controll def list = UserAwareAction.async { implicit request => UsingFilters( - Filter("isEditable", (value: Boolean, el: DataSetSQL) => + Filter("isEditable", (value: Boolean, el: DataSet) => for {isEditable <- el.isEditableBy(request.identity)} yield {isEditable && value || !isEditable && !value}), - Filter("isActive", (value: Boolean, el: DataSetSQL) => + Filter("isActive", (value: Boolean, el: DataSet) => Fox.successful(el.isUsable == value)) ) { filter => for { - dataSets <- DataSetSQLDAO.findAll + dataSets <- DataSetDAO.findAll filtered <- filter.applyOn(dataSets) js <- Fox.serialCombined(filtered)(d => d.publicWrites(request.identity)) } yield { @@ -90,7 +90,7 @@ class DataSetController @Inject()(val messagesApi: MessagesApi) extends Controll def accessList(dataSetName: String) = SecuredAction.async { implicit request => for { - dataSet <- DataSetSQLDAO.findOneByName(dataSetName) ?~> Messages("dataSet.notFound", dataSetName) + dataSet <- DataSetDAO.findOneByName(dataSetName) ?~> Messages("dataSet.notFound", dataSetName) allowedTeams <- dataSet.allowedTeamIds users <- UserService.findByTeams(allowedTeams) usersJs <- Fox.serialCombined(users.distinct)(_.compactWrites) @@ -102,7 +102,7 @@ class DataSetController @Inject()(val messagesApi: MessagesApi) extends Controll def read(dataSetName: String, sharingToken: Option[String]) = UserAwareAction.async { implicit request => val ctx = URLSharing.fallbackTokenAccessContext(sharingToken) for { - dataSet <- DataSetSQLDAO.findOneByName(dataSetName)(ctx) ?~> Messages("dataSet.notFound", dataSetName) + dataSet <- DataSetDAO.findOneByName(dataSetName)(ctx) ?~> Messages("dataSet.notFound", dataSetName) js <- dataSet.publicWrites(request.identity) } yield { Ok(Json.toJson(js)) @@ -113,10 +113,10 @@ class DataSetController @Inject()(val messagesApi: MessagesApi) extends Controll withJsonBodyUsing(dataSetPublicReads) { case (description, displayName, isPublic) => for { - dataSet <- DataSetSQLDAO.findOneByName(dataSetName) ?~> Messages("dataSet.notFound", dataSetName) + dataSet <- DataSetDAO.findOneByName(dataSetName) ?~> Messages("dataSet.notFound", dataSetName) _ <- Fox.assertTrue(dataSet.isEditableBy(request.identity)) ?~> Messages("notAllowed") - _ <- DataSetSQLDAO.updateFields(dataSet._id, description, displayName, isPublic) - updated <- DataSetSQLDAO.findOneByName(dataSetName) + _ <- DataSetDAO.updateFields(dataSet._id, description, displayName, isPublic) + updated <- DataSetDAO.findOneByName(dataSetName) js <- updated.publicWrites(Some(request.identity)) } yield { Ok(Json.toJson(js)) @@ -127,7 +127,7 @@ class DataSetController @Inject()(val messagesApi: MessagesApi) extends Controll def importDataSet(dataSetName: String) = SecuredAction.async { implicit request => for { _ <- DataSetService.isProperDataSetName(dataSetName) ?~> Messages("dataSet.import.impossible.name") - dataSet <- DataSetSQLDAO.findOneByName(dataSetName) ?~> Messages("dataSet.notFound", dataSetName) + dataSet <- DataSetDAO.findOneByName(dataSetName) ?~> Messages("dataSet.notFound", dataSetName) result <- DataSetService.importDataSet(dataSet) } yield { Status(result.status)(result.body) @@ -137,14 +137,14 @@ class DataSetController @Inject()(val messagesApi: MessagesApi) extends Controll def updateTeams(dataSetName: String) = SecuredAction.async(parse.json) { implicit request => withJsonBodyAs[List[String]] { teams => for { - dataSet <- DataSetSQLDAO.findOneByName(dataSetName) ?~> Messages("dataSet.notFound", dataSetName) + dataSet <- DataSetDAO.findOneByName(dataSetName) ?~> Messages("dataSet.notFound", dataSetName) _ <- Fox.assertTrue(dataSet.isEditableBy(request.identity)) ?~> Messages("notAllowed") teamIdsValidated <- Fox.serialCombined(teams)(ObjectId.parse(_)) - userTeams <- TeamSQLDAO.findAllEditable + userTeams <- TeamDAO.findAllEditable oldAllowedTeams <- dataSet.allowedTeamIds teamsWithoutUpdate = oldAllowedTeams.filterNot(t => userTeams.exists(_._id == t)) teamsWithUpdate = teamIdsValidated.filter(t => userTeams.exists(_._id == t)) - _ <- DataSetAllowedTeamsSQLDAO.updateAllowedTeamsForDataSet(dataSet._id, (teamsWithUpdate ++ teamsWithoutUpdate).distinct) + _ <- DataSetAllowedTeamsDAO.updateAllowedTeamsForDataSet(dataSet._id, (teamsWithUpdate ++ teamsWithoutUpdate).distinct) } yield Ok(Json.toJson((teamsWithUpdate ++ teamsWithoutUpdate).map(_.toString))) } @@ -158,7 +158,7 @@ class DataSetController @Inject()(val messagesApi: MessagesApi) extends Controll def deleteSharingToken(dataSetName: String) = SecuredAction.async { implicit request => for { - _ <- DataSetSQLDAO.updateSharingTokenByName(dataSetName, None) + _ <- DataSetDAO.updateSharingTokenByName(dataSetName, None) } yield Ok } diff --git a/app/controllers/DataStoreController.scala b/app/controllers/DataStoreController.scala index 7e8bc74997..c3e0472122 100644 --- a/app/controllers/DataStoreController.scala +++ b/app/controllers/DataStoreController.scala @@ -2,7 +2,7 @@ package controllers import javax.inject.Inject import com.scalableminds.util.tools.{Fox, FoxImplicits} -import models.binary.DataStoreSQLDAO +import models.binary.DataStoreDAO import oxalis.security.WebknossosSilhouette.UserAwareAction import play.api.i18n.{Messages, MessagesApi} import play.api.libs.concurrent.Execution.Implicits._ @@ -11,7 +11,7 @@ import play.api.libs.json.{Json, Writes} class DataStoreController @Inject()(val messagesApi: MessagesApi) extends Controller with FoxImplicits { def list = UserAwareAction.async { implicit request => for { - dataStores <- DataStoreSQLDAO.findAll ?~> Messages("dataStore.list.failed") + dataStores <- DataStoreDAO.findAll ?~> Messages("dataStore.list.failed") js <- Fox.serialCombined(dataStores)(d => d.publicWrites) } yield { Ok(Json.toJson(js)) diff --git a/app/controllers/InitialDataController.scala b/app/controllers/InitialDataController.scala index c658e7a8d0..9f8d349600 100644 --- a/app/controllers/InitialDataController.scala +++ b/app/controllers/InitialDataController.scala @@ -8,13 +8,13 @@ import com.typesafe.scalalogging.LazyLogging import javax.inject.Inject import models.binary._ import models.configuration.UserConfiguration -import models.project.{ProjectSQL, ProjectSQLDAO} -import models.task.{TaskTypeSQL, TaskTypeSQLDAO} +import models.project.{Project, ProjectDAO} +import models.task.{TaskType, TaskTypeDAO} import models.team._ import models.user._ import net.liftweb.common.Full import org.joda.time.DateTime -import oxalis.security.{TokenSQL, TokenSQLDAO, TokenType} +import oxalis.security.{Token, TokenDAO, TokenType} import play.api.i18n.MessagesApi import play.api.Play.current import oxalis.security.WebknossosSilhouette.UserAwareAction @@ -47,9 +47,9 @@ Sampletown Samplecountry """ val organizationTeamId = ObjectId.generate - val defaultOrganization = OrganizationSQL(ObjectId.generate, "Connectomics department", additionalInformation, "/assets/images/mpi-logos.svg", "MPI for Brain Research") - val organizationTeam = TeamSQL(organizationTeamId, defaultOrganization._id, defaultOrganization.name, true) - val defaultUser = UserSQL( + val defaultOrganization = Organization(ObjectId.generate, "Connectomics department", additionalInformation, "/assets/images/mpi-logos.svg", "MPI for Brain Research") + val organizationTeam = Team(organizationTeamId, defaultOrganization._id, defaultOrganization.name, true) + val defaultUser = User( ObjectId.generate, defaultOrganization._id, defaultUserEmail, @@ -85,7 +85,7 @@ Samplecountry def assertNoOrganizationsPresent = for { - organizations <- OrganizationSQLDAO.findAll + organizations <- OrganizationDAO.findAll _ <- organizations.isEmpty ?~> "initialData.organizationsNotEmpty" } yield () @@ -94,9 +94,9 @@ Samplecountry case Full(_) => Fox.successful(()) case _ => for { - _ <- UserSQLDAO.insertOne(defaultUser) - _ <- UserExperiencesSQLDAO.updateExperiencesForUser(defaultUser._id, Map("sampleExp" -> 10)) - _ <- UserTeamRolesSQLDAO.insertTeamMembership(defaultUser._id, TeamMembershipSQL(organizationTeam._id, true)) + _ <- UserDAO.insertOne(defaultUser) + _ <- UserExperiencesDAO.updateExperiencesForUser(defaultUser._id, Map("sampleExp" -> 10)) + _ <- UserTeamRolesDAO.insertTeamMembership(defaultUser._id, TeamMembershipSQL(organizationTeam._id, true)) _ = logger.info("Inserted default user scmboy") } yield () }.toFox @@ -104,10 +104,10 @@ Samplecountry def insertToken = { val expiryTime = Play.configuration.underlying.getDuration("silhouette.tokenAuthenticator.authenticatorExpiry").toMillis - TokenSQLDAO.findOneByLoginInfo("credentials", defaultUserEmail, TokenType.Authentication).futureBox.flatMap { + TokenDAO.findOneByLoginInfo("credentials", defaultUserEmail, TokenType.Authentication).futureBox.flatMap { case Full(_) => Fox.successful(()) case _ => - val newToken = TokenSQL( + val newToken = Token( ObjectId.generate, "secretScmBoyToken", LoginInfo("credentials", defaultUserEmail), @@ -116,51 +116,51 @@ Samplecountry None, TokenType.Authentication ) - TokenSQLDAO.insertOne(newToken) + TokenDAO.insertOne(newToken) } } def insertOrganization = { - OrganizationSQLDAO.findOneByName(defaultOrganization.name).futureBox.flatMap { + OrganizationDAO.findOneByName(defaultOrganization.name).futureBox.flatMap { case Full(_) => Fox.successful(()) case _ => - OrganizationSQLDAO.insertOne(defaultOrganization) + OrganizationDAO.insertOne(defaultOrganization) }.toFox } def insertTeams = { - TeamSQLDAO.findAll.flatMap { + TeamDAO.findAll.flatMap { teams => if (teams.isEmpty) - TeamSQLDAO.insertOne(organizationTeam) + TeamDAO.insertOne(organizationTeam) else Fox.successful(()) }.toFox } def insertTaskType = { - TaskTypeSQLDAO.findAll.flatMap { + TaskTypeDAO.findAll.flatMap { types => if (types.isEmpty) { - val taskType = TaskTypeSQL( + val taskType = TaskType( ObjectId.generate, organizationTeam._id, "sampleTaskType", "Check those cells out!" ) - for {_ <- TaskTypeSQLDAO.insertOne(taskType)} yield () + for {_ <- TaskTypeDAO.insertOne(taskType)} yield () } else Fox.successful(()) }.toFox } def insertProject = { - ProjectSQLDAO.findAll.flatMap { + ProjectDAO.findAll.flatMap { projects => if (projects.isEmpty) { UserService.defaultUser.flatMap { user => - val project = ProjectSQL(ObjectId.generate, organizationTeam._id, user._id, "sampleProject", 100, false, Some(5400000)) - for {_ <- ProjectSQLDAO.insertOne(project)} yield () + val project = Project(ObjectId.generate, organizationTeam._id, user._id, "sampleProject", 100, false, Some(5400000)) + for {_ <- ProjectDAO.insertOne(project)} yield () } } else Fox.successful(()) }.toFox @@ -168,11 +168,11 @@ Samplecountry def insertLocalDataStoreIfEnabled: Fox[Any] = { if (Play.configuration.getBoolean("datastore.enabled").getOrElse(true)) { - DataStoreSQLDAO.findOneByName("localhost").futureBox.map { maybeStore => + DataStoreDAO.findOneByName("localhost").futureBox.map { maybeStore => if (maybeStore.isEmpty) { val url = Play.configuration.getString("http.uri").getOrElse("http://localhost:9000") val key = Play.configuration.getString("datastore.key").getOrElse("something-secure") - DataStoreSQLDAO.insertOne(DataStoreSQL("localhost", url, WebKnossosStore, key)) + DataStoreDAO.insertOne(DataStore("localhost", url, WebKnossosStore, key)) } } } else Fox.successful(()) diff --git a/app/controllers/OrganizationController.scala b/app/controllers/OrganizationController.scala index 44214fae7f..95ba255fb6 100755 --- a/app/controllers/OrganizationController.scala +++ b/app/controllers/OrganizationController.scala @@ -15,7 +15,7 @@ class OrganizationController @Inject()(val messagesApi: MessagesApi) extends Con def listAllOrganizations = Action.async { implicit request => for { - allOrgs <- OrganizationSQLDAO.findAll(GlobalAccessContext) + allOrgs <- OrganizationDAO.findAll(GlobalAccessContext) js <- Fox.serialCombined(allOrgs)(o => o.publicWrites(GlobalAccessContext)) } yield { Ok(Json.toJson(js)) diff --git a/app/controllers/ProjectController.scala b/app/controllers/ProjectController.scala index 766d7f53bb..e7fde684da 100644 --- a/app/controllers/ProjectController.scala +++ b/app/controllers/ProjectController.scala @@ -20,7 +20,7 @@ class ProjectController @Inject()(val messagesApi: MessagesApi) extends Controll def list = SecuredAction.async { implicit request => for { - projects <- ProjectSQLDAO.findAll + projects <- ProjectDAO.findAll js <- Fox.serialCombined(projects)(_.publicWrites) } yield { Ok(Json.toJson(js)) @@ -30,8 +30,8 @@ class ProjectController @Inject()(val messagesApi: MessagesApi) extends Controll def listWithStatus = SecuredAction.async { implicit request => for { - projects <- ProjectSQLDAO.findAll - allCounts <- TaskSQLDAO.countAllOpenInstancesGroupedByProjects + projects <- ProjectDAO.findAll + allCounts <- TaskDAO.countAllOpenInstancesGroupedByProjects js <- Fox.serialCombined(projects) { project => for { openTaskInstances <- Fox.successful(allCounts.get(project._id).getOrElse(0)) @@ -46,7 +46,7 @@ class ProjectController @Inject()(val messagesApi: MessagesApi) extends Controll def read(projectName: String) = SecuredAction.async { implicit request => for { - project <- ProjectSQLDAO.findOneByName(projectName) ?~> Messages("project.notFound", projectName) + project <- ProjectDAO.findOneByName(projectName) ?~> Messages("project.notFound", projectName) js <- project.publicWrites } yield { Ok(js) @@ -56,7 +56,7 @@ class ProjectController @Inject()(val messagesApi: MessagesApi) extends Controll def delete(projectName: String) = SecuredAction.async { implicit request => for { - project <- ProjectSQLDAO.findOneByName(projectName) ?~> Messages("project.notFound", projectName) + project <- ProjectDAO.findOneByName(projectName) ?~> Messages("project.notFound", projectName) _ <- project.isDeletableBy(request.identity) ?~> Messages("project.remove.notAllowed") _ <- ProjectService.deleteOne(project._id) ?~> Messages("project.remove.failure") } yield { @@ -65,12 +65,12 @@ class ProjectController @Inject()(val messagesApi: MessagesApi) extends Controll } def create = SecuredAction.async(parse.json) { implicit request => - withJsonBodyUsing(ProjectSQL.projectPublicReads) { project => - ProjectSQLDAO.findOneByName(project.name)(GlobalAccessContext).futureBox.flatMap { + withJsonBodyUsing(Project.projectPublicReads) { project => + ProjectDAO.findOneByName(project.name)(GlobalAccessContext).futureBox.flatMap { case Empty => for { _ <- ensureTeamAdministration(request.identity, project._team) - _ <- ProjectSQLDAO.insertOne(project) + _ <- ProjectDAO.insertOne(project) js <- project.publicWrites } yield Ok(js) case _ => @@ -80,12 +80,12 @@ class ProjectController @Inject()(val messagesApi: MessagesApi) extends Controll } def update(projectName: String) = SecuredAction.async(parse.json) { implicit request => - withJsonBodyUsing(ProjectSQL.projectPublicReads) { updateRequest => + withJsonBodyUsing(Project.projectPublicReads) { updateRequest => for{ - project <- ProjectSQLDAO.findOneByName(projectName)(GlobalAccessContext) ?~> Messages("project.notFound", projectName) + project <- ProjectDAO.findOneByName(projectName)(GlobalAccessContext) ?~> Messages("project.notFound", projectName) _ <- ensureTeamAdministration(request.identity, project._team) - _ <- ProjectSQLDAO.updateOne(updateRequest.copy(_id = project._id, paused = project.paused)) ?~> Messages("project.update.failed", projectName) - updated <- ProjectSQLDAO.findOneByName(projectName) + _ <- ProjectDAO.updateOne(updateRequest.copy(_id = project._id, paused = project.paused)) ?~> Messages("project.update.failed", projectName) + updated <- ProjectDAO.findOneByName(projectName) js <- updated.publicWrites } yield Ok(js) } @@ -103,9 +103,9 @@ class ProjectController @Inject()(val messagesApi: MessagesApi) extends Controll private def updatePauseStatus(projectName: String, isPaused: Boolean)(implicit request: SecuredRequest[_]) = { for { - project <- ProjectSQLDAO.findOneByName(projectName) ?~> Messages("project.notFound", projectName) - _ <- ProjectSQLDAO.updatePaused(project._id, isPaused) ?~> Messages("project.update.failed", projectName) - updatedProject <- ProjectSQLDAO.findOne(project._id) ?~> Messages("project.notFound", projectName) + project <- ProjectDAO.findOneByName(projectName) ?~> Messages("project.notFound", projectName) + _ <- ProjectDAO.updatePaused(project._id, isPaused) ?~> Messages("project.update.failed", projectName) + updatedProject <- ProjectDAO.findOne(project._id) ?~> Messages("project.notFound", projectName) js <- updatedProject.publicWrites } yield { Ok(js) @@ -115,9 +115,9 @@ class ProjectController @Inject()(val messagesApi: MessagesApi) extends Controll def tasksForProject(projectName: String) = SecuredAction.async { implicit request => for { - project <- ProjectSQLDAO.findOneByName(projectName) ?~> Messages("project.notFound", projectName) + project <- ProjectDAO.findOneByName(projectName) ?~> Messages("project.notFound", projectName) _ <- ensureTeamAdministration(request.identity, project._team) ?~> Messages("notAllowed") - tasks <- TaskSQLDAO.findAllByProject(project._id)(GlobalAccessContext) + tasks <- TaskDAO.findAllByProject(project._id)(GlobalAccessContext) js <- Fox.serialCombined(tasks)(_.publicWrites) } yield { Ok(Json.toJson(js)) @@ -128,9 +128,9 @@ class ProjectController @Inject()(val messagesApi: MessagesApi) extends Controll implicit request => for { _ <- (delta.getOrElse(1L) >= 0) ?~> Messages("project.increaseTaskInstances.negative") - project <- ProjectSQLDAO.findOneByName(projectName) ?~> Messages("project.notFound", projectName) - _ <- TaskSQLDAO.incrementTotalInstancesOfAllWithProject(project._id, delta.getOrElse(1L)) - openInstanceCount <- TaskSQLDAO.countOpenInstancesForProject(project._id) + project <- ProjectDAO.findOneByName(projectName) ?~> Messages("project.notFound", projectName) + _ <- TaskDAO.incrementTotalInstancesOfAllWithProject(project._id, delta.getOrElse(1L)) + openInstanceCount <- TaskDAO.countOpenInstancesForProject(project._id) js <- project.publicWritesWithStatus(openInstanceCount) } yield Ok(js) } @@ -138,7 +138,7 @@ class ProjectController @Inject()(val messagesApi: MessagesApi) extends Controll def usersWithOpenTasks(projectName: String) = SecuredAction.async { implicit request => for { - emails <- ProjectSQLDAO.findUsersWithOpenTasks(projectName) + emails <- ProjectDAO.findUsersWithOpenTasks(projectName) } yield { Ok(Json.toJson(emails)) } diff --git a/app/controllers/ReportController.scala b/app/controllers/ReportController.scala index 3856d13e1e..b19e5c4183 100644 --- a/app/controllers/ReportController.scala +++ b/app/controllers/ReportController.scala @@ -6,9 +6,9 @@ package controllers import javax.inject.Inject import com.scalableminds.util.accesscontext.{DBAccessContext, GlobalAccessContext} import com.scalableminds.util.tools.{Fox, FoxImplicits} -import models.annotation.{AnnotationSQLDAO, AnnotationTypeSQL} -import models.team.TeamSQLDAO -import models.user.{UserSQL, UserSQLDAO} +import models.annotation.{AnnotationDAO, AnnotationTypeSQL} +import models.team.TeamDAO +import models.user.{User, UserDAO} import oxalis.security.WebknossosSilhouette.SecuredAction import play.api.i18n.MessagesApi import play.api.libs.concurrent.Execution.Implicits._ @@ -24,7 +24,7 @@ case class ProjectProgressEntry(projectName: String, paused: Boolean, totalTasks finishedInstances: Int, activeInstances: Int) object ProjectProgressEntry { implicit val jsonFormat = Json.format[ProjectProgressEntry] } -object ReportSQLDAO extends SimpleSQLDAO { +object ReportDAO extends SimpleSQLDAO { def projectProgress(teamId: ObjectId)(implicit ctx: DBAccessContext): Fox[List[ProjectProgressEntry]] = { for { @@ -73,7 +73,7 @@ object ReportSQLDAO extends SimpleSQLDAO { FROM filteredProjects p join webknossos.tasks_ t on p._id = t._project - left join (select #${AnnotationSQLDAO.columns} from webknossos.annotations_ a where a.state = 'Active' and a.typ = 'Task') a on t._id = a._task + left join (select #${AnnotationDAO.columns} from webknossos.annotations_ a where a.state = 'Active' and a.typ = 'Task') a on t._id = a._task group by p._id ) @@ -120,24 +120,24 @@ class ReportController @Inject()(val messagesApi: MessagesApi) extends Controlle def projectProgressOverview(teamId: String) = SecuredAction.async { implicit request => for { - entries <- ReportSQLDAO.projectProgress(ObjectId(teamId))(GlobalAccessContext) + entries <- ReportDAO.projectProgress(ObjectId(teamId))(GlobalAccessContext) } yield Ok(Json.toJson(entries)) } def openTasksOverview(teamId: String) = SecuredAction.async { implicit request => for { teamIdValidated <- ObjectId.parse(teamId) - team <- TeamSQLDAO.findOne(teamIdValidated)(GlobalAccessContext) ?~> "team.notFound" - users <- UserSQLDAO.findAllByTeams(List(team._id), includeDeactivated = false)(GlobalAccessContext) + team <- TeamDAO.findOne(teamIdValidated)(GlobalAccessContext) ?~> "team.notFound" + users <- UserDAO.findAllByTeams(List(team._id), includeDeactivated = false)(GlobalAccessContext) nonAdminUsers <- Fox.filterNot(users)(_.isTeamManagerOrAdminOf(teamIdValidated)) entries: List[OpenTasksEntry] <- getAllAvailableTaskCountsAndProjects(nonAdminUsers)(GlobalAccessContext) } yield Ok(Json.toJson(entries)) } - private def getAllAvailableTaskCountsAndProjects(users: Seq[UserSQL])(implicit ctx: DBAccessContext): Fox[List[OpenTasksEntry]] = { + private def getAllAvailableTaskCountsAndProjects(users: Seq[User])(implicit ctx: DBAccessContext): Fox[List[OpenTasksEntry]] = { val foxes = users.map { user => for { - assignmentCountsByProject <- ReportSQLDAO.getAssignmentsByProjectsFor(user._id) + assignmentCountsByProject <- ReportDAO.getAssignmentsByProjectsFor(user._id) } yield { OpenTasksEntry(user._id.toString, user.name, assignmentCountsByProject.values.sum, assignmentCountsByProject) } diff --git a/app/controllers/ScriptController.scala b/app/controllers/ScriptController.scala index d4969898ba..2d93cbc142 100644 --- a/app/controllers/ScriptController.scala +++ b/app/controllers/ScriptController.scala @@ -17,13 +17,13 @@ class ScriptController @Inject()(val messagesApi: MessagesApi) extends Controlle val scriptPublicReads = ((__ \ 'name).read[String](minLength[String](2) or maxLength[String](50)) and (__ \ 'gist).read[String] and - (__ \ 'owner).read[String] (ObjectId.stringObjectIdReads("owner"))) (ScriptSQL.fromForm _) + (__ \ 'owner).read[String] (ObjectId.stringObjectIdReads("owner"))) (Script.fromForm _) def create = SecuredAction.async(parse.json) { implicit request => withJsonBodyUsing(scriptPublicReads) { script => for { _ <- request.identity.isAdmin ?~> Messages("notAllowed") - _ <- ScriptSQLDAO.insertOne(script) + _ <- ScriptDAO.insertOne(script) js <- script.publicWrites } yield { Ok(js) @@ -34,7 +34,7 @@ class ScriptController @Inject()(val messagesApi: MessagesApi) extends Controlle def get(scriptId: String) = SecuredAction.async { implicit request => for { scriptIdValidated <- ObjectId.parse(scriptId) - script <- ScriptSQLDAO.findOne(scriptIdValidated) ?~> Messages("script.notFound") + script <- ScriptDAO.findOne(scriptIdValidated) ?~> Messages("script.notFound") js <- script.publicWrites } yield { Ok(js) @@ -43,7 +43,7 @@ class ScriptController @Inject()(val messagesApi: MessagesApi) extends Controlle def list = SecuredAction.async { implicit request => for { - scripts <- ScriptSQLDAO.findAll + scripts <- ScriptDAO.findAll js <- Fox.serialCombined(scripts)(s => s.publicWrites) } yield { Ok(Json.toJson(js)) @@ -54,10 +54,10 @@ class ScriptController @Inject()(val messagesApi: MessagesApi) extends Controlle withJsonBodyUsing(scriptPublicReads) { scriptFromForm => for { scriptIdValidated <- ObjectId.parse(scriptId) - oldScript <- ScriptSQLDAO.findOne(scriptIdValidated) ?~> Messages("script.notFound") + oldScript <- ScriptDAO.findOne(scriptIdValidated) ?~> Messages("script.notFound") _ <- (oldScript._owner == request.identity._id) ?~> Messages("script.notOwner") updatedScript = scriptFromForm.copy(_id = oldScript._id) - _ <- ScriptSQLDAO.updateOne(updatedScript) + _ <- ScriptDAO.updateOne(updatedScript) js <- updatedScript.publicWrites } yield { Ok(js) @@ -68,10 +68,10 @@ class ScriptController @Inject()(val messagesApi: MessagesApi) extends Controlle def delete(scriptId: String) = SecuredAction.async { implicit request => for { scriptIdValidated <- ObjectId.parse(scriptId) - oldScript <- ScriptSQLDAO.findOne(scriptIdValidated) ?~> Messages("script.notFound") + oldScript <- ScriptDAO.findOne(scriptIdValidated) ?~> Messages("script.notFound") _ <- (oldScript._owner == request.identity._id) ?~> Messages("script.notOwner") - _ <- ScriptSQLDAO.deleteOne(scriptIdValidated) ?~> Messages("script.removalFailed") - _ <- TaskSQLDAO.removeScriptFromAllTasks(scriptIdValidated) ?~> Messages("script.removalFailed") + _ <- ScriptDAO.deleteOne(scriptIdValidated) ?~> Messages("script.removalFailed") + _ <- TaskDAO.removeScriptFromAllTasks(scriptIdValidated) ?~> Messages("script.removalFailed") } yield { Ok } diff --git a/app/controllers/StatisticsController.scala b/app/controllers/StatisticsController.scala index 2e66ae5ba7..56a47be4f8 100644 --- a/app/controllers/StatisticsController.scala +++ b/app/controllers/StatisticsController.scala @@ -2,11 +2,11 @@ package controllers import javax.inject.Inject import com.scalableminds.util.tools.Fox -import models.annotation.AnnotationSQLDAO -import models.binary.DataSetSQLDAO -import models.task.TaskSQLDAO -import models.user.time.{TimeSpanSQL, TimeSpanService} -import models.user.UserSQLDAO +import models.annotation.AnnotationDAO +import models.binary.DataSetDAO +import models.task.TaskDAO +import models.user.time.{TimeSpan, TimeSpanService} +import models.user.UserDAO import oxalis.security.WebknossosSilhouette.SecuredAction import play.api.i18n.{Messages, MessagesApi} import play.api.libs.concurrent.Execution.Implicits._ @@ -19,8 +19,8 @@ class StatisticsController @Inject()(val messagesApi: MessagesApi) extends Controller { val intervalHandler = Map( - "month" -> TimeSpanSQL.groupByMonth _, - "week" -> TimeSpanSQL.groupByWeek _ + "month" -> TimeSpan.groupByMonth _, + "week" -> TimeSpan.groupByWeek _ ) def intervalTracingTimeJson[T <: models.user.time.Interval](times: Map[T, Duration]) = times.map { @@ -36,10 +36,10 @@ class StatisticsController @Inject()(val messagesApi: MessagesApi) case Some(handler) => for { times <- TimeSpanService.loggedTimePerInterval(handler, start, end) - numberOfUsers <- UserSQLDAO.countAll - numberOfDatasets <- DataSetSQLDAO.countAll - numberOfAnnotations <- AnnotationSQLDAO.countAll - numberOfAssignments <- TaskSQLDAO.countAllOpenInstances + numberOfUsers <- UserDAO.countAll + numberOfDatasets <- DataSetDAO.countAll + numberOfAnnotations <- AnnotationDAO.countAll + numberOfAssignments <- TaskDAO.countAllOpenInstances } yield { Ok(Json.obj( "name" -> "oxalis", @@ -59,7 +59,7 @@ class StatisticsController @Inject()(val messagesApi: MessagesApi) def users(interval: String, start: Option[Long], end: Option[Long], limit: Int) = SecuredAction.async { implicit request => for { handler <- intervalHandler.get(interval) ?~> Messages("statistics.interval.invalid") - users <- UserSQLDAO.findAll + users <- UserDAO.findAll usersWithTimes <- Fox.serialCombined(users)(user => TimeSpanService.loggedTimeOfUser(user, handler, start, end).map(user -> _)) data = usersWithTimes.sortBy(-_._2.map(_._2.toMillis).sum).take(limit) json <- Fox.combined(data.map { diff --git a/app/controllers/TaskController.scala b/app/controllers/TaskController.scala index 17b95e2de5..62bf83c598 100755 --- a/app/controllers/TaskController.scala +++ b/app/controllers/TaskController.scala @@ -9,10 +9,10 @@ import com.scalableminds.webknossos.datastore.SkeletonTracing.{SkeletonTracing, import com.scalableminds.webknossos.datastore.tracings.{ProtoGeometryImplicits, TracingReference} import models.annotation.nml.NmlService import models.annotation.AnnotationService -import models.binary.DataSetSQLDAO -import models.project.ProjectSQLDAO +import models.binary.DataSetDAO +import models.project.ProjectDAO import models.task._ -import models.team.OrganizationSQLDAO +import models.team.OrganizationDAO import models.user._ import net.liftweb.common.Box import oxalis.security.WebknossosSilhouette.{SecuredAction, SecuredRequest} @@ -65,7 +65,7 @@ class TaskController @Inject() (val messagesApi: MessagesApi) def read(taskId: String) = SecuredAction.async { implicit request => for { - task <- TaskSQLDAO.findOne(ObjectId(taskId)) ?~> Messages("task.notFound") + task <- TaskDAO.findOne(ObjectId(taskId)) ?~> Messages("task.notFound") js <- task.publicWrites } yield { Ok(js) @@ -87,8 +87,8 @@ class TaskController @Inject() (val messagesApi: MessagesApi) jsonString <- body.dataParts.get("formJSON").flatMap(_.headOption) ?~> Messages("format.json.missing") params <- JsonHelper.parseJsonToFox[NmlTaskParameters](jsonString) ?~> Messages("task.create.failed") taskTypeIdValidated <- ObjectId.parse(params.taskTypeId) - taskType <- TaskTypeSQLDAO.findOne(taskTypeIdValidated) ?~> Messages("taskType.notFound") - project <- ProjectSQLDAO.findOneByName(params.projectName) ?~> Messages("project.notFound", params.projectName) + taskType <- TaskTypeDAO.findOne(taskTypeIdValidated) ?~> Messages("taskType.notFound") + project <- ProjectDAO.findOneByName(params.projectName) ?~> Messages("project.notFound", params.projectName) _ <- ensureTeamAdministration(request.identity, project._team) parseResults: List[NmlService.NmlParseResult] = NmlService.extractFromFile(inputFile.ref.file, inputFile.filename).parseResults skeletonSuccesses <- Fox.serialCombined(parseResults)(_.toSkeletonSuccessFox) ?~> Messages("task.create.failed") @@ -132,7 +132,7 @@ class TaskController @Inject() (val messagesApi: MessagesApi) Fox.failure("Cannot create tasks on multiple datasets in one go.") } - def taskToJsonFoxed(taskFox: Fox[TaskSQL], otherFox: Fox[_]): Fox[JsObject] = { + def taskToJsonFoxed(taskFox: Fox[Task], otherFox: Fox[_]): Fox[JsObject] = { for { _ <- otherFox task <- taskFox @@ -142,11 +142,11 @@ class TaskController @Inject() (val messagesApi: MessagesApi) for { dataSetName <- assertAllOnSameDataset - dataSet <- DataSetSQLDAO.findOneByName(requestedTasks.head._1.dataSet) ?~> Messages("dataSet.notFound", dataSetName) + dataSet <- DataSetDAO.findOneByName(requestedTasks.head._1.dataSet) ?~> Messages("dataSet.notFound", dataSetName) dataStoreHandler <- dataSet.dataStoreHandler tracingReferences: List[Box[TracingReference]] <- dataStoreHandler.saveSkeletonTracings(SkeletonTracings(requestedTasks.map(_._2))) requestedTasksWithTracingReferences = requestedTasks zip tracingReferences - taskObjects: List[Fox[TaskSQL]] = requestedTasksWithTracingReferences.map(r => createTaskWithoutAnnotationBase(r._1._1, r._2)) + taskObjects: List[Fox[Task]] = requestedTasksWithTracingReferences.map(r => createTaskWithoutAnnotationBase(r._1._1, r._2)) zipped = (requestedTasks, tracingReferences, taskObjects).zipped.toList annotationBases = zipped.map(tuple => AnnotationService.createAnnotationBase( taskFox = tuple._3, @@ -171,21 +171,21 @@ class TaskController @Inject() (val messagesApi: MessagesApi) case Some(scriptId) => for { scriptIdValidated <- ObjectId.parse(scriptId) - _ <- ScriptSQLDAO.findOne(scriptIdValidated) ?~> Messages("script.notFound") + _ <- ScriptDAO.findOne(scriptIdValidated) ?~> Messages("script.notFound") } yield () case _ => Fox.successful(()) } } - private def createTaskWithoutAnnotationBase(params: TaskParameters, tracingReferenceBox: Box[TracingReference])(implicit request: SecuredRequest[_]): Fox[TaskSQL] = { + private def createTaskWithoutAnnotationBase(params: TaskParameters, tracingReferenceBox: Box[TracingReference])(implicit request: SecuredRequest[_]): Fox[Task] = { for { _ <- tracingReferenceBox.toFox taskTypeIdValidated <- ObjectId.parse(params.taskTypeId) - taskType <- TaskTypeSQLDAO.findOne(taskTypeIdValidated) ?~> Messages("taskType.notFound") - project <- ProjectSQLDAO.findOneByName(params.projectName) ?~> Messages("project.notFound", params.projectName) + taskType <- TaskTypeDAO.findOne(taskTypeIdValidated) ?~> Messages("taskType.notFound") + project <- ProjectDAO.findOneByName(params.projectName) ?~> Messages("project.notFound", params.projectName) _ <- validateScript(params.scriptId) _ <- ensureTeamAdministration(request.identity, project._team) - task = TaskSQL( + task = Task( ObjectId.generate, project._id, params.scriptId.map(ObjectId(_)), @@ -199,7 +199,7 @@ class TaskController @Inject() (val messagesApi: MessagesApi) editRotation = params.editRotation, creationInfo = params.creationInfo ) - _ <- TaskSQLDAO.insertOne(task) + _ <- TaskDAO.insertOne(task) } yield task } @@ -208,11 +208,11 @@ class TaskController @Inject() (val messagesApi: MessagesApi) val params = request.body for { taskIdValidated <- ObjectId.parse(taskId) - task <- TaskSQLDAO.findOne(taskIdValidated) ?~> Messages("task.notFound") + task <- TaskDAO.findOne(taskIdValidated) ?~> Messages("task.notFound") project <- task.project _ <- ensureTeamAdministration(request.identity, project._team) ?~> Messages("notAllowed") - _ <- TaskSQLDAO.updateTotalInstances(task._id, task.totalInstances + params.openInstances - task.openInstances) - updatedTask <- TaskSQLDAO.findOne(taskIdValidated) + _ <- TaskDAO.updateTotalInstances(task._id, task.totalInstances + params.openInstances - task.openInstances) + updatedTask <- TaskDAO.findOne(taskIdValidated) json <- updatedTask.publicWrites } yield { JsonOk(json, Messages("task.editSuccess")) @@ -222,10 +222,10 @@ class TaskController @Inject() (val messagesApi: MessagesApi) def delete(taskId: String) = SecuredAction.async { implicit request => for { taskIdValidated <- ObjectId.parse(taskId) - task <- TaskSQLDAO.findOne(taskIdValidated) ?~> Messages("task.notFound") + task <- TaskDAO.findOne(taskIdValidated) ?~> Messages("task.notFound") project <- task.project _ <- ensureTeamAdministration(request.identity, project._team) ?~> Messages("notAllowed") - _ <- TaskSQLDAO.removeOneAndItsAnnotations(task._id) + _ <- TaskDAO.removeOneAndItsAnnotations(task._id) } yield { JsonOk(Messages("task.removed")) } @@ -234,7 +234,7 @@ class TaskController @Inject() (val messagesApi: MessagesApi) def listTasksForType(taskTypeId: String) = SecuredAction.async { implicit request => for { taskTypeIdValidated <- ObjectId.parse(taskTypeId) - tasks <- TaskSQLDAO.findAllByTaskType(taskTypeIdValidated) + tasks <- TaskDAO.findAllByTaskType(taskTypeIdValidated) js <- Fox.serialCombined(tasks)(_.publicWrites) } yield { Ok(Json.toJson(js)) @@ -249,7 +249,7 @@ class TaskController @Inject() (val messagesApi: MessagesApi) taskIdsOpt <- Fox.runOptional((request.body \ "ids").asOpt[List[String]])(ids => Fox.serialCombined(ids)(ObjectId.parse)) taskTypeIdOpt <- Fox.runOptional((request.body \ "taskType").asOpt[String])(ObjectId.parse(_)) randomizeOpt = (request.body \ "random").asOpt[Boolean] - tasks <- TaskSQLDAO.findAllByProjectAndTaskTypeAndIdsAndUser(projectNameOpt, taskTypeIdOpt, taskIdsOpt, userIdOpt, randomizeOpt) + tasks <- TaskDAO.findAllByProjectAndTaskTypeAndIdsAndUser(projectNameOpt, taskTypeIdOpt, taskIdsOpt, userIdOpt, randomizeOpt) jsResult <- Fox.serialCombined(tasks)(_.publicWrites) } yield { Ok(Json.toJson(jsResult)) @@ -261,7 +261,7 @@ class TaskController @Inject() (val messagesApi: MessagesApi) val user = request.identity for { teams <- getAllowedTeamsForNextTask(user) - (task, initializingAnnotationId) <- TaskSQLDAO.assignNext(user._id, teams) ?~> Messages("task.unavailable") + (task, initializingAnnotationId) <- TaskDAO.assignNext(user._id, teams) ?~> Messages("task.unavailable") insertedAnnotationBox <- AnnotationService.createAnnotationFor(user, task, initializingAnnotationId).futureBox _ <- AnnotationService.abortInitializedAnnotationOnFailure(initializingAnnotationId, insertedAnnotationBox) annotation <- insertedAnnotationBox.toFox @@ -272,12 +272,12 @@ class TaskController @Inject() (val messagesApi: MessagesApi) } - private def getAllowedTeamsForNextTask(user: UserSQL)(implicit ctx: DBAccessContext): Fox[List[ObjectId]] = { + private def getAllowedTeamsForNextTask(user: User)(implicit ctx: DBAccessContext): Fox[List[ObjectId]] = { (for { numberOfOpen <- AnnotationService.countOpenNonAdminTasks(user) } yield { if (user.isAdmin) { - OrganizationSQLDAO.findOne(user._organization).flatMap(_.teamIds) + OrganizationDAO.findOne(user._organization).flatMap(_.teamIds) } else if (numberOfOpen < MAX_OPEN_TASKS) { user.teamIds } else { @@ -298,7 +298,7 @@ class TaskController @Inject() (val messagesApi: MessagesApi) val user = request.identity for { teamIds <- user.teamIds - task <- TaskSQLDAO.peekNextAssignment(user._id, teamIds) ?~> Messages("task.unavailable") + task <- TaskDAO.peekNextAssignment(user._id, teamIds) ?~> Messages("task.unavailable") taskJson <- task.publicWrites(GlobalAccessContext) } yield Ok(taskJson) } diff --git a/app/controllers/TaskTypeController.scala b/app/controllers/TaskTypeController.scala index 4ccad3bc57..c10b517197 100755 --- a/app/controllers/TaskTypeController.scala +++ b/app/controllers/TaskTypeController.scala @@ -18,13 +18,13 @@ class TaskTypeController @Inject()(val messagesApi: MessagesApi) extends Control ((__ \ 'summary).read[String](minLength[String](2) or maxLength[String](50)) and (__ \ 'description).read[String] and (__ \ 'team).read[String] (ObjectId.stringObjectIdReads("team")) and - (__ \ 'settings).read[AnnotationSettings]) (TaskTypeSQL.fromForm _) + (__ \ 'settings).read[AnnotationSettings]) (TaskType.fromForm _) def create = SecuredAction.async(parse.json) { implicit request => withJsonBodyUsing(taskTypePublicReads) { taskType => for { _ <- ensureTeamAdministration(request.identity, taskType._team) - _ <- TaskTypeSQLDAO.insertOne(taskType) + _ <- TaskTypeDAO.insertOne(taskType) js <- taskType.publicWrites } yield Ok(js) } @@ -33,7 +33,7 @@ class TaskTypeController @Inject()(val messagesApi: MessagesApi) extends Control def get(taskTypeId: String) = SecuredAction.async { implicit request => for { taskTypeIdValidated <- ObjectId.parse(taskTypeId) - taskType <- TaskTypeSQLDAO.findOne(taskTypeIdValidated) ?~> Messages("taskType.notFound") + taskType <- TaskTypeDAO.findOne(taskTypeIdValidated) ?~> Messages("taskType.notFound") _ <- ensureTeamAdministration(request.identity, taskType._team) js <- taskType.publicWrites } yield Ok(js) @@ -41,7 +41,7 @@ class TaskTypeController @Inject()(val messagesApi: MessagesApi) extends Control def list = SecuredAction.async { implicit request => for { - taskTypes <- TaskTypeSQLDAO.findAll + taskTypes <- TaskTypeDAO.findAll js <- Fox.serialCombined(taskTypes)(t => t.publicWrites) } yield Ok(Json.toJson(js)) } @@ -50,11 +50,11 @@ class TaskTypeController @Inject()(val messagesApi: MessagesApi) extends Control withJsonBodyUsing(taskTypePublicReads) { taskTypeFromForm => for { taskTypeIdValidated <- ObjectId.parse(taskTypeId) - taskType <- TaskTypeSQLDAO.findOne(taskTypeIdValidated) ?~> Messages("taskType.notFound") + taskType <- TaskTypeDAO.findOne(taskTypeIdValidated) ?~> Messages("taskType.notFound") updatedTaskType = taskTypeFromForm.copy(_id = taskType._id) _ <- ensureTeamAdministration(request.identity, taskType._team) _ <- ensureTeamAdministration(request.identity, updatedTaskType._team) - _ <- TaskTypeSQLDAO.updateOne(updatedTaskType) + _ <- TaskTypeDAO.updateOne(updatedTaskType) js <- updatedTaskType.publicWrites } yield { JsonOk(js, Messages("taskType.editSuccess")) @@ -65,10 +65,10 @@ class TaskTypeController @Inject()(val messagesApi: MessagesApi) extends Control def delete(taskTypeId: String) = SecuredAction.async { implicit request => for { taskTypeIdValidated <- ObjectId.parse(taskTypeId) - taskType <- TaskTypeSQLDAO.findOne(taskTypeIdValidated) ?~> Messages("taskType.notFound") + taskType <- TaskTypeDAO.findOne(taskTypeIdValidated) ?~> Messages("taskType.notFound") _ <- ensureTeamAdministration(request.identity, taskType._team) - _ <- TaskTypeSQLDAO.deleteOne(taskTypeIdValidated) ?~> Messages("taskType.deleteFailure") - _ <- TaskSQLDAO.removeAllWithTaskTypeAndItsAnnotations(taskTypeIdValidated) ?~> Messages("taskType.deleteFailure") + _ <- TaskTypeDAO.deleteOne(taskTypeIdValidated) ?~> Messages("taskType.deleteFailure") + _ <- TaskDAO.removeAllWithTaskTypeAndItsAnnotations(taskTypeIdValidated) ?~> Messages("taskType.deleteFailure") } yield { JsonOk(Messages("taskType.deleteSuccess", taskType.summary)) } diff --git a/app/controllers/TeamController.scala b/app/controllers/TeamController.scala index f35560688e..ca74e20960 100755 --- a/app/controllers/TeamController.scala +++ b/app/controllers/TeamController.scala @@ -5,7 +5,7 @@ import javax.inject.Inject import com.scalableminds.util.accesscontext.GlobalAccessContext import com.scalableminds.util.tools.Fox import models.team._ -import models.user.UserTeamRolesSQLDAO +import models.user.UserTeamRolesDAO import oxalis.security.WebknossosSilhouette.SecuredAction import play.api.i18n.{Messages, MessagesApi} import play.api.libs.concurrent.Execution.Implicits._ @@ -20,7 +20,7 @@ class TeamController @Inject()(val messagesApi: MessagesApi) extends Controller def list = SecuredAction.async { implicit request => for { - allTeams <- TeamSQLDAO.findAllEditable + allTeams <- TeamDAO.findAllEditable js <- Fox.serialCombined(allTeams)(_.publicWrites) } yield { Ok(Json.toJson(js)) @@ -29,7 +29,7 @@ class TeamController @Inject()(val messagesApi: MessagesApi) extends Controller def listAllTeams = Action.async { implicit request => for { - allTeams <- TeamSQLDAO.findAll(GlobalAccessContext) + allTeams <- TeamDAO.findAll(GlobalAccessContext) js <- Fox.serialCombined(allTeams)(_.publicWrites(GlobalAccessContext)) } yield { Ok(Json.toJson(js)) @@ -39,9 +39,9 @@ class TeamController @Inject()(val messagesApi: MessagesApi) extends Controller def delete(id: String) = SecuredAction.async { implicit request => for { teamIdValidated <- ObjectId.parse(id) - team <- TeamSQLDAO.findOne(teamIdValidated) - _ <- TeamSQLDAO.deleteOne(teamIdValidated) - _ <- UserTeamRolesSQLDAO.removeTeamFromAllUsers(teamIdValidated) + team <- TeamDAO.findOne(teamIdValidated) + _ <- TeamDAO.deleteOne(teamIdValidated) + _ <- UserTeamRolesDAO.removeTeamFromAllUsers(teamIdValidated) } yield { JsonOk(Messages("team.deleted")) } @@ -51,8 +51,8 @@ class TeamController @Inject()(val messagesApi: MessagesApi) extends Controller withJsonBodyUsing(teamNameReads) { teamName => for { _ <- bool2Fox(request.identity.isAdmin) ?~> Messages("user.noAdmin") - team = TeamSQL(ObjectId.generate, request.identity._organization, teamName) - _ <- TeamSQLDAO.insertOne(team) + team = Team(ObjectId.generate, request.identity._organization, teamName) + _ <- TeamDAO.insertOne(team) js <- team.publicWrites } yield { JsonOk(js, Messages("team.created")) diff --git a/app/controllers/TimeController.scala b/app/controllers/TimeController.scala index 1685a7aa6d..51d9952b04 100644 --- a/app/controllers/TimeController.scala +++ b/app/controllers/TimeController.scala @@ -5,7 +5,7 @@ import java.util.Calendar import javax.inject.Inject import com.scalableminds.util.tools.{Fox, FoxImplicits} -import models.user.time.TimeSpanSQLDAO +import models.user.time.TimeSpanDAO import models.user._ import oxalis.security.WebknossosSilhouette.{SecuredAction, SecuredRequest} import play.api.i18n.{Messages, MessagesApi} @@ -19,7 +19,7 @@ class TimeController @Inject()(val messagesApi: MessagesApi) extends Controller //all users with working hours > 0 def getWorkingHoursOfAllUsers(year: Int, month: Int, startDay: Option[Int], endDay: Option[Int]) = SecuredAction.async { implicit request => for { - users <- UserSQLDAO.findAll + users <- UserDAO.findAll filteredUsers <- Fox.filter(users)(user => request.identity.isTeamManagerOrAdminOf(user)) //rather Admin than TeamManager js <- loggedTimeForUserListByMonth(filteredUsers, year, month, startDay, endDay) } yield { @@ -51,7 +51,7 @@ class TimeController @Inject()(val messagesApi: MessagesApi) extends Controller //helper methods - def loggedTimeForUserListByMonth(users: List[UserSQL], year: Int, month: Int, startDay: Option[Int], endDay: Option[Int]) (implicit request: SecuredRequest[AnyContent]): Fox[JsValue] = { + def loggedTimeForUserListByMonth(users: List[User], year: Int, month: Int, startDay: Option[Int], endDay: Option[Int])(implicit request: SecuredRequest[AnyContent]): Fox[JsValue] = { lazy val startDate = Calendar.getInstance() lazy val endDate = Calendar.getInstance() @@ -76,7 +76,7 @@ class TimeController @Inject()(val messagesApi: MessagesApi) extends Controller Fox.combined(futureJsObjects).map(jsObjectList => Json.toJson(jsObjectList)) } - def loggedTimeForUserListByTimestamp(user: UserSQL, startDate: Long, endDate: Long) (implicit request: SecuredRequest[AnyContent]): Fox[JsValue] = { + def loggedTimeForUserListByTimestamp(user: User, startDate: Long, endDate: Long)(implicit request: SecuredRequest[AnyContent]): Fox[JsValue] = { lazy val sDate = Calendar.getInstance() lazy val eDate = Calendar.getInstance() @@ -86,10 +86,10 @@ class TimeController @Inject()(val messagesApi: MessagesApi) extends Controller getUserHours(user, sDate, eDate) } - def getUserHours(user: UserSQL, startDate: Calendar, endDate: Calendar)(implicit request: SecuredRequest[AnyContent]): Fox[JsObject] = { + def getUserHours(user: User, startDate: Calendar, endDate: Calendar)(implicit request: SecuredRequest[AnyContent]): Fox[JsObject] = { for { userJs <- user.compactWrites - timeJs <- TimeSpanSQLDAO.findAllByUserWithTask(user._id, Some(startDate.getTimeInMillis), Some(endDate.getTimeInMillis)) + timeJs <- TimeSpanDAO.findAllByUserWithTask(user._id, Some(startDate.getTimeInMillis), Some(endDate.getTimeInMillis)) } yield { Json.obj( "user" -> userJs, diff --git a/app/controllers/UserController.scala b/app/controllers/UserController.scala index 4f22d6268f..93ec0d13ae 100755 --- a/app/controllers/UserController.scala +++ b/app/controllers/UserController.scala @@ -4,7 +4,7 @@ import javax.inject.Inject import com.scalableminds.util.accesscontext.{DBAccessContext, GlobalAccessContext} import com.scalableminds.util.tools.DefaultConverters._ import com.scalableminds.util.tools.{Fox, FoxImplicits} -import models.annotation.{AnnotationSQLDAO, AnnotationTypeSQL} +import models.annotation.{AnnotationDAO, AnnotationTypeSQL} import models.team._ import models.user._ import models.user.time._ @@ -37,7 +37,7 @@ class UserController @Inject()(val messagesApi: MessagesApi) def user(userId: String) = SecuredAction.async { implicit request => for { userIdValidated <- ObjectId.parse(userId) - user <- UserSQLDAO.findOne(userIdValidated) ?~> Messages("user.notFound") + user <- UserDAO.findOne(userIdValidated) ?~> Messages("user.notFound") _ <- Fox.assertTrue(user.isEditableBy(request.identity)) ?~> Messages("notAllowed") js <- user.publicWrites(request.identity) } yield Ok(js) @@ -45,7 +45,7 @@ class UserController @Inject()(val messagesApi: MessagesApi) def annotations(isFinished: Option[Boolean], limit: Option[Int]) = SecuredAction.async { implicit request => for { - annotations <- AnnotationSQLDAO.findAllFor(request.identity._id, isFinished, AnnotationTypeSQL.Explorational, limit.getOrElse(defaultAnnotationLimit)) + annotations <- AnnotationDAO.findAllFor(request.identity._id, isFinished, AnnotationTypeSQL.Explorational, limit.getOrElse(defaultAnnotationLimit)) jsonList <- Fox.serialCombined(annotations)(_.publicWrites(Some(request.identity))) } yield { Ok(Json.toJson(jsonList)) @@ -54,7 +54,7 @@ class UserController @Inject()(val messagesApi: MessagesApi) def tasks(isFinished: Option[Boolean], limit: Option[Int]) = SecuredAction.async { implicit request => for { - annotations <- AnnotationSQLDAO.findAllFor(request.identity._id, isFinished, AnnotationTypeSQL.Task, limit.getOrElse(defaultAnnotationLimit)) + annotations <- AnnotationDAO.findAllFor(request.identity._id, isFinished, AnnotationTypeSQL.Task, limit.getOrElse(defaultAnnotationLimit)) jsonList <- Fox.serialCombined(annotations)(_.publicWrites(Some(request.identity))) } yield { Ok(Json.toJson(jsonList)) @@ -64,9 +64,9 @@ class UserController @Inject()(val messagesApi: MessagesApi) def userLoggedTime(userId: String) = SecuredAction.async { implicit request => for { userIdValidated <- ObjectId.parse(userId) - user <- UserSQLDAO.findOne(userIdValidated) ?~> Messages("user.notFound") + user <- UserDAO.findOne(userIdValidated) ?~> Messages("user.notFound") _ <- Fox.assertTrue(user.isEditableBy(request.identity)) ?~> Messages("notAllowed") - loggedTimeAsMap <- TimeSpanService.loggedTimeOfUser(user, TimeSpanSQL.groupByMonth) + loggedTimeAsMap <- TimeSpanService.loggedTimeOfUser(user, TimeSpan.groupByMonth) } yield { JsonOk(Json.obj("loggedTime" -> loggedTimeAsMap.map { case (paymentInterval, duration) => @@ -76,15 +76,15 @@ class UserController @Inject()(val messagesApi: MessagesApi) } } - private def groupByAnnotationAndDay(timeSpan: TimeSpanSQL) = { - (timeSpan._annotation.map(_.toString).getOrElse(""), TimeSpanSQL.groupByDay(timeSpan)) + private def groupByAnnotationAndDay(timeSpan: TimeSpan) = { + (timeSpan._annotation.map(_.toString).getOrElse(""), TimeSpan.groupByDay(timeSpan)) } def usersLoggedTime = SecuredAction.async(validateJson[TimeSpanRequest]) { implicit request => Fox.combined(request.body.users.map { userId => for { userIdValidated <- ObjectId.parse(userId) - user <- UserSQLDAO.findOne(userIdValidated) ?~> Messages("user.notFound") + user <- UserDAO.findOne(userIdValidated) ?~> Messages("user.notFound") _ <- Fox.assertTrue(user.isEditableBy(request.identity)) ?~> Messages("notAllowed") result <- TimeSpanService.loggedTimeOfUser(user, groupByAnnotationAndDay, Some(request.body.start), Some(request.body.end)) } yield { @@ -111,9 +111,9 @@ class UserController @Inject()(val messagesApi: MessagesApi) def userAnnotations(userId: String, isFinished: Option[Boolean], limit: Option[Int]) = SecuredAction.async { implicit request => for { userIdValidated <- ObjectId.parse(userId) - user <- UserSQLDAO.findOne(userIdValidated) ?~> Messages("user.notFound") + user <- UserDAO.findOne(userIdValidated) ?~> Messages("user.notFound") _ <- Fox.assertTrue(user.isEditableBy(request.identity)) ?~> Messages("notAllowed") - annotations <- AnnotationSQLDAO.findAllFor(userIdValidated, isFinished, AnnotationTypeSQL.Explorational, limit.getOrElse(defaultAnnotationLimit)) + annotations <- AnnotationDAO.findAllFor(userIdValidated, isFinished, AnnotationTypeSQL.Explorational, limit.getOrElse(defaultAnnotationLimit)) jsonList <- Fox.serialCombined(annotations)(_.publicWrites(Some(request.identity))) } yield { Ok(Json.toJson(jsonList)) @@ -123,9 +123,9 @@ class UserController @Inject()(val messagesApi: MessagesApi) def userTasks(userId: String, isFinished: Option[Boolean], limit: Option[Int]) = SecuredAction.async { implicit request => for { userIdValidated <- ObjectId.parse(userId) - user <- UserSQLDAO.findOne(userIdValidated) ?~> Messages("user.notFound") + user <- UserDAO.findOne(userIdValidated) ?~> Messages("user.notFound") _ <- Fox.assertTrue(user.isEditableBy(request.identity)) ?~> Messages("notAllowed") - annotations <- AnnotationSQLDAO.findAllFor(userIdValidated, isFinished, AnnotationTypeSQL.Task, limit.getOrElse(defaultAnnotationLimit)) + annotations <- AnnotationDAO.findAllFor(userIdValidated, isFinished, AnnotationTypeSQL.Task, limit.getOrElse(defaultAnnotationLimit)) jsonList <- Fox.serialCombined(annotations)(_.publicWrites(Some(request.identity))) } yield { Ok(Json.toJson(jsonList)) @@ -134,7 +134,7 @@ class UserController @Inject()(val messagesApi: MessagesApi) def loggedTime = SecuredAction.async { implicit request => for { - loggedTimeAsMap <- TimeSpanService.loggedTimeOfUser(request.identity, TimeSpanSQL.groupByMonth) + loggedTimeAsMap <- TimeSpanService.loggedTimeOfUser(request.identity, TimeSpan.groupByMonth) } yield { JsonOk(Json.obj("loggedTime" -> loggedTimeAsMap.map { case (paymentInterval, duration) => @@ -146,11 +146,11 @@ class UserController @Inject()(val messagesApi: MessagesApi) def list = SecuredAction.async { implicit request => UsingFilters( - Filter("isEditable", (value: Boolean, el: UserSQL) => for {isEditable <- el.isEditableBy(request.identity)} yield isEditable == value), - Filter("isAdmin", (value: Boolean, el: UserSQL) => Fox.successful(el.isAdmin == value)) + Filter("isEditable", (value: Boolean, el: User) => for {isEditable <- el.isEditableBy(request.identity)} yield isEditable == value), + Filter("isAdmin", (value: Boolean, el: User) => Fox.successful(el.isAdmin == value)) ) { filter => for { - users <- UserSQLDAO.findAll + users <- UserDAO.findAll filtered <- filter.applyOn(users) js <- Fox.serialCombined(filtered.sortBy(_.lastName.toLowerCase))(u => u.publicWrites(request.identity)) } yield { @@ -168,7 +168,7 @@ class UserController @Inject()(val messagesApi: MessagesApi) (__ \ "teams").read[List[TeamMembershipSQL]](Reads.list(TeamMembershipSQL.publicReads)) and (__ \ "experiences").read[Map[String, Int]]).tupled - def ensureProperTeamAdministration(user: UserSQL, teams: List[(TeamMembershipSQL, TeamSQL)]) = { + def ensureProperTeamAdministration(user: User, teams: List[(TeamMembershipSQL, Team)]) = { Fox.combined(teams.map { case (TeamMembershipSQL(_, true), team) => { for { @@ -181,7 +181,7 @@ class UserController @Inject()(val messagesApi: MessagesApi) }) } - private def checkAdminOnlyUpdates(user: UserSQL, isActive: Boolean, isAdmin: Boolean, email: String)(issuingUser: UserSQL): Boolean = { + private def checkAdminOnlyUpdates(user: User, isActive: Boolean, isAdmin: Boolean, email: String)(issuingUser: User): Boolean = { if (user.isDeactivated == !isActive && user.isAdmin == isAdmin && user.email == email) true else issuingUser.isAdminOf(user) } @@ -192,10 +192,10 @@ class UserController @Inject()(val messagesApi: MessagesApi) case (firstName, lastName, email, isActive, isAdmin, assignedMemberships, experiences) => for { userIdValidated <- ObjectId.parse(userId) - user <- UserSQLDAO.findOne(userIdValidated) ?~> Messages("user.notFound") + user <- UserDAO.findOne(userIdValidated) ?~> Messages("user.notFound") _ <- Fox.assertTrue(user.isEditableBy(request.identity)) ?~> Messages("notAllowed") _ <- checkAdminOnlyUpdates(user, isActive, isAdmin, email)(issuingUser) ?~> Messages("notAllowed") - teams <- Fox.combined(assignedMemberships.map(t => TeamSQLDAO.findOne(t.teamId)(GlobalAccessContext) ?~> Messages("team.notFound"))) + teams <- Fox.combined(assignedMemberships.map(t => TeamDAO.findOne(t.teamId)(GlobalAccessContext) ?~> Messages("team.notFound"))) oldTeamMemberships <- user.teamMemberships teamsWithoutUpdate <- Fox.filterNot(oldTeamMemberships)(t => issuingUser.isTeamManagerOrAdminOf(t.teamId)) assignedMembershipWTeams = assignedMemberships.zip(teams) @@ -204,7 +204,7 @@ class UserController @Inject()(val messagesApi: MessagesApi) trimmedExperiences = experiences.map { case (key, value) => key.trim -> value } updatedTeams = teamsWithUpdate.map(_._1) ++ teamsWithoutUpdate _ <- UserService.update(user, firstName.trim, lastName.trim, email, isActive, isAdmin, updatedTeams, trimmedExperiences) - updatedUser <- UserSQLDAO.findOne(userIdValidated) + updatedUser <- UserDAO.findOne(userIdValidated) updatedJs <- updatedUser.publicWrites(request.identity) } yield { Ok(updatedJs) diff --git a/app/controllers/UserTokenController.scala b/app/controllers/UserTokenController.scala index 572ef0366c..390efbd3ca 100644 --- a/app/controllers/UserTokenController.scala +++ b/app/controllers/UserTokenController.scala @@ -5,8 +5,8 @@ import com.scalableminds.util.accesscontext.{DBAccessContext, GlobalAccessContex import com.scalableminds.util.tools.Fox import com.scalableminds.webknossos.datastore.services.{AccessMode, AccessResourceType, UserAccessAnswer, UserAccessRequest} import models.annotation._ -import models.binary.{DataSetSQLDAO, DataStoreHandlingStrategy} -import models.user.UserSQL +import models.binary.{DataSetDAO, DataStoreHandlingStrategy} +import models.user.User import net.liftweb.common.{Box, Full} import oxalis.security.WebknossosSilhouette.UserAwareAction import oxalis.security.{TokenType, URLSharing, WebknossosSilhouette} @@ -60,11 +60,11 @@ class UserTokenController @Inject()(val messagesApi: MessagesApi) } - private def handleDataSourceAccess(dataSourceName: String, mode: AccessMode.Value, userBox: Box[UserSQL])(implicit ctx: DBAccessContext): Fox[UserAccessAnswer] = { + private def handleDataSourceAccess(dataSourceName: String, mode: AccessMode.Value, userBox: Box[User])(implicit ctx: DBAccessContext): Fox[UserAccessAnswer] = { //Note: reading access is ensured in findOneBySourceName, depending on the implicit DBAccessContext def tryRead: Fox[UserAccessAnswer] = { - DataSetSQLDAO.findOneByName(dataSourceName).futureBox map { + DataSetDAO.findOneByName(dataSourceName).futureBox map { case Full(_) => UserAccessAnswer(true) case _ => UserAccessAnswer(false, Some("No read access on dataset")) } @@ -72,7 +72,7 @@ class UserTokenController @Inject()(val messagesApi: MessagesApi) def tryWrite: Fox[UserAccessAnswer] = { for { - dataset <- DataSetSQLDAO.findOneByName(dataSourceName) ?~> "datasource.notFound" + dataset <- DataSetDAO.findOneByName(dataSourceName) ?~> "datasource.notFound" user <- userBox.toFox isAllowed <- user.isTeamManagerOrAdminOfOrg(dataset._organization) } yield { @@ -98,10 +98,10 @@ class UserTokenController @Inject()(val messagesApi: MessagesApi) } } - private def handleTracingAccess(tracingId: String, mode: AccessMode.Value, userBox: Box[UserSQL])(implicit ctx: DBAccessContext): Fox[UserAccessAnswer] = { + private def handleTracingAccess(tracingId: String, mode: AccessMode.Value, userBox: Box[User])(implicit ctx: DBAccessContext): Fox[UserAccessAnswer] = { - def findAnnotationForTracing(tracingId: String): Fox[AnnotationSQL] = { - val annotationFox = AnnotationSQLDAO.findOneByTracingId(tracingId) + def findAnnotationForTracing(tracingId: String): Fox[Annotation] = { + val annotationFox = AnnotationDAO.findOneByTracingId(tracingId) for { annotationBox <- annotationFox.futureBox } yield { diff --git a/app/controllers/WKDataStoreController.scala b/app/controllers/WKDataStoreController.scala index 1f7c6ee122..ac5af49ad2 100644 --- a/app/controllers/WKDataStoreController.scala +++ b/app/controllers/WKDataStoreController.scala @@ -7,7 +7,7 @@ import com.scalableminds.webknossos.datastore.services.DataStoreStatus import com.scalableminds.util.accesscontext.GlobalAccessContext import com.scalableminds.util.tools.{Fox, FoxImplicits} import com.typesafe.scalalogging.LazyLogging -import models.annotation.{AnnotationSQL, AnnotationSQLDAO} +import models.annotation.{Annotation, AnnotationDAO} import models.binary._ import models.user.time.TimeSpanService import play.api.i18n.{I18nSupport, Messages, MessagesApi} @@ -39,7 +39,7 @@ class WKDataStoreController @Inject()(val messagesApi: MessagesApi) request.body.validate[DataStoreStatus] match { case JsSuccess(status, _) => logger.debug(s"Status update from data store '$name'. Status: " + status.ok) - DataStoreSQLDAO.updateUrlByName(name, status.url)(GlobalAccessContext).map(_ => Ok) + DataStoreDAO.updateUrlByName(name, status.url)(GlobalAccessContext).map(_ => Ok) case e: JsError => logger.error("Data store '$name' sent invalid update. Error: " + e) Future.successful(JsonBadRequest(JsError.toFlatJson(e))) @@ -79,16 +79,16 @@ class WKDataStoreController @Inject()(val messagesApi: MessagesApi) def handleTracingUpdateReport(name: String) = DataStoreAction(name).async(parse.json) { implicit request => for { tracingId <- (request.body \ "tracingId").asOpt[String].toFox - annotation <- AnnotationSQLDAO.findOneByTracingId(tracingId)(GlobalAccessContext) + annotation <- AnnotationDAO.findOneByTracingId(tracingId)(GlobalAccessContext) _ <- ensureAnnotationNotFinished(annotation) timestamps <- (request.body \ "timestamps").asOpt[List[Long]].toFox statisticsOpt = (request.body \ "statistics").asOpt[JsObject] userTokenOpt = (request.body \ "userToken").asOpt[String] _ <- statisticsOpt match { - case Some(statistics) => AnnotationSQLDAO.updateStatistics(annotation._id, statistics)(GlobalAccessContext) + case Some(statistics) => AnnotationDAO.updateStatistics(annotation._id, statistics)(GlobalAccessContext) case None => Fox.successful(()) } - _ <- AnnotationSQLDAO.updateModified(annotation._id, System.currentTimeMillis)(GlobalAccessContext) + _ <- AnnotationDAO.updateModified(annotation._id, System.currentTimeMillis)(GlobalAccessContext) userBox <- bearerTokenService.userForTokenOpt(userTokenOpt)(GlobalAccessContext).futureBox _ <- Fox.runOptional(userBox)(user => TimeSpanService.logUserInteraction(timestamps, user, annotation)(GlobalAccessContext)) } yield { @@ -96,7 +96,7 @@ class WKDataStoreController @Inject()(val messagesApi: MessagesApi) } } - private def ensureAnnotationNotFinished(annotation: AnnotationSQL) = { + private def ensureAnnotationNotFinished(annotation: Annotation) = { if (annotation.state == Finished) Fox.failure("annotation already finshed") else Fox.successful(()) } @@ -106,13 +106,13 @@ trait WKDataStoreActionHelper extends FoxImplicits with Results with I18nSupport import play.api.mvc._ - class RequestWithDataStore[A](val dataStore: DataStoreSQL, request: Request[A]) extends WrappedRequest[A](request) + class RequestWithDataStore[A](val dataStore: DataStore, request: Request[A]) extends WrappedRequest[A](request) case class DataStoreAction(name: String) extends ActionBuilder[RequestWithDataStore] { def invokeBlock[A](request: Request[A], block: (RequestWithDataStore[A]) => Future[Result]): Future[Result] = { request.getQueryString("key") .toFox - .flatMap(key => DataStoreSQLDAO.findOneByKey(key)(GlobalAccessContext)) // Check if key is valid + .flatMap(key => DataStoreDAO.findOneByKey(key)(GlobalAccessContext)) // Check if key is valid //.filter(dataStore => dataStore.name == name) // Check if correct name is provided .flatMap(dataStore => block(new RequestWithDataStore(dataStore, request))) // Run underlying action .getOrElse(Forbidden(Messages("dataStore.notFound"))) // Default error diff --git a/app/models/analytics/AnalyticsEntry.scala b/app/models/analytics/AnalyticsEntry.scala index dcded2444e..9b366fab9e 100644 --- a/app/models/analytics/AnalyticsEntry.scala +++ b/app/models/analytics/AnalyticsEntry.scala @@ -8,7 +8,7 @@ import slick.jdbc.PostgresProfile.api._ import slick.lifted.Rep import utils.{ObjectId, SQLDAO} -case class AnalyticsEntrySQL( +case class AnalyticsEntry( _id: ObjectId, _user: Option[ObjectId], namespace: String, @@ -17,14 +17,14 @@ case class AnalyticsEntrySQL( isDeleted: Boolean = false ) -object AnalyticsSQLDAO extends SQLDAO[AnalyticsEntrySQL, AnalyticsRow, Analytics] { +object AnalyticsSQL extends SQLDAO[AnalyticsEntry, AnalyticsRow, Analytics] { val collection = Analytics def idColumn(x: Analytics): Rep[String] = x._Id def isDeletedColumn(x: Analytics): Rep[Boolean] = x.isdeleted - def parse(r: AnalyticsRow): Fox[AnalyticsEntrySQL] = - Fox.successful(AnalyticsEntrySQL( + def parse(r: AnalyticsRow): Fox[AnalyticsEntry] = + Fox.successful(AnalyticsEntry( ObjectId(r._Id), r._User.map(ObjectId(_)), r.namespace, @@ -33,7 +33,7 @@ object AnalyticsSQLDAO extends SQLDAO[AnalyticsEntrySQL, AnalyticsRow, Analytics r.isdeleted )) - def insertOne(a: AnalyticsEntrySQL): Fox[Unit] = { + def insertOne(a: AnalyticsEntry): Fox[Unit] = { for { _ <- run(sqlu"""insert into webknossos.analytics(_id, _user, namespace, value, created, isDeleted) values(${a._id.toString}, ${a._user.map(_.id)}, ${a.namespace}, #${sanitize(a.value.toString)}, diff --git a/app/models/annotation/Annotation.scala b/app/models/annotation/Annotation.scala index b8eedc9655..8f233079d9 100755 --- a/app/models/annotation/Annotation.scala +++ b/app/models/annotation/Annotation.scala @@ -10,9 +10,9 @@ import com.scalableminds.webknossos.datastore.tracings.{TracingReference, Tracin import com.scalableminds.webknossos.schema.Tables._ import models.annotation.AnnotationState._ import models.annotation.AnnotationTypeSQL.AnnotationTypeSQL -import models.binary.{DataSetSQL, DataSetSQLDAO} -import models.task.{TaskSQLDAO, TaskTypeSQLDAO, _} -import models.user.{UserSQL, UserService} +import models.binary.{DataSet, DataSetDAO} +import models.task.{TaskDAO, TaskTypeDAO, _} +import models.user.{User, UserService} import play.api.Play.current import play.api.i18n.Messages import play.api.i18n.Messages.Implicits._ @@ -25,7 +25,7 @@ import slick.lifted.Rep import utils.{ObjectId, SQLDAO} -case class AnnotationSQL( +case class Annotation( _id: ObjectId, _dataSet: ObjectId, _task: Option[ObjectId] = None, @@ -50,14 +50,14 @@ case class AnnotationSQL( lazy val id = _id.toString lazy val team = _team.toString - def user: Fox[UserSQL] = + def user: Fox[User] = UserService.findOneById(_user, useCache = true)(GlobalAccessContext) - def task: Fox[TaskSQL] = - _task.toFox.flatMap(taskId => TaskSQLDAO.findOne(taskId)(GlobalAccessContext)) + def task: Fox[Task] = + _task.toFox.flatMap(taskId => TaskDAO.findOne(taskId)(GlobalAccessContext)) - def dataSet: Fox[DataSetSQL] = - DataSetSQLDAO.findOne(_dataSet)(GlobalAccessContext) ?~> "dataSet.notFound" + def dataSet: Fox[DataSet] = + DataSetDAO.findOne(_dataSet)(GlobalAccessContext) ?~> "dataSet.notFound" val tracingType = tracing.typ @@ -72,8 +72,8 @@ case class AnnotationSQL( if (typ == AnnotationTypeSQL.Task || typ == AnnotationTypeSQL.TracingBase) for { taskId <- _task.toFox - task: TaskSQL <- TaskSQLDAO.findOne(taskId) ?~> Messages("task.notFound") - taskType <- TaskTypeSQLDAO.findOne(task._taskType) ?~> Messages("taskType.notFound") + task: Task <- TaskDAO.findOne(taskId) ?~> Messages("task.notFound") + taskType <- TaskTypeDAO.findOne(task._taskType) ?~> Messages("taskType.notFound") } yield { taskType.settings } @@ -88,7 +88,7 @@ case class AnnotationSQL( restrictions.getOrElse(AnnotationRestrictions.defaultAnnotationRestrictions(this)) } - def publicWrites(requestingUser: Option[UserSQL] = None, restrictions: Option[AnnotationRestrictions] = None, readOnly: Option[Boolean] = None)(implicit ctx: DBAccessContext): Fox[JsObject] = { + def publicWrites(requestingUser: Option[User] = None, restrictions: Option[AnnotationRestrictions] = None, readOnly: Option[Boolean] = None)(implicit ctx: DBAccessContext): Fox[JsObject] = { for { taskJson <- task.flatMap(_.publicWrites).getOrElse(JsNull) dataSet <- dataSet @@ -123,23 +123,19 @@ case class AnnotationSQL( } -object AnnotationSQL extends FoxImplicits { - -} - -object AnnotationSQLDAO extends SQLDAO[AnnotationSQL, AnnotationsRow, Annotations] { +object AnnotationDAO extends SQLDAO[Annotation, AnnotationsRow, Annotations] { val collection = Annotations def idColumn(x: Annotations): Rep[String] = x._Id def isDeletedColumn(x: Annotations): Rep[Boolean] = x.isdeleted - def parse(r: AnnotationsRow): Fox[AnnotationSQL] = + def parse(r: AnnotationsRow): Fox[Annotation] = for { state <- AnnotationState.fromString(r.state).toFox tracingTyp <- TracingType.fromString(r.tracingTyp).toFox typ <- AnnotationTypeSQL.fromString(r.typ).toFox } yield { - AnnotationSQL( + Annotation( ObjectId(r._Id), ObjectId(r._Dataset), r._Task.map(ObjectId(_)), @@ -172,7 +168,7 @@ object AnnotationSQLDAO extends SQLDAO[AnnotationSQL, AnnotationsRow, Annotation // read operations - override def findOne(id: ObjectId)(implicit ctx: DBAccessContext): Fox[AnnotationSQL] = + override def findOne(id: ObjectId)(implicit ctx: DBAccessContext): Fox[Annotation] = for { accessQuery <- readAccessQuery rList <- run(sql"select #${columns} from #${existingCollectionName} where _id = ${id.id} and #${accessQuery}".as[AnnotationsRow]) @@ -180,7 +176,7 @@ object AnnotationSQLDAO extends SQLDAO[AnnotationSQL, AnnotationsRow, Annotation parsed <- parse(r) ?~> ("SQLDAO Error: Could not parse database row for object " + id + " in " + collectionName) } yield parsed - def findAllFor(userId: ObjectId, isFinished: Option[Boolean], annotationType: AnnotationTypeSQL, limit: Int)(implicit ctx: DBAccessContext): Fox[List[AnnotationSQL]] = { + def findAllFor(userId: ObjectId, isFinished: Option[Boolean], annotationType: AnnotationTypeSQL, limit: Int)(implicit ctx: DBAccessContext): Fox[List[Annotation]] = { val stateQuery = isFinished match { case Some(true) => s"state = '${AnnotationState.Finished.toString}'" case Some(false) => s"state = '${AnnotationState.Active.toString}'" @@ -196,7 +192,7 @@ object AnnotationSQLDAO extends SQLDAO[AnnotationSQL, AnnotationsRow, Annotation } // hint: does not use access query (because they dont support prefixes yet). use only after separate access check - def findAllFinishedForProject(projectId: ObjectId)(implicit ctx: DBAccessContext): Fox[List[AnnotationSQL]] = + def findAllFinishedForProject(projectId: ObjectId)(implicit ctx: DBAccessContext): Fox[List[Annotation]] = for { accessQuery <- readAccessQuery r <- run(sql"""select #${columnsWithPrefix("a.")} from #${existingCollectionName} a @@ -205,7 +201,7 @@ object AnnotationSQLDAO extends SQLDAO[AnnotationSQL, AnnotationsRow, Annotation parsed <- Fox.combined(r.toList.map(parse)) } yield parsed - def findAllByTaskIdAndType(taskId: ObjectId, typ: AnnotationTypeSQL)(implicit ctx: DBAccessContext): Fox[List[AnnotationSQL]] = + def findAllByTaskIdAndType(taskId: ObjectId, typ: AnnotationTypeSQL)(implicit ctx: DBAccessContext): Fox[List[Annotation]] = for { r <- run(Annotations.filter(r => notdel(r) && r._Task === taskId.id && r.typ === typ.toString && r.state =!= AnnotationState.Cancelled.toString).result) accessQuery <- readAccessQuery @@ -214,7 +210,7 @@ object AnnotationSQLDAO extends SQLDAO[AnnotationSQL, AnnotationsRow, Annotation parsed <- Fox.combined(r.toList.map(parse)) } yield parsed - def findOneByTracingId(tracingId: String)(implicit ctx: DBAccessContext): Fox[AnnotationSQL] = + def findOneByTracingId(tracingId: String)(implicit ctx: DBAccessContext): Fox[Annotation] = for { rList <- run(Annotations.filter(r => notdel(r) && r.tracingId === tracingId).result.headOption) accessQuery <- readAccessQuery @@ -250,7 +246,7 @@ object AnnotationSQLDAO extends SQLDAO[AnnotationSQL, AnnotationsRow, Annotation // update operations - def insertOne(a: AnnotationSQL): Fox[Unit] = { + def insertOne(a: Annotation): Fox[Unit] = { for { _ <- run( sqlu""" @@ -263,7 +259,7 @@ object AnnotationSQLDAO extends SQLDAO[AnnotationSQL, AnnotationsRow, Annotation } yield () } - def updateInitialized(a: AnnotationSQL): Fox[Unit] = { + def updateInitialized(a: Annotation): Fox[Unit] = { for { _ <- run( sqlu""" diff --git a/app/models/annotation/AnnotationInformationProvider.scala b/app/models/annotation/AnnotationInformationProvider.scala index 8845222d7d..370469d6d1 100755 --- a/app/models/annotation/AnnotationInformationProvider.scala +++ b/app/models/annotation/AnnotationInformationProvider.scala @@ -12,17 +12,17 @@ trait AnnotationInformationProvider with FoxImplicits with models.basics.Implicits { - def provideAnnotation(typ: String, id: String)(implicit request: UserAwareRequest[_]): Fox[AnnotationSQL] = + def provideAnnotation(typ: String, id: String)(implicit request: UserAwareRequest[_]): Fox[Annotation] = for { annotationIdentifier <- AnnotationIdentifier.parse(typ, id) annotation <- provideAnnotation(annotationIdentifier) ?~> "annotation.notFound" } yield annotation - def provideAnnotation(annotationIdentifier: AnnotationIdentifier)(implicit request: UserAwareRequest[_]): Fox[AnnotationSQL] = { + def provideAnnotation(annotationIdentifier: AnnotationIdentifier)(implicit request: UserAwareRequest[_]): Fox[Annotation] = { AnnotationStore.requestAnnotation(annotationIdentifier, request.identity) } - def nameFor(annotation: AnnotationSQL)(implicit request: UserAwareRequest[_]): Fox[String] = { + def nameFor(annotation: Annotation)(implicit request: UserAwareRequest[_]): Fox[String] = { if (annotation.name == "") { handlerForTyp(annotation.typ).nameForAnnotation(annotation) } else diff --git a/app/models/annotation/AnnotationMerger.scala b/app/models/annotation/AnnotationMerger.scala index c70f13234c..559177ed5c 100644 --- a/app/models/annotation/AnnotationMerger.scala +++ b/app/models/annotation/AnnotationMerger.scala @@ -6,7 +6,7 @@ import com.scalableminds.util.accesscontext.DBAccessContext import com.scalableminds.util.tools.{Fox, FoxImplicits} import com.typesafe.scalalogging.LazyLogging import models.annotation.AnnotationTypeSQL.AnnotationTypeSQL -import models.binary.DataSetSQLDAO +import models.binary.DataSetDAO import play.api.libs.concurrent.Execution.Implicits._ import utils.ObjectId @@ -16,19 +16,19 @@ object AnnotationMerger extends FoxImplicits with LazyLogging { identifierA: AnnotationIdentifier, identifierB: AnnotationIdentifier, persistTracing: Boolean - )(implicit request: SecuredRequest[_], ctx: DBAccessContext): Fox[AnnotationSQL] = { + )(implicit request: SecuredRequest[_], ctx: DBAccessContext): Fox[Annotation] = { for { - annotationA: AnnotationSQL <- AnnotationStore.requestAnnotation(identifierA, Some(request.identity)) ?~> "Request Annotation in AnnotationStore failed" - annotationB: AnnotationSQL <- AnnotationStore.requestAnnotation(identifierB, Some(request.identity)) ?~> "Request Annotation in AnnotationStore failed" + annotationA: Annotation <- AnnotationStore.requestAnnotation(identifierA, Some(request.identity)) ?~> "Request Annotation in AnnotationStore failed" + annotationB: Annotation <- AnnotationStore.requestAnnotation(identifierB, Some(request.identity)) ?~> "Request Annotation in AnnotationStore failed" mergedAnnotation <- mergeTwo(annotationA, annotationB, persistTracing) } yield mergedAnnotation } def mergeTwo( - annotationA: AnnotationSQL, - annotationB: AnnotationSQL, - persistTracing: Boolean - )(implicit request: SecuredRequest[_], ctx: DBAccessContext): Fox[AnnotationSQL] = { + annotationA: Annotation, + annotationB: Annotation, + persistTracing: Boolean + )(implicit request: SecuredRequest[_], ctx: DBAccessContext): Fox[Annotation] = { mergeN( ObjectId.generate, persistTracing, @@ -47,15 +47,15 @@ object AnnotationMerger extends FoxImplicits with LazyLogging { _dataSet: ObjectId, _team: ObjectId, typ: AnnotationTypeSQL, - annotations: List[AnnotationSQL] - )(implicit ctx: DBAccessContext): Fox[AnnotationSQL] = { + annotations: List[Annotation] + )(implicit ctx: DBAccessContext): Fox[Annotation] = { if (annotations.isEmpty) Fox.empty else { for { mergedTracingReference <- mergeTracingsOfAnnotations(annotations, _dataSet, persistTracing) } yield { - AnnotationSQL( + Annotation( newId, _dataSet, None, @@ -68,9 +68,9 @@ object AnnotationMerger extends FoxImplicits with LazyLogging { } } - private def mergeTracingsOfAnnotations(annotations: List[AnnotationSQL], dataSetId: ObjectId, persistTracing: Boolean)(implicit ctx: DBAccessContext): Fox[TracingReference] = { + private def mergeTracingsOfAnnotations(annotations: List[Annotation], dataSetId: ObjectId, persistTracing: Boolean)(implicit ctx: DBAccessContext): Fox[TracingReference] = { for { - dataSet <- DataSetSQLDAO.findOne(dataSetId) + dataSet <- DataSetDAO.findOne(dataSetId) dataStoreHandler <- dataSet.dataStoreHandler tracingReference <- dataStoreHandler.mergeSkeletonTracingsByIds(annotations.map(_.tracing), persistTracing) ?~> "Failed to merge skeleton tracings." } yield { diff --git a/app/models/annotation/AnnotationMutations.scala b/app/models/annotation/AnnotationMutations.scala index 2cf2499b8f..2029b71261 100755 --- a/app/models/annotation/AnnotationMutations.scala +++ b/app/models/annotation/AnnotationMutations.scala @@ -7,12 +7,12 @@ import com.scalableminds.util.accesscontext.DBAccessContext import com.scalableminds.util.tools.{BoxImplicits, Fox, FoxImplicits} import com.scalableminds.webknossos.datastore.tracings.TracingType import models.annotation.AnnotationState._ -import models.user.UserSQL +import models.user.User import play.api.libs.concurrent.Execution.Implicits._ -class AnnotationMutations(val annotation: AnnotationSQL) extends BoxImplicits with FoxImplicits { +class AnnotationMutations(val annotation: Annotation) extends BoxImplicits with FoxImplicits { - def finish(user: UserSQL, restrictions: AnnotationRestrictions)(implicit ctx: DBAccessContext): Fox[String] = { + def finish(user: User, restrictions: AnnotationRestrictions)(implicit ctx: DBAccessContext): Fox[String] = { def executeFinish: Fox[String] = { for { _ <- AnnotationService.finish(annotation) @@ -39,25 +39,25 @@ class AnnotationMutations(val annotation: AnnotationSQL) extends BoxImplicits wi } def reopen(implicit ctx: DBAccessContext) = - AnnotationSQLDAO.updateState(annotation._id, AnnotationState.Active) + AnnotationDAO.updateState(annotation._id, AnnotationState.Active) def rename(name: String)(implicit ctx: DBAccessContext) = - AnnotationSQLDAO.updateName(annotation._id, name) + AnnotationDAO.updateName(annotation._id, name) def setDescription(description: String)(implicit ctx: DBAccessContext) = - AnnotationSQLDAO.updateDescription(annotation._id, description) + AnnotationDAO.updateDescription(annotation._id, description) def setIsPublic(isPublic: Boolean)(implicit ctx: DBAccessContext) = - AnnotationSQLDAO.updateIsPublic(annotation._id, isPublic) + AnnotationDAO.updateIsPublic(annotation._id, isPublic) def setTags(tags: List[String])(implicit ctx: DBAccessContext) = - AnnotationSQLDAO.updateTags(annotation._id, tags) + AnnotationDAO.updateTags(annotation._id, tags) def cancel(implicit ctx: DBAccessContext) = - AnnotationSQLDAO.updateState(annotation._id, Cancelled) + AnnotationDAO.updateState(annotation._id, Cancelled) - def transferToUser(user: UserSQL)(implicit ctx: DBAccessContext) = - AnnotationSQLDAO.updateUser(annotation._id, user._id) + def transferToUser(user: User)(implicit ctx: DBAccessContext) = + AnnotationDAO.updateUser(annotation._id, user._id) def resetToBase(implicit ctx: DBAccessContext) = annotation.typ match { case AnnotationTypeSQL.Explorational => @@ -68,7 +68,7 @@ class AnnotationMutations(val annotation: AnnotationSQL) extends BoxImplicits wi annotationBase <- task.annotationBase dataSet <- annotationBase.dataSet newTracingReference <- AnnotationService.tracingFromBase(annotationBase, dataSet) - _ <- AnnotationSQLDAO.updateTracingReference(annotation._id, newTracingReference) + _ <- AnnotationDAO.updateTracingReference(annotation._id, newTracingReference) } yield () case _ if annotation.tracingType != TracingType.skeleton => Fox.failure("annotation.revert.skeletonOnly") diff --git a/app/models/annotation/AnnotationRestrictions.scala b/app/models/annotation/AnnotationRestrictions.scala index 1aae99e6d4..b30140c2f3 100755 --- a/app/models/annotation/AnnotationRestrictions.scala +++ b/app/models/annotation/AnnotationRestrictions.scala @@ -3,7 +3,7 @@ package models.annotation import com.scalableminds.util.accesscontext.GlobalAccessContext import com.scalableminds.util.tools.{Fox, FoxImplicits} import javax.management.relation.Role -import models.user.UserSQL +import models.user.User import play.api.libs.json._ import models.annotation.AnnotationState._ import utils.ObjectId @@ -13,25 +13,25 @@ import ExecutionContext.Implicits.global class AnnotationRestrictions { - def allowAccess(user: Option[UserSQL]): Fox[Boolean] = Fox.successful(false) + def allowAccess(user: Option[User]): Fox[Boolean] = Fox.successful(false) - def allowUpdate(user: Option[UserSQL]): Fox[Boolean] = Fox.successful(false) + def allowUpdate(user: Option[User]): Fox[Boolean] = Fox.successful(false) - def allowFinish(user: Option[UserSQL]): Fox[Boolean] = Fox.successful(false) + def allowFinish(user: Option[User]): Fox[Boolean] = Fox.successful(false) - def allowDownload(user: Option[UserSQL]): Fox[Boolean] = allowAccess(user) + def allowDownload(user: Option[User]): Fox[Boolean] = allowAccess(user) - def allowAccess(user: UserSQL): Fox[Boolean] = allowAccess(Some(user)) + def allowAccess(user: User): Fox[Boolean] = allowAccess(Some(user)) - def allowUpdate(user: UserSQL): Fox[Boolean] = allowUpdate(Some(user)) + def allowUpdate(user: User): Fox[Boolean] = allowUpdate(Some(user)) - def allowFinish(user: UserSQL): Fox[Boolean] = allowFinish(Some(user)) + def allowFinish(user: User): Fox[Boolean] = allowFinish(Some(user)) - def allowDownload(user: UserSQL): Fox[Boolean] = allowDownload(Some(user)) + def allowDownload(user: User): Fox[Boolean] = allowDownload(Some(user)) } object AnnotationRestrictions extends FoxImplicits{ - def writeAsJson(ar: AnnotationRestrictions, u: Option[UserSQL]) : Fox[JsObject] = + def writeAsJson(ar: AnnotationRestrictions, u: Option[User]) : Fox[JsObject] = for { allowAccess <- ar.allowAccess(u) allowUpdate <- ar.allowUpdate(u) @@ -48,9 +48,9 @@ object AnnotationRestrictions extends FoxImplicits{ def restrictEverything = new AnnotationRestrictions() - def defaultAnnotationRestrictions(annotation: AnnotationSQL): AnnotationRestrictions = + def defaultAnnotationRestrictions(annotation: Annotation): AnnotationRestrictions = new AnnotationRestrictions { - override def allowAccess(userOption: Option[UserSQL]) = { + override def allowAccess(userOption: Option[User]) = { if(annotation.isPublic) Fox.successful(true) else (for { @@ -61,14 +61,14 @@ object AnnotationRestrictions extends FoxImplicits{ }).orElse(Fox.successful(false)) } - override def allowUpdate(user: Option[UserSQL]) = { + override def allowUpdate(user: Option[User]) = { Fox.successful(user.exists { user => annotation._user == user._id && !(annotation.state == Finished) }) } - override def allowFinish(user: Option[UserSQL]) = { + override def allowFinish(user: Option[User]) = { (for { u <- option2Fox(user) isTeamManagerOrAdminOfTeam <- u.isTeamManagerOrAdminOf(annotation._team) @@ -80,13 +80,13 @@ object AnnotationRestrictions extends FoxImplicits{ def readonlyAnnotation() = new AnnotationRestrictions { - override def allowAccess(user: Option[UserSQL]) = Fox.successful(true) + override def allowAccess(user: Option[User]) = Fox.successful(true) } def updateableAnnotation() = new AnnotationRestrictions { - override def allowAccess(user: Option[UserSQL]) = Fox.successful(true) - override def allowUpdate(user: Option[UserSQL]) = Fox.successful(true) - override def allowFinish(user: Option[UserSQL]) = Fox.successful(true) + override def allowAccess(user: Option[User]) = Fox.successful(true) + override def allowUpdate(user: Option[User]) = Fox.successful(true) + override def allowFinish(user: Option[User]) = Fox.successful(true) } } diff --git a/app/models/annotation/AnnotationService.scala b/app/models/annotation/AnnotationService.scala index eef63b338f..c8cc9257cb 100755 --- a/app/models/annotation/AnnotationService.scala +++ b/app/models/annotation/AnnotationService.scala @@ -18,9 +18,9 @@ import models.annotation.AnnotationTypeSQL.AnnotationTypeSQL import models.annotation.handler.SavedTracingInformationHandler import models.annotation.nml.NmlWriter import models.binary._ -import models.task.TaskSQL -import models.team.OrganizationSQLDAO -import models.user.UserSQL +import models.task.Task +import models.team.OrganizationDAO +import models.user.User import utils.ObjectId import play.api.i18n.Messages import play.api.Play.current @@ -39,7 +39,7 @@ object AnnotationService with ProtoGeometryImplicits with LazyLogging { - private def selectSuitableTeam(user: UserSQL, dataSet: DataSetSQL)(implicit ctx: DBAccessContext): Fox[ObjectId] = { + private def selectSuitableTeam(user: User, dataSet: DataSet)(implicit ctx: DBAccessContext): Fox[ObjectId] = { (for { userTeamIds <- user.teamIds datasetAllowedTeamIds <- dataSet.allowedTeamIds @@ -50,7 +50,7 @@ object AnnotationService case None => for { _ <- Fox.assertTrue(user.isTeamManagerOrAdminOfOrg(user._organization)) - organizationTeamId <- OrganizationSQLDAO.findOrganizationTeamId(user._organization) + organizationTeamId <- OrganizationDAO.findOrganizationTeamId(user._organization) } yield organizationTeamId } }).flatten @@ -80,24 +80,24 @@ object AnnotationService } def createExplorationalFor( - user: UserSQL, - _dataSet: ObjectId, - tracingType: TracingType.Value, - withFallback: Boolean)(implicit ctx: DBAccessContext): Fox[AnnotationSQL] = { + user: User, + _dataSet: ObjectId, + tracingType: TracingType.Value, + withFallback: Boolean)(implicit ctx: DBAccessContext): Fox[Annotation] = { - def createTracing(dataSet: DataSetSQL, dataSource: DataSource) = tracingType match { + def createTracing(dataSet: DataSet, dataSource: DataSource) = tracingType match { case TracingType.skeleton => dataSet.dataStoreHandler.flatMap(_.saveSkeletonTracing(SkeletonTracingDefaults.createInstance.copy(dataSetName = dataSet.name, editPosition = dataSource.center))) case TracingType.volume => dataSet.dataStoreHandler.flatMap(_.saveVolumeTracing(createVolumeTracing(dataSource, withFallback))) } for { - dataSet <- DataSetSQLDAO.findOne(_dataSet) + dataSet <- DataSetDAO.findOne(_dataSet) dataSource <- dataSet.constructDataSource usableDataSource <- dataSource.toUsable ?~> "DataSet is not imported." tracing <- createTracing(dataSet, usableDataSource) teamId <- selectSuitableTeam(user, dataSet) - annotation = AnnotationSQL( + annotation = Annotation( ObjectId.generate, _dataSet, None, @@ -105,35 +105,35 @@ object AnnotationService user._id, tracing ) - _ <- AnnotationSQLDAO.insertOne(annotation) + _ <- AnnotationDAO.insertOne(annotation) } yield { annotation } } - def finish(annotation: AnnotationSQL)(implicit ctx: DBAccessContext) = { + def finish(annotation: Annotation)(implicit ctx: DBAccessContext) = { // WARNING: needs to be repeatable, might be called multiple times for an annotation - AnnotationSQLDAO.updateState(annotation._id, AnnotationState.Finished) + AnnotationDAO.updateState(annotation._id, AnnotationState.Finished) } - def baseFor(taskId: ObjectId)(implicit ctx: DBAccessContext): Fox[AnnotationSQL] = + def baseFor(taskId: ObjectId)(implicit ctx: DBAccessContext): Fox[Annotation] = (for { - list <- AnnotationSQLDAO.findAllByTaskIdAndType(taskId, AnnotationTypeSQL.TracingBase) + list <- AnnotationDAO.findAllByTaskIdAndType(taskId, AnnotationTypeSQL.TracingBase) } yield list.headOption.toFox).flatten def annotationsFor(taskId: ObjectId)(implicit ctx: DBAccessContext) = - AnnotationSQLDAO.findAllByTaskIdAndType(taskId, AnnotationTypeSQL.Task) + AnnotationDAO.findAllByTaskIdAndType(taskId, AnnotationTypeSQL.Task) def countActiveAnnotationsFor(taskId: ObjectId)(implicit ctx: DBAccessContext) = - AnnotationSQLDAO.countActiveByTask(taskId, AnnotationTypeSQL.Task) + AnnotationDAO.countActiveByTask(taskId, AnnotationTypeSQL.Task) - def countOpenNonAdminTasks(user: UserSQL)(implicit ctx: DBAccessContext) = + def countOpenNonAdminTasks(user: User)(implicit ctx: DBAccessContext) = for { teamManagerTeamIds <- user.teamManagerTeamIds - result <- AnnotationSQLDAO.countActiveAnnotationsFor(user._id, AnnotationTypeSQL.Task, teamManagerTeamIds) + result <- AnnotationDAO.countActiveAnnotationsFor(user._id, AnnotationTypeSQL.Task, teamManagerTeamIds) } yield result - def tracingFromBase(annotationBase: AnnotationSQL, dataSet: DataSetSQL)(implicit ctx: DBAccessContext): Fox[TracingReference] = { + def tracingFromBase(annotationBase: Annotation, dataSet: DataSet)(implicit ctx: DBAccessContext): Fox[TracingReference] = { for { dataSource <- bool2Fox(dataSet.isUsable) ?~> Messages("dataSet.notImported", dataSet.name) dataStoreHandler <- dataSet.dataStoreHandler @@ -141,10 +141,10 @@ object AnnotationService } yield newTracingReference } - def createAnnotationFor(user: UserSQL, task: TaskSQL, initializingAnnotationId: ObjectId)(implicit messages: Messages, ctx: DBAccessContext): Fox[AnnotationSQL] = { - def useAsTemplateAndInsert(annotation: AnnotationSQL) = { + def createAnnotationFor(user: User, task: Task, initializingAnnotationId: ObjectId)(implicit messages: Messages, ctx: DBAccessContext): Fox[Annotation] = { + def useAsTemplateAndInsert(annotation: Annotation) = { for { - dataSetName <- DataSetSQLDAO.getNameById(annotation._dataSet)(GlobalAccessContext) ?~> "dataSet.notFound" + dataSetName <- DataSetDAO.getNameById(annotation._dataSet)(GlobalAccessContext) ?~> "dataSet.notFound" dataSet <- annotation.dataSet ?~> ("Could not access DataSet " + dataSetName + ". Does your team have access?") newTracing <- tracingFromBase(annotation, dataSet) ?~> "Failed to use annotation base as template." newAnnotation = annotation.copy( @@ -155,7 +155,7 @@ object AnnotationService typ = AnnotationTypeSQL.Task, created = System.currentTimeMillis, modified = System.currentTimeMillis) - _ <- AnnotationSQLDAO.updateInitialized(newAnnotation) + _ <- AnnotationDAO.updateInitialized(newAnnotation) } yield { newAnnotation } @@ -190,19 +190,19 @@ object AnnotationService trees = Seq(initialTree)) } - def abortInitializedAnnotationOnFailure(initializingAnnotationId: ObjectId, insertedAnnotationBox: Box[AnnotationSQL]) = { + def abortInitializedAnnotationOnFailure(initializingAnnotationId: ObjectId, insertedAnnotationBox: Box[Annotation]) = { insertedAnnotationBox match { case Full(_) => Fox.successful(()) - case _ => AnnotationSQLDAO.abortInitializingAnnotation(initializingAnnotationId) + case _ => AnnotationDAO.abortInitializingAnnotation(initializingAnnotationId) } } def createAnnotationBase( - taskFox: Fox[TaskSQL], - userId: ObjectId, - tracingReferenceBox: Box[TracingReference], - dataSetId: ObjectId, - description: Option[String] + taskFox: Fox[Task], + userId: ObjectId, + tracingReferenceBox: Box[TracingReference], + dataSetId: ObjectId, + description: Option[String] )(implicit ctx: DBAccessContext) = { for { @@ -210,7 +210,7 @@ object AnnotationService taskType <- task.taskType tracingReference <- tracingReferenceBox.toFox project <- task.project - annotationBase = AnnotationSQL( + annotationBase = Annotation( ObjectId.generate, dataSetId, Some(task._id), @@ -219,21 +219,21 @@ object AnnotationService tracingReference, description.getOrElse(""), typ = AnnotationTypeSQL.TracingBase) - _ <- AnnotationSQLDAO.insertOne(annotationBase) + _ <- AnnotationDAO.insertOne(annotationBase) } yield true } def createFrom( - user: UserSQL, - dataSet: DataSetSQL, - tracingReference: TracingReference, - annotationType: AnnotationTypeSQL, - name: Option[String], - description: String)(implicit messages: Messages, ctx: DBAccessContext): Fox[AnnotationSQL] = { + user: User, + dataSet: DataSet, + tracingReference: TracingReference, + annotationType: AnnotationTypeSQL, + name: Option[String], + description: String)(implicit messages: Messages, ctx: DBAccessContext): Fox[Annotation] = { for { teamId <- selectSuitableTeam(user, dataSet) - annotation = AnnotationSQL( + annotation = Annotation( ObjectId.generate, dataSet._id, None, @@ -243,11 +243,11 @@ object AnnotationService description, name = name.getOrElse(""), typ = annotationType) - _ <- AnnotationSQLDAO.insertOne(annotation) + _ <- AnnotationDAO.insertOne(annotation) } yield annotation } - def zipAnnotations(annotations: List[AnnotationSQL], zipFileName: String)(implicit messages: Messages, ctx: DBAccessContext): Fox[TemporaryFile] = { + def zipAnnotations(annotations: List[Annotation], zipFileName: String)(implicit messages: Messages, ctx: DBAccessContext): Fox[TemporaryFile] = { for { tracingsNamesAndScalesAsTuples <- getTracingsScalesAndNamesFor(annotations) tracingsAndNamesFlattened = flattenTupledLists(tracingsNamesAndScalesAsTuples) @@ -264,11 +264,11 @@ object AnnotationService ((l1, l2, l3).zipped.toList, l4).zipped.toList.map( tuple => (tuple._1._1, tuple._1._2, tuple._1._3, tuple._2)) } - private def getTracingsScalesAndNamesFor(annotations: List[AnnotationSQL])(implicit ctx: DBAccessContext): Fox[List[(List[SkeletonTracing], List[String], List[Option[Scale]], List[AnnotationSQL])]] = { + private def getTracingsScalesAndNamesFor(annotations: List[Annotation])(implicit ctx: DBAccessContext): Fox[List[(List[SkeletonTracing], List[String], List[Option[Scale]], List[Annotation])]] = { def getTracings(dataSetId: ObjectId, tracingReferences: List[TracingReference]) = { for { - dataSet <- DataSetSQLDAO.findOne(dataSetId) + dataSet <- DataSetDAO.findOne(dataSetId) dataStoreHandler <- dataSet.dataStoreHandler tracingContainers <- Fox.serialCombined(tracingReferences.grouped(1000).toList)(dataStoreHandler.getSkeletonTracings) } yield tracingContainers.flatMap(_.tracings) @@ -276,13 +276,13 @@ object AnnotationService def getDatasetScale(dataSetId: ObjectId) = { for { - dataSet <- DataSetSQLDAO.findOne(dataSetId) + dataSet <- DataSetDAO.findOne(dataSetId) } yield dataSet.scale } - def getNames(annotations: List[AnnotationSQL]) = Fox.combined(annotations.map(a => SavedTracingInformationHandler.nameForAnnotation(a).toFox)) + def getNames(annotations: List[Annotation]) = Fox.combined(annotations.map(a => SavedTracingInformationHandler.nameForAnnotation(a).toFox)) - val annotationsGrouped: Map[ObjectId, List[AnnotationSQL]] = annotations.groupBy(_._dataSet) + val annotationsGrouped: Map[ObjectId, List[Annotation]] = annotations.groupBy(_._dataSet) val tracings = annotationsGrouped.map { case (dataSetId, annotations) => { for { diff --git a/app/models/annotation/AnnotationStore.scala b/app/models/annotation/AnnotationStore.scala index 8fbeef319e..d293916de3 100755 --- a/app/models/annotation/AnnotationStore.scala +++ b/app/models/annotation/AnnotationStore.scala @@ -4,7 +4,7 @@ import com.scalableminds.util.accesscontext.DBAccessContext import com.scalableminds.util.tools.Fox import com.typesafe.scalalogging.LazyLogging import models.annotation.handler.AnnotationInformationHandler -import models.user.UserSQL +import models.user.User import net.liftweb.common.{Box, Empty, Failure, Full} import play.api.libs.concurrent.Execution.Implicits._ @@ -14,9 +14,9 @@ object AnnotationStore extends LazyLogging { private val cacheTimeout = 5 minutes - case class StoredResult(result: Fox[AnnotationSQL], timestamp: Long = System.currentTimeMillis) + case class StoredResult(result: Fox[Annotation], timestamp: Long = System.currentTimeMillis) - def requestAnnotation(id: AnnotationIdentifier, user: Option[UserSQL])(implicit ctx: DBAccessContext) = { + def requestAnnotation(id: AnnotationIdentifier, user: Option[User])(implicit ctx: DBAccessContext) = { requestFromCache(id) .getOrElse(requestFromHandler(id, user)) .futureBox @@ -28,7 +28,7 @@ object AnnotationStore extends LazyLogging { } } - private def requestFromCache(id: AnnotationIdentifier): Option[Fox[AnnotationSQL]] = { + private def requestFromCache(id: AnnotationIdentifier): Option[Fox[Annotation]] = { val handler = AnnotationInformationHandler.informationHandlers(id.annotationType) if (handler.cache) { val cached = getFromCache(id) @@ -37,7 +37,7 @@ object AnnotationStore extends LazyLogging { None } - private def requestFromHandler(id: AnnotationIdentifier, user: Option[UserSQL])(implicit ctx: DBAccessContext) = { + private def requestFromHandler(id: AnnotationIdentifier, user: Option[User])(implicit ctx: DBAccessContext) = { val handler = AnnotationInformationHandler.informationHandlers(id.annotationType) for { annotation <- handler.provideAnnotation(id.identifier, user) @@ -49,15 +49,15 @@ object AnnotationStore extends LazyLogging { } } - private def storeInCache(id: AnnotationIdentifier, annotation: AnnotationSQL) = { + private def storeInCache(id: AnnotationIdentifier, annotation: Annotation) = { TemporaryAnnotationStore.insert(id.toUniqueString, annotation, Some(cacheTimeout)) } - private def getFromCache(annotationId: AnnotationIdentifier): Option[Fox[AnnotationSQL]] = { + private def getFromCache(annotationId: AnnotationIdentifier): Option[Fox[Annotation]] = { TemporaryAnnotationStore.find(annotationId.toUniqueString).map(Fox.successful(_)) } - def findCachedByTracingId(tracingId: String): Box[AnnotationSQL] = { + def findCachedByTracingId(tracingId: String): Box[Annotation] = { val annotationOpt = TemporaryAnnotationStore.findAll.find(a => a.tracing.id == tracingId) annotationOpt match { case Some(annotation) => Full(annotation) diff --git a/app/models/annotation/TemporaryAnnotationStore.scala b/app/models/annotation/TemporaryAnnotationStore.scala index d2c418caf0..f865d978bc 100644 --- a/app/models/annotation/TemporaryAnnotationStore.scala +++ b/app/models/annotation/TemporaryAnnotationStore.scala @@ -5,6 +5,6 @@ package models.annotation import com.scalableminds.webknossos.datastore.storage.TemporaryStore -object TemporaryAnnotationStore extends TemporaryStore[String, AnnotationSQL] { +object TemporaryAnnotationStore extends TemporaryStore[String, Annotation] { val system = akka.actor.ActorSystem("system") } diff --git a/app/models/annotation/handler/AnnotationInformationHandler.scala b/app/models/annotation/handler/AnnotationInformationHandler.scala index 95b8c90fab..1470c4ec89 100755 --- a/app/models/annotation/handler/AnnotationInformationHandler.scala +++ b/app/models/annotation/handler/AnnotationInformationHandler.scala @@ -4,7 +4,7 @@ import com.scalableminds.util.accesscontext.DBAccessContext import com.scalableminds.util.tools.{Fox, FoxImplicits} import models.annotation.AnnotationTypeSQL.AnnotationTypeSQL import models.annotation._ -import models.user.UserSQL +import models.user.User import play.api.libs.concurrent.Execution.Implicits._ import utils.ObjectId @@ -20,16 +20,16 @@ trait AnnotationInformationHandler extends FoxImplicits { def cache: Boolean = true - def provideAnnotation(identifier: ObjectId, user: Option[UserSQL])(implicit ctx: DBAccessContext): Fox[AnnotationSQL] + def provideAnnotation(identifier: ObjectId, user: Option[User])(implicit ctx: DBAccessContext): Fox[Annotation] - def nameForAnnotation(t: AnnotationSQL)(implicit ctx: DBAccessContext): Fox[String] = { + def nameForAnnotation(t: Annotation)(implicit ctx: DBAccessContext): Fox[String] = { Fox.successful(t.id) } def restrictionsFor(identifier: ObjectId)(implicit ctx: DBAccessContext): Fox[AnnotationRestrictions] - def assertAllOnSameDataset(annotations: List[AnnotationSQL]): Fox[Boolean] = { - def allOnSameDatasetIter(annotations: List[AnnotationSQL], _dataSet: ObjectId): Boolean = + def assertAllOnSameDataset(annotations: List[Annotation]): Fox[Boolean] = { + def allOnSameDatasetIter(annotations: List[Annotation], _dataSet: ObjectId): Boolean = annotations match { case List() => true case head :: tail => head._dataSet == _dataSet && allOnSameDatasetIter(tail, _dataSet) diff --git a/app/models/annotation/handler/ProjectInformationHandler.scala b/app/models/annotation/handler/ProjectInformationHandler.scala index b26018a9ff..8912a95983 100755 --- a/app/models/annotation/handler/ProjectInformationHandler.scala +++ b/app/models/annotation/handler/ProjectInformationHandler.scala @@ -3,19 +3,19 @@ package models.annotation.handler import com.scalableminds.util.accesscontext.DBAccessContext import com.scalableminds.util.tools.{Fox, FoxImplicits} import models.annotation._ -import models.project.ProjectSQLDAO -import models.user.UserSQL +import models.project.ProjectDAO +import models.user.User import scala.concurrent.ExecutionContext.Implicits.global import utils.ObjectId object ProjectInformationHandler extends AnnotationInformationHandler with FoxImplicits { - override def provideAnnotation(projectId: ObjectId, userOpt: Option[UserSQL])(implicit ctx: DBAccessContext): Fox[AnnotationSQL] = + override def provideAnnotation(projectId: ObjectId, userOpt: Option[User])(implicit ctx: DBAccessContext): Fox[Annotation] = { for { - project <- ProjectSQLDAO.findOne(projectId) ?~> "project.notFound" - annotations <- AnnotationSQLDAO.findAllFinishedForProject(project._id) + project <- ProjectDAO.findOne(projectId) ?~> "project.notFound" + annotations <- AnnotationDAO.findAllFinishedForProject(project._id) _ <- assertAllOnSameDataset(annotations) _ <- assertNonEmpty(annotations) ?~> "project.noAnnotations" user <- userOpt ?~> "user.notAuthorised" @@ -28,10 +28,10 @@ object ProjectInformationHandler extends AnnotationInformationHandler with FoxIm override def restrictionsFor(projectId: ObjectId)(implicit ctx: DBAccessContext) = for { - project <- ProjectSQLDAO.findOne(projectId) + project <- ProjectDAO.findOne(projectId) } yield { new AnnotationRestrictions { - override def allowAccess(userOption: Option[UserSQL]): Fox[Boolean] = + override def allowAccess(userOption: Option[User]): Fox[Boolean] = (for { user <- userOption.toFox allowed <- user.isTeamManagerOrAdminOf(project._team) diff --git a/app/models/annotation/handler/SavedTracingInformationHandler.scala b/app/models/annotation/handler/SavedTracingInformationHandler.scala index b877fe8c12..0a7cca6ef7 100755 --- a/app/models/annotation/handler/SavedTracingInformationHandler.scala +++ b/app/models/annotation/handler/SavedTracingInformationHandler.scala @@ -4,7 +4,7 @@ import com.scalableminds.util.accesscontext.DBAccessContext import com.scalableminds.util.tools.TextUtils._ import com.scalableminds.util.tools.{Fox, FoxImplicits} import models.annotation._ -import models.user.UserSQL +import models.user.User import play.api.libs.concurrent.Execution.Implicits._ import utils.ObjectId @@ -12,7 +12,7 @@ object SavedTracingInformationHandler extends AnnotationInformationHandler with override val cache = false - override def nameForAnnotation(annotation: AnnotationSQL)(implicit ctx: DBAccessContext): Fox[String] = + override def nameForAnnotation(annotation: Annotation)(implicit ctx: DBAccessContext): Fox[String] = for { userName <- annotation.user.map(_.abreviatedName).getOrElse("") dataSetName <- annotation.dataSet.map(_.name) @@ -22,8 +22,8 @@ object SavedTracingInformationHandler extends AnnotationInformationHandler with normalize(s"${dataSetName}__${task}__${userName}__${id}") } - def provideAnnotation(annotationId: ObjectId, userOpt: Option[UserSQL])(implicit ctx: DBAccessContext): Fox[AnnotationSQL] = - AnnotationSQLDAO.findOne(annotationId) ?~> "annotation.notFound" + def provideAnnotation(annotationId: ObjectId, userOpt: Option[User])(implicit ctx: DBAccessContext): Fox[Annotation] = + AnnotationDAO.findOne(annotationId) ?~> "annotation.notFound" def restrictionsFor(identifier: ObjectId)(implicit ctx: DBAccessContext) = { for { diff --git a/app/models/annotation/handler/TaskInformationHandler.scala b/app/models/annotation/handler/TaskInformationHandler.scala index ad4102e542..ec78ab17b3 100755 --- a/app/models/annotation/handler/TaskInformationHandler.scala +++ b/app/models/annotation/handler/TaskInformationHandler.scala @@ -3,24 +3,24 @@ package models.annotation.handler import com.scalableminds.util.accesscontext.DBAccessContext import com.scalableminds.util.tools.{Fox, FoxImplicits} import models.annotation._ -import models.task.TaskSQLDAO -import models.user.UserSQL +import models.task.TaskDAO +import models.user.User import play.api.libs.concurrent.Execution.Implicits._ import models.annotation.AnnotationState._ -import models.project.ProjectSQLDAO +import models.project.ProjectDAO import utils.ObjectId object TaskInformationHandler extends AnnotationInformationHandler with FoxImplicits { - override def provideAnnotation(taskId: ObjectId, userOpt: Option[UserSQL])(implicit ctx: DBAccessContext): Fox[AnnotationSQL] = + override def provideAnnotation(taskId: ObjectId, userOpt: Option[User])(implicit ctx: DBAccessContext): Fox[Annotation] = for { - task <- TaskSQLDAO.findOne(taskId) ?~> "task.notFound" + task <- TaskDAO.findOne(taskId) ?~> "task.notFound" annotations <- task.annotations finishedAnnotations = annotations.filter(_.state == Finished) _ <- assertAllOnSameDataset(finishedAnnotations) _ <- assertNonEmpty(finishedAnnotations) ?~> "task.noAnnotations" user <- userOpt ?~> "user.notAuthorised" - project <- ProjectSQLDAO.findOne(task._project) + project <- ProjectDAO.findOne(task._project) _dataSet = finishedAnnotations.head._dataSet mergedAnnotation <- AnnotationMerger.mergeN(task._id, persistTracing=false, user._id, _dataSet, project._team, AnnotationTypeSQL.CompoundTask, finishedAnnotations) ?~> "annotation.merge.failed.compound" @@ -28,11 +28,11 @@ object TaskInformationHandler extends AnnotationInformationHandler with FoxImpli def restrictionsFor(taskId: ObjectId)(implicit ctx: DBAccessContext) = for { - task <- TaskSQLDAO.findOne(taskId) ?~> "task.notFound" - project <- ProjectSQLDAO.findOne(task._project) + task <- TaskDAO.findOne(taskId) ?~> "task.notFound" + project <- ProjectDAO.findOne(task._project) } yield { new AnnotationRestrictions { - override def allowAccess(userOption: Option[UserSQL]): Fox[Boolean] = + override def allowAccess(userOption: Option[User]): Fox[Boolean] = (for { user <- userOption.toFox allowed <- user.isTeamManagerOrAdminOf(project._team) diff --git a/app/models/annotation/handler/TaskTypeInformationHandler.scala b/app/models/annotation/handler/TaskTypeInformationHandler.scala index 3c8ad015ac..aef4235124 100755 --- a/app/models/annotation/handler/TaskTypeInformationHandler.scala +++ b/app/models/annotation/handler/TaskTypeInformationHandler.scala @@ -3,8 +3,8 @@ package models.annotation.handler import com.scalableminds.util.accesscontext.DBAccessContext import com.scalableminds.util.tools.{Fox, FoxImplicits} import models.annotation._ -import models.task.{TaskSQLDAO, TaskTypeSQLDAO} -import models.user.UserSQL +import models.task.{TaskDAO, TaskTypeDAO} +import models.user.User import play.api.libs.concurrent.Execution.Implicits._ import models.annotation.AnnotationState._ import utils.ObjectId @@ -12,10 +12,10 @@ import utils.ObjectId object TaskTypeInformationHandler extends AnnotationInformationHandler with FoxImplicits { - override def provideAnnotation(taskTypeId: ObjectId, userOpt: Option[UserSQL])(implicit ctx: DBAccessContext): Fox[AnnotationSQL] = + override def provideAnnotation(taskTypeId: ObjectId, userOpt: Option[User])(implicit ctx: DBAccessContext): Fox[Annotation] = for { - taskType <- TaskTypeSQLDAO.findOne(taskTypeId) ?~> "taskType.notFound" - tasks <- TaskSQLDAO.findAllByTaskType(taskType._id) + taskType <- TaskTypeDAO.findOne(taskTypeId) ?~> "taskType.notFound" + tasks <- TaskDAO.findAllByTaskType(taskType._id) annotations <- Fox.serialCombined(tasks)(_.annotations).map(_.flatten).toFox finishedAnnotations = annotations.filter(_.state == Finished) _ <- assertAllOnSameDataset(finishedAnnotations) @@ -28,10 +28,10 @@ object TaskTypeInformationHandler extends AnnotationInformationHandler with FoxI override def restrictionsFor(taskTypeId: ObjectId)(implicit ctx: DBAccessContext) = for { - taskType <- TaskTypeSQLDAO.findOne(taskTypeId) ?~> "taskType.notFound" + taskType <- TaskTypeDAO.findOne(taskTypeId) ?~> "taskType.notFound" } yield { new AnnotationRestrictions { - override def allowAccess(userOption: Option[UserSQL]): Fox[Boolean] = + override def allowAccess(userOption: Option[User]): Fox[Boolean] = (for { user <- userOption.toFox allowed <- user.isTeamManagerOrAdminOf(taskType._team) diff --git a/app/models/annotation/nml/NmlWriter.scala b/app/models/annotation/nml/NmlWriter.scala index b38b04a578..ab902dac5b 100644 --- a/app/models/annotation/nml/NmlWriter.scala +++ b/app/models/annotation/nml/NmlWriter.scala @@ -10,7 +10,7 @@ import com.scalableminds.util.xml.Xml import com.scalableminds.webknossos.datastore.SkeletonTracing._ import com.scalableminds.webknossos.datastore.VolumeTracing.VolumeTracing import com.sun.xml.txw2.output.IndentingXMLStreamWriter -import models.annotation.AnnotationSQL +import models.annotation.Annotation import net.liftweb.common.Full import org.joda.time.DateTime import play.api.libs.concurrent.Execution.Implicits._ @@ -21,7 +21,7 @@ import scala.concurrent.Future object NmlWriter extends FoxImplicits { private lazy val outputService = XMLOutputFactory.newInstance() - def toNmlStream(tracing: Either[SkeletonTracing, VolumeTracing], annotation: AnnotationSQL, scale: Option[Scale]) = Enumerator.outputStream { os => + def toNmlStream(tracing: Either[SkeletonTracing, VolumeTracing], annotation: Annotation, scale: Option[Scale]) = Enumerator.outputStream { os => implicit val writer = new IndentingXMLStreamWriter(outputService.createXMLStreamWriter(os)) for { @@ -32,7 +32,7 @@ object NmlWriter extends FoxImplicits { } } - def toNml(tracing: Either[SkeletonTracing, VolumeTracing], annotation: AnnotationSQL, scale: Option[Scale])(implicit writer: XMLStreamWriter): Fox[Unit] = { + def toNml(tracing: Either[SkeletonTracing, VolumeTracing], annotation: Annotation, scale: Option[Scale])(implicit writer: XMLStreamWriter): Fox[Unit] = { tracing match { case Right(volumeTracing) => { for { @@ -51,7 +51,7 @@ object NmlWriter extends FoxImplicits { } } - def writeVolumeThings(annotation: AnnotationSQL, volumeTracing: VolumeTracing, scale: Option[Scale])(implicit writer: XMLStreamWriter): Fox[Unit] = { + def writeVolumeThings(annotation: Annotation, volumeTracing: VolumeTracing, scale: Option[Scale])(implicit writer: XMLStreamWriter): Fox[Unit] = { for { _ <- writeMetaData(annotation) _ = Xml.withinElementSync("parameters")(writeParametersAsXml(volumeTracing, annotation.description, scale)) @@ -61,7 +61,7 @@ object NmlWriter extends FoxImplicits { } yield () } - def writeSkeletonThings(annotation: AnnotationSQL, skeletonTracing: SkeletonTracing, scale: Option[Scale])(implicit writer: XMLStreamWriter): Fox[Unit] = { + def writeSkeletonThings(annotation: Annotation, skeletonTracing: SkeletonTracing, scale: Option[Scale])(implicit writer: XMLStreamWriter): Fox[Unit] = { for { _ <- writeMetaData(annotation) _ = Xml.withinElementSync("parameters")(writeParametersAsXml(skeletonTracing, annotation.description, scale)) @@ -236,7 +236,7 @@ object NmlWriter extends FoxImplicits { } } - def writeMetaData(annotation: AnnotationSQL)(implicit writer: XMLStreamWriter): Fox[Unit] = { + def writeMetaData(annotation: Annotation)(implicit writer: XMLStreamWriter): Fox[Unit] = { Xml.withinElementSync("meta") { writer.writeAttribute("name", "writer") writer.writeAttribute("content", "NmlWriter.scala") @@ -259,7 +259,7 @@ object NmlWriter extends FoxImplicits { } yield () } - def writeUser(annotation: AnnotationSQL)(implicit writer: XMLStreamWriter): Future[Unit] = { + def writeUser(annotation: Annotation)(implicit writer: XMLStreamWriter): Future[Unit] = { for { userBox <- annotation.user.futureBox } yield { @@ -273,7 +273,7 @@ object NmlWriter extends FoxImplicits { } } - def writeTask(annotation: AnnotationSQL)(implicit writer: XMLStreamWriter): Future[Unit] = { + def writeTask(annotation: Annotation)(implicit writer: XMLStreamWriter): Future[Unit] = { for { taskBox <- annotation.task.futureBox } yield { diff --git a/app/models/basics/Implicits.scala b/app/models/basics/Implicits.scala index 79a71dfa71..d67478b02d 100755 --- a/app/models/basics/Implicits.scala +++ b/app/models/basics/Implicits.scala @@ -1,7 +1,7 @@ package models.basics import com.scalableminds.util.accesscontext.{AuthorizedAccessContext, DBAccessContext} -import models.user.UserSQL +import models.user.User import oxalis.security.WebknossosSilhouette.{SecuredRequest, UserAwareAction, UserAwareRequest} import scala.language.implicitConversions @@ -25,7 +25,7 @@ trait Implicits { UserAwareRequest[B](Some(user), Some(authenticator), initialRequest) } - implicit def userToDBAccess(user: UserSQL): DBAccessContext = { + implicit def userToDBAccess(user: User): DBAccessContext = { AuthorizedAccessContext(user) } } diff --git a/app/models/binary/DataSet.scala b/app/models/binary/DataSet.scala index 7cc2266f49..95af1c4ce8 100755 --- a/app/models/binary/DataSet.scala +++ b/app/models/binary/DataSet.scala @@ -9,7 +9,7 @@ import com.scalableminds.webknossos.datastore.models.datasource.{AbstractDataLay import com.scalableminds.webknossos.schema.Tables._ import models.configuration.DataSetConfiguration import models.team._ -import models.user.UserSQL +import models.user.User import net.liftweb.common.Full import play.api.Play.current import play.api.i18n.Messages @@ -23,7 +23,7 @@ import slick.lifted.Rep import utils.{ObjectId, SQLDAO, SimpleSQLDAO} -case class DataSetSQL( +case class DataSet( _id: ObjectId, _dataStore: String, _organization: ObjectId, @@ -42,19 +42,19 @@ case class DataSetSQL( ) extends FoxImplicits { def getDataLayerByName(dataLayerName: String)(implicit ctx: DBAccessContext): Fox[DataLayer] = - DataSetDataLayerSQLDAO.findOneByNameForDataSet(dataLayerName, _id) + DataSetDataLayerDAO.findOneByNameForDataSet(dataLayerName, _id) def getLogoUrl: Fox[String] = logoUrl match { case Some(url) => Fox.successful(url) - case None => OrganizationSQLDAO.findOne(_organization)(GlobalAccessContext).map(_.logoUrl) + case None => OrganizationDAO.findOne(_organization)(GlobalAccessContext).map(_.logoUrl) } - def organization: Fox[OrganizationSQL] = - OrganizationSQLDAO.findOne(_organization)(GlobalAccessContext) ?~> Messages("organization.notFound") + def organization: Fox[Organization] = + OrganizationDAO.findOne(_organization)(GlobalAccessContext) ?~> Messages("organization.notFound") - def dataStore: Fox[DataStoreSQL] = - DataStoreSQLDAO.findOneByName(_dataStore.trim)(GlobalAccessContext) ?~> Messages("datastore.notFound") + def dataStore: Fox[DataStore] = + DataStoreDAO.findOneByName(_dataStore.trim)(GlobalAccessContext) ?~> Messages("datastore.notFound") def dataStoreInfo: Fox[DataStoreInfo] = for { @@ -73,7 +73,7 @@ case class DataSetSQL( def urlEncodedName: String = UriEncoding.encodePathSegment(name, "UTF-8") - def isEditableBy(userOpt: Option[UserSQL])(implicit ctx: DBAccessContext): Fox[Boolean] = { + def isEditableBy(userOpt: Option[User])(implicit ctx: DBAccessContext): Fox[Boolean] = { userOpt match { case Some(user) => for { @@ -83,22 +83,22 @@ case class DataSetSQL( } } - def isEditableBy(user: UserSQL)(implicit ctx: DBAccessContext): Fox[Boolean] = + def isEditableBy(user: User)(implicit ctx: DBAccessContext): Fox[Boolean] = isEditableBy(Some(user)) def allowedTeamIds = - DataSetAllowedTeamsSQLDAO.findAllForDataSet(_id)(GlobalAccessContext) ?~> Messages("allowedTeams.notFound") + DataSetAllowedTeamsDAO.findAllForDataSet(_id)(GlobalAccessContext) ?~> Messages("allowedTeams.notFound") def allowedTeams = for { allowedTeamIds <- allowedTeamIds - allowedTeams <- Fox.combined(allowedTeamIds.map(TeamSQLDAO.findOne(_)(GlobalAccessContext))) + allowedTeams <- Fox.combined(allowedTeamIds.map(TeamDAO.findOne(_)(GlobalAccessContext))) } yield allowedTeams def constructDataSource(implicit ctx: DBAccessContext): Fox[InboxDataSource] = { for { organization <- organization - dataLayersBox <- (DataSetDataLayerSQLDAO.findAllForDataSet(_id) ?~> "could not find data layers").futureBox + dataLayersBox <- (DataSetDataLayerDAO.findAllForDataSet(_id) ?~> "could not find data layers").futureBox dataSourceId = DataSourceId(name, organization.name) } yield { dataLayersBox match { @@ -112,7 +112,7 @@ case class DataSetSQL( } } - def publicWrites(user: Option[UserSQL]): Fox[JsObject] = { + def publicWrites(user: Option[User]): Fox[JsObject] = { implicit val ctx = GlobalAccessContext for { teams <- allowedTeams @@ -139,7 +139,7 @@ case class DataSetSQL( } } -object DataSetSQLDAO extends SQLDAO[DataSetSQL, DatasetsRow, Datasets] { +object DataSetDAO extends SQLDAO[DataSet, DatasetsRow, Datasets] { val collection = Datasets def idColumn(x: Datasets): Rep[String] = x._Id @@ -156,12 +156,12 @@ object DataSetSQLDAO extends SQLDAO[DataSetSQL, DatasetsRow, Datasets] { private def writeScaleLiteral(scale: Scale): String = writeStructTuple(List(scale.x, scale.y, scale.z).map(_.toString)) - def parse(r: DatasetsRow): Fox[DataSetSQL] = { + def parse(r: DatasetsRow): Fox[DataSet] = { for { scale <- parseScaleOpt(r.scale) defaultConfigurationOpt <- Fox.runOptional(r.defaultconfiguration)(JsonHelper.parseJsonToFox[DataSetConfiguration](_)) } yield { - DataSetSQL( + DataSet( ObjectId(r._Id), r._Datastore.trim, ObjectId(r._Organization), @@ -191,7 +191,7 @@ object DataSetSQLDAO extends SQLDAO[DataSetSQL, DatasetsRow, Datasets] { or ('${requestingUserId.id}' in (select _user from webknossos.user_team_roles where isTeammanager) and _organization in (select _organization from webknossos.users_ where _id = '${requestingUserId.id}'))""" - override def findOne(id: ObjectId)(implicit ctx: DBAccessContext): Fox[DataSetSQL] = + override def findOne(id: ObjectId)(implicit ctx: DBAccessContext): Fox[DataSet] = for { accessQuery <- readAccessQuery rList <- run(sql"select #${columns} from #${existingCollectionName} where _id = ${id.id} and #${accessQuery}".as[DatasetsRow]) @@ -199,7 +199,7 @@ object DataSetSQLDAO extends SQLDAO[DataSetSQL, DatasetsRow, Datasets] { parsed <- parse(r) ?~> ("SQLDAO Error: Could not parse database row for object " + id + " in " + collectionName) } yield parsed - override def findAll(implicit ctx: DBAccessContext): Fox[List[DataSetSQL]] = { + override def findAll(implicit ctx: DBAccessContext): Fox[List[DataSet]] = { for { accessQuery <- readAccessQuery r <- run(sql"select #${columns} from #${existingCollectionName} where #${accessQuery}".as[DatasetsRow]) @@ -207,7 +207,7 @@ object DataSetSQLDAO extends SQLDAO[DataSetSQL, DatasetsRow, Datasets] { } yield parsed } - def findOneByName(name: String)(implicit ctx: DBAccessContext): Fox[DataSetSQL] = + def findOneByName(name: String)(implicit ctx: DBAccessContext): Fox[DataSet] = for { accessQuery <- readAccessQuery rList <- run(sql"select #${columns} from #${existingCollectionName} where name = ${name} and #${accessQuery}".as[DatasetsRow]) @@ -263,7 +263,7 @@ object DataSetSQLDAO extends SQLDAO[DataSetSQL, DatasetsRow, Datasets] { } yield () } - def insertOne(d: DataSetSQL)(implicit ctx: DBAccessContext): Fox[Unit] = { + def insertOne(d: DataSet)(implicit ctx: DBAccessContext): Fox[Unit] = { val defaultConfiguration: Option[String] = d.defaultConfiguration.map(c => Json.toJson(c.configuration).toString) for { _ <- run( @@ -278,7 +278,7 @@ object DataSetSQLDAO extends SQLDAO[DataSetSQL, DatasetsRow, Datasets] { for { old <- findOneByName(name) - organization <- OrganizationSQLDAO.findOneByName(source.id.team) + organization <- OrganizationDAO.findOneByName(source.id.team) q = sqlu"""update webknossos.dataSets set _dataStore = ${dataStoreName}, @@ -288,7 +288,7 @@ object DataSetSQLDAO extends SQLDAO[DataSetSQL, DatasetsRow, Datasets] { status = ${source.statusOpt.getOrElse("")} where _id = ${old._id.id}""" _ <- run(q) - _ <- DataSetDataLayerSQLDAO.updateLayers(old._id, source) + _ <- DataSetDataLayerDAO.updateLayers(old._id, source) } yield () } @@ -315,7 +315,7 @@ object DataSetSQLDAO extends SQLDAO[DataSetSQL, DatasetsRow, Datasets] { } -object DataSetResolutionsSQLDAO extends SimpleSQLDAO { +object DataSetResolutionsDAO extends SimpleSQLDAO { def parseRow(row: DatasetResolutionsRow): Fox[Point3D] = { for { @@ -354,14 +354,14 @@ object DataSetResolutionsSQLDAO extends SimpleSQLDAO { } -object DataSetDataLayerSQLDAO extends SimpleSQLDAO { +object DataSetDataLayerDAO extends SimpleSQLDAO { def parseRow(row: DatasetLayersRow, dataSetId: ObjectId): Fox[DataLayer] = { val result: Fox[Fox[DataLayer]] = for { category <- Category.fromString(row.category).toFox ?~> "Could not parse Layer Category" boundingBox <- BoundingBox.fromSQL(parseArrayTuple(row.boundingbox).map(_.toInt)).toFox ?~> "Could not parse boundingbox" elementClass <- ElementClass.fromString(row.elementclass).toFox ?~> "Could not parse Layer ElementClass" - resolutions <- DataSetResolutionsSQLDAO.findDataResolutionForLayer(dataSetId, row.name) ?~> "Could not find resolution for layer" + resolutions <- DataSetResolutionsDAO.findDataResolutionForLayer(dataSetId, row.name) ?~> "Could not find resolution for layer" } yield { (row.largestsegmentid, row.mappings) match { case (Some(segmentId), Some(mappings)) => @@ -429,13 +429,13 @@ object DataSetDataLayerSQLDAO extends SimpleSQLDAO { } for { _ <- run(DBIO.sequence(List(clearQuery) ++ insertQueries)) - _ <- DataSetResolutionsSQLDAO.updateResolutions(_dataSet, source.toUsable.map(_.dataLayers)) + _ <- DataSetResolutionsDAO.updateResolutions(_dataSet, source.toUsable.map(_.dataLayers)) } yield () } } -object DataSetAllowedTeamsSQLDAO extends SimpleSQLDAO { +object DataSetAllowedTeamsDAO extends SimpleSQLDAO { def findAllForDataSet(dataSetId: ObjectId)(implicit ctx: DBAccessContext): Fox[List[ObjectId]] = { val query = for { diff --git a/app/models/binary/DataSetService.scala b/app/models/binary/DataSetService.scala index 788be8eaa8..ba9fba93bb 100644 --- a/app/models/binary/DataSetService.scala +++ b/app/models/binary/DataSetService.scala @@ -4,7 +4,7 @@ import com.scalableminds.util.accesscontext.{DBAccessContext, GlobalAccessContex import com.scalableminds.util.tools.{Fox, FoxImplicits} import com.scalableminds.webknossos.datastore.models.datasource.inbox.{InboxDataSourceLike => InboxDataSource} import com.typesafe.scalalogging.LazyLogging -import models.team.OrganizationSQLDAO +import models.team.OrganizationDAO import net.liftweb.common.Full import oxalis.security.{URLSharing, WebknossosSilhouette} import play.api.libs.concurrent.Akka @@ -20,7 +20,7 @@ object DataSetService extends FoxImplicits with LazyLogging { name.matches("[A-Za-z0-9_\\-]*") def assertNewDataSetName(name: String)(implicit ctx: DBAccessContext): Fox[Boolean] = - DataSetSQLDAO.findOneByName(name)(GlobalAccessContext).reverse + DataSetDAO.findOneByName(name)(GlobalAccessContext).reverse def createDataSet( name: String, @@ -31,9 +31,9 @@ object DataSetService extends FoxImplicits with LazyLogging { ) = { implicit val ctx = GlobalAccessContext val newId = ObjectId.generate - OrganizationSQLDAO.findOneByName(owningOrganization).futureBox.flatMap { + OrganizationDAO.findOneByName(owningOrganization).futureBox.flatMap { case Full(organization) => for { - _ <- DataSetSQLDAO.insertOne(DataSetSQL( + _ <- DataSetDAO.insertOne(DataSet( newId, dataStore.name, organization._id, @@ -47,8 +47,8 @@ object DataSetService extends FoxImplicits with LazyLogging { None, dataSource.statusOpt.getOrElse(""), None)) - _ <- DataSetDataLayerSQLDAO.updateLayers(newId, dataSource) - _ <- DataSetAllowedTeamsSQLDAO.updateAllowedTeamsForDataSet(newId, List()) + _ <- DataSetDataLayerDAO.updateLayers(newId, dataSource) + _ <- DataSetAllowedTeamsDAO.updateAllowedTeamsForDataSet(newId, List()) } yield () case _ => Fox.failure("org.notExist") } @@ -59,9 +59,9 @@ object DataSetService extends FoxImplicits with LazyLogging { dataSource: InboxDataSource )(implicit ctx: DBAccessContext): Fox[Unit] = { - DataSetSQLDAO.findOneByName(dataSource.id.name)(GlobalAccessContext).futureBox.flatMap { + DataSetDAO.findOneByName(dataSource.id.name)(GlobalAccessContext).futureBox.flatMap { case Full(dataSet) if dataSet._dataStore == dataStoreInfo.name => - DataSetSQLDAO.updateDataSourceByName( + DataSetDAO.updateDataSourceByName( dataSource.id.name, dataStoreInfo.name, dataSource, @@ -82,15 +82,15 @@ object DataSetService extends FoxImplicits with LazyLogging { } def deactivateUnreportedDataSources(dataStoreName: String, dataSources: List[InboxDataSource])(implicit ctx: DBAccessContext) = - DataSetSQLDAO.deactivateUnreported(dataSources.map(_.id.name), dataStoreName) + DataSetDAO.deactivateUnreported(dataSources.map(_.id.name), dataStoreName) - def importDataSet(dataSet: DataSetSQL)(implicit ctx: DBAccessContext): Fox[WSResponse] = + def importDataSet(dataSet: DataSet)(implicit ctx: DBAccessContext): Fox[WSResponse] = for { dataStoreHandler <- dataSet.dataStoreHandler result <- dataStoreHandler.importDataSource } yield result - def updateDataSources(dataStore: DataStoreSQL, dataSources: List[InboxDataSource])(implicit ctx: DBAccessContext) = { + def updateDataSources(dataStore: DataStore, dataSources: List[InboxDataSource])(implicit ctx: DBAccessContext) = { logger.info(s"[${dataStore.name}] Available datasets: " + s"${dataSources.count(_.isUsable)} (usable), ${dataSources.count(!_.isUsable)} (unusable)") val dataStoreInfo = DataStoreInfo(dataStore.name, dataStore.url, dataStore.typ) @@ -104,11 +104,11 @@ object DataSetService extends FoxImplicits with LazyLogging { def createSharingToken(dataSetName: String)(implicit ctx: DBAccessContext) = { val tokenValue = URLSharing.generateToken for { - _ <- DataSetSQLDAO.updateSharingTokenByName(dataSetName, Some(tokenValue)) + _ <- DataSetDAO.updateSharingTokenByName(dataSetName, Some(tokenValue)) } yield tokenValue } - val tokenFoxOfFox: Fox[Fox[String]] = DataSetSQLDAO.getSharingTokenByName(dataSetName).map { + val tokenFoxOfFox: Fox[Fox[String]] = DataSetDAO.getSharingTokenByName(dataSetName).map { oldTokenOpt => { if (oldTokenOpt.isDefined) Fox.successful(oldTokenOpt.get) else createSharingToken(dataSetName) diff --git a/app/models/binary/DataStore.scala b/app/models/binary/DataStore.scala index 9e4c0a9397..45204c5c6f 100644 --- a/app/models/binary/DataStore.scala +++ b/app/models/binary/DataStore.scala @@ -10,7 +10,7 @@ import slick.lifted.Rep import utils.SQLDAO -case class DataStoreSQL( +case class DataStore( name: String, url: String, typ: DataStoreType, @@ -39,14 +39,14 @@ object DataStoreInfo { } -object DataStoreSQLDAO extends SQLDAO[DataStoreSQL, DatastoresRow, Datastores] { +object DataStoreDAO extends SQLDAO[DataStore, DatastoresRow, Datastores] { val collection = Datastores def idColumn(x: Datastores): Rep[String] = x.name def isDeletedColumn(x: Datastores): Rep[Boolean] = x.isdeleted - def parse(r: DatastoresRow): Fox[DataStoreSQL] = - Fox.successful(DataStoreSQL( + def parse(r: DatastoresRow): Fox[DataStore] = + Fox.successful(DataStore( r.name, r.url, DataStoreType.stringToType(r.typ), @@ -54,7 +54,7 @@ object DataStoreSQLDAO extends SQLDAO[DataStoreSQL, DatastoresRow, Datastores] { r.isdeleted )) - def findOneByKey(key: String)(implicit ctx: DBAccessContext): Fox[DataStoreSQL] = + def findOneByKey(key: String)(implicit ctx: DBAccessContext): Fox[DataStore] = for { rOpt <- run(Datastores.filter(r => notdel(r) && r.key === key).result.headOption) r <- rOpt.toFox @@ -63,7 +63,7 @@ object DataStoreSQLDAO extends SQLDAO[DataStoreSQL, DatastoresRow, Datastores] { parsed } - def findOneByName(name: String)(implicit ctx: DBAccessContext): Fox[DataStoreSQL] = + def findOneByName(name: String)(implicit ctx: DBAccessContext): Fox[DataStore] = for { rOpt <- run(Datastores.filter(r => notdel(r) && r.name === name).result.headOption) r <- rOpt.toFox @@ -77,7 +77,7 @@ object DataStoreSQLDAO extends SQLDAO[DataStoreSQL, DatastoresRow, Datastores] { for {_ <- run(q.update(url))} yield () } - def insertOne(d: DataStoreSQL): Fox[Unit] = { + def insertOne(d: DataStore): Fox[Unit] = { for { _ <- run(sqlu"""insert into webknossos.dataStores(name, url, key, typ, isDeleted) values(${d.name}, ${d.url}, ${d.key}, '#${d.typ.name}', ${d.isDeleted})""") diff --git a/app/models/binary/DataStoreHandler.scala b/app/models/binary/DataStoreHandler.scala index 76c115bd1e..ff466e88a5 100644 --- a/app/models/binary/DataStoreHandler.scala +++ b/app/models/binary/DataStoreHandler.scala @@ -65,7 +65,7 @@ object DataStoreHandlingStrategy { } -class WKStoreHandlingStrategy(dataStoreInfo: DataStoreInfo, dataSet: DataSetSQL) extends DataStoreHandlingStrategy with LazyLogging { +class WKStoreHandlingStrategy(dataStoreInfo: DataStoreInfo, dataSet: DataSet) extends DataStoreHandlingStrategy with LazyLogging { override def getSkeletonTracing(reference: TracingReference): Fox[SkeletonTracing] = { logger.debug("Called to get SkeletonTracing. Base: " + dataSet.name + " Datastore: " + dataStoreInfo) diff --git a/app/models/configuration/DataSetConfiguration.scala b/app/models/configuration/DataSetConfiguration.scala index 1a4f5067b6..bd5ba320a5 100644 --- a/app/models/configuration/DataSetConfiguration.scala +++ b/app/models/configuration/DataSetConfiguration.scala @@ -3,7 +3,7 @@ package models.configuration import com.scalableminds.util.accesscontext.DBAccessContext import com.scalableminds.util.tools.Fox import com.scalableminds.webknossos.datastore.models.datasource.Category -import models.binary.DataSetSQL +import models.binary.DataSet import play.api.libs.json._ case class DataSetConfiguration(configuration: Map[String, JsValue]) { @@ -18,7 +18,7 @@ object DataSetConfiguration { implicit val dataSetConfigurationFormat = Json.format[DataSetConfiguration] - def constructInitialDefault(dataSet: DataSetSQL)(implicit ctx: DBAccessContext): Fox[DataSetConfiguration] = + def constructInitialDefault(dataSet: DataSet)(implicit ctx: DBAccessContext): Fox[DataSetConfiguration] = for { dataSource <- dataSet.constructDataSource } yield constructInitialDefault(dataSource.toUsable.map(d => d.dataLayers.filter(_.category != Category.segmentation).map(_.name)).getOrElse(List())) diff --git a/app/models/project/Project.scala b/app/models/project/Project.scala index 44699cf667..f32c2b149c 100755 --- a/app/models/project/Project.scala +++ b/app/models/project/Project.scala @@ -5,9 +5,9 @@ import com.scalableminds.util.tools.{Fox, FoxImplicits} import com.scalableminds.webknossos.schema.Tables._ import com.typesafe.scalalogging.LazyLogging import models.annotation.{AnnotationState, AnnotationTypeSQL} -import models.task.TaskSQLDAO -import models.team.TeamSQLDAO -import models.user.{UserSQL, UserService} +import models.task.TaskDAO +import models.team.TeamDAO +import models.user.{User, UserService} import net.liftweb.common.Full import play.api.libs.concurrent.Execution.Implicits._ import play.api.libs.functional.syntax._ @@ -19,7 +19,7 @@ import utils.{ObjectId, SQLDAO} import scala.concurrent.Future -case class ProjectSQL( +case class Project( _id: ObjectId, _team: ObjectId, _owner: ObjectId, @@ -33,15 +33,15 @@ case class ProjectSQL( def owner = UserService.findOneById(_owner, useCache = true)(GlobalAccessContext) - def isDeletableBy(user: UserSQL) = user._id == _owner || user.isAdmin + def isDeletableBy(user: User) = user._id == _owner || user.isAdmin def team(implicit ctx: DBAccessContext) = - TeamSQLDAO.findOne(_team)(GlobalAccessContext) + TeamDAO.findOne(_team)(GlobalAccessContext) def publicWrites(implicit ctx: DBAccessContext): Fox[JsObject] = for { owner <- owner.flatMap(_.compactWrites).futureBox - teamNameOpt <- TeamSQLDAO.findOne(_team)(GlobalAccessContext).map(_.name).toFutureOption + teamNameOpt <- TeamDAO.findOne(_team)(GlobalAccessContext).map(_.name).toFutureOption } yield { Json.obj( "name" -> name, @@ -65,10 +65,10 @@ case class ProjectSQL( } -object ProjectSQL { +object Project { private val validateProjectName = Reads.pattern("^[a-zA-Z0-9_-]*$".r, "project.name.invalidChars") - val projectPublicReads: Reads[ProjectSQL] = + val projectPublicReads: Reads[Project] = ((__ \ 'name).read[String](Reads.minLength[String](3) keepAnd validateProjectName) and (__ \ 'team).read[String](ObjectId.stringObjectIdReads("team")) and (__ \ 'priority).read[Int] and @@ -76,18 +76,18 @@ object ProjectSQL { (__ \ 'expectedTime).readNullable[Long] and (__ \ 'owner).read[String](ObjectId.stringObjectIdReads("owner"))) ( (name, team, priority, paused, expectedTime, owner) => - ProjectSQL(ObjectId.generate, ObjectId(team), ObjectId(owner), name, priority, paused getOrElse false, expectedTime)) + Project(ObjectId.generate, ObjectId(team), ObjectId(owner), name, priority, paused getOrElse false, expectedTime)) } -object ProjectSQLDAO extends SQLDAO[ProjectSQL, ProjectsRow, Projects] { +object ProjectDAO extends SQLDAO[Project, ProjectsRow, Projects] { val collection = Projects def idColumn(x: Projects): Rep[String] = x._Id def isDeletedColumn(x: Projects): Rep[Boolean] = x.isdeleted - def parse(r: ProjectsRow): Fox[ProjectSQL] = - Fox.successful(ProjectSQL( + def parse(r: ProjectsRow): Fox[Project] = + Fox.successful(Project( ObjectId(r._Id), ObjectId(r._Team), ObjectId(r._Owner), @@ -106,7 +106,7 @@ object ProjectSQLDAO extends SQLDAO[ProjectSQL, ProjectsRow, Projects] { // read operations - override def findOne(id: ObjectId)(implicit ctx: DBAccessContext): Fox[ProjectSQL] = + override def findOne(id: ObjectId)(implicit ctx: DBAccessContext): Fox[Project] = for { accessQuery <- readAccessQuery rList <- run(sql"select #${columns} from #${existingCollectionName} where _id = ${id.id} and #${accessQuery}".as[ProjectsRow]) @@ -114,7 +114,7 @@ object ProjectSQLDAO extends SQLDAO[ProjectSQL, ProjectsRow, Projects] { parsed <- parse(r) ?~> ("SQLDAO Error: Could not parse database row for object " + id + " in " + collectionName) } yield parsed - override def findAll(implicit ctx: DBAccessContext): Fox[List[ProjectSQL]] = { + override def findAll(implicit ctx: DBAccessContext): Fox[List[Project]] = { for { accessQuery <- readAccessQuery r <- run(sql"select #${columns} from #${existingCollectionName} where #${accessQuery} order by created".as[ProjectsRow]) @@ -122,7 +122,7 @@ object ProjectSQLDAO extends SQLDAO[ProjectSQL, ProjectsRow, Projects] { } yield parsed } - def findOneByName(name: String)(implicit ctx: DBAccessContext): Fox[ProjectSQL] = + def findOneByName(name: String)(implicit ctx: DBAccessContext): Fox[Project] = for { accessQuery <- readAccessQuery rList <- run(sql"select #${columns} from #${existingCollectionName} where name = '#${sanitize(name)}' and #${accessQuery}".as[ProjectsRow]) @@ -148,14 +148,14 @@ object ProjectSQLDAO extends SQLDAO[ProjectSQL, ProjectsRow, Projects] { // write operations - def insertOne(p: ProjectSQL)(implicit ctx: DBAccessContext): Fox[Unit] = + def insertOne(p: Project)(implicit ctx: DBAccessContext): Fox[Unit] = for { _ <- run(sqlu"""insert into webknossos.projects(_id, _team, _owner, name, priority, paused, expectedTime, created, isDeleted) values(${p._id.id}, ${p._team.id}, ${p._owner.id}, ${p.name}, ${p.priority}, ${p.paused}, ${p.expectedTime}, ${new java.sql.Timestamp(p.created)}, ${p.isDeleted})""") } yield () - def updateOne(p: ProjectSQL)(implicit ctx: DBAccessContext): Fox[Unit] = + def updateOne(p: Project)(implicit ctx: DBAccessContext): Fox[Unit] = for { //note that p.created is skipped _ <- assertUpdateAccess(p._id) _ <- run(sqlu"""update webknossos.projects @@ -180,12 +180,12 @@ object ProjectService extends LazyLogging with FoxImplicits { def deleteOne(projectId: ObjectId)(implicit ctx: DBAccessContext): Fox[Boolean] = { val futureFox: Future[Fox[Boolean]] = for { - removalSuccessBox <- ProjectSQLDAO.deleteOne(projectId).futureBox + removalSuccessBox <- ProjectDAO.deleteOne(projectId).futureBox } yield { removalSuccessBox match { case Full(_) => { for { - _ <- TaskSQLDAO.removeAllWithProjectAndItsAnnotations(projectId) + _ <- TaskDAO.removeAllWithProjectAndItsAnnotations(projectId) } yield true } case _ => { diff --git a/app/models/task/Script.scala b/app/models/task/Script.scala index a01df6765e..f48a418f47 100644 --- a/app/models/task/Script.scala +++ b/app/models/task/Script.scala @@ -3,7 +3,7 @@ package models.task import com.scalableminds.util.accesscontext.{DBAccessContext, GlobalAccessContext} import com.scalableminds.util.tools.{Fox, FoxImplicits} import com.scalableminds.webknossos.schema.Tables._ -import models.user.UserSQLDAO +import models.user.UserDAO import play.api.libs.concurrent.Execution.Implicits._ import play.api.libs.json._ import slick.jdbc.PostgresProfile.api._ @@ -11,7 +11,7 @@ import slick.lifted.Rep import utils.{ObjectId, SQLDAO} -case class ScriptSQL( +case class Script( _id: ObjectId, _owner: ObjectId, name: String, @@ -23,7 +23,7 @@ case class ScriptSQL( def publicWrites: Fox[JsObject] = { implicit val ctx = GlobalAccessContext for { - owner <- UserSQLDAO.findOne(_owner) + owner <- UserDAO.findOne(_owner) ownerJs <- owner.compactWrites } yield { Json.obj( @@ -37,17 +37,17 @@ case class ScriptSQL( } -object ScriptSQL { +object Script { def fromForm( name: String, gist: String, _owner: String) = { - ScriptSQL(ObjectId.generate, ObjectId(_owner), name, gist) + Script(ObjectId.generate, ObjectId(_owner), name, gist) } } -object ScriptSQLDAO extends SQLDAO[ScriptSQL, ScriptsRow, Scripts] { +object ScriptDAO extends SQLDAO[Script, ScriptsRow, Scripts] { val collection = Scripts def idColumn(x: Scripts): Rep[String] = x._Id @@ -56,8 +56,8 @@ object ScriptSQLDAO extends SQLDAO[ScriptSQL, ScriptsRow, Scripts] { override def readAccessQ(requestingUserId: ObjectId): String = s"(select _organization from webknossos.users_ u where u._id = _owner) = (select _organization from webknossos.users_ u where u._id = '${requestingUserId}')" - def parse(r: ScriptsRow): Fox[ScriptSQL] = - Fox.successful(ScriptSQL( + def parse(r: ScriptsRow): Fox[Script] = + Fox.successful(Script( ObjectId(r._Id), ObjectId(r._Owner), r.name, @@ -66,13 +66,13 @@ object ScriptSQLDAO extends SQLDAO[ScriptSQL, ScriptsRow, Scripts] { r.isdeleted )) - def insertOne(s: ScriptSQL)(implicit ctx: DBAccessContext): Fox[Unit] = + def insertOne(s: Script)(implicit ctx: DBAccessContext): Fox[Unit] = for { _ <- run(sqlu"""insert into webknossos.scripts(_id, _owner, name, gist, created, isDeleted) values(${s._id}, ${s._owner}, ${s.name}, ${s.gist}, ${new java.sql.Timestamp(s.created)}, ${s.isDeleted})""") } yield () - def updateOne(s: ScriptSQL)(implicit ctx: DBAccessContext): Fox[Unit] = + def updateOne(s: Script)(implicit ctx: DBAccessContext): Fox[Unit] = for { //note that s.created is skipped _ <- assertUpdateAccess(s._id) _ <- run(sqlu"""update webknossos.scripts @@ -84,7 +84,7 @@ object ScriptSQLDAO extends SQLDAO[ScriptSQL, ScriptsRow, Scripts] { where _id = ${s._id}""") } yield () - override def findAll(implicit ctx: DBAccessContext): Fox[List[ScriptSQL]] = + override def findAll(implicit ctx: DBAccessContext): Fox[List[Script]] = for { accessQuery <- readAccessQuery r <- run(sql"select #${columns} from webknossos.scripts_ where #${accessQuery}".as[ScriptsRow]) diff --git a/app/models/task/Task.scala b/app/models/task/Task.scala index 6394da40f5..1b05150d02 100755 --- a/app/models/task/Task.scala +++ b/app/models/task/Task.scala @@ -7,10 +7,10 @@ import com.scalableminds.util.tools.{Fox, FoxImplicits} import com.scalableminds.webknossos.datastore.tracings.TracingType import com.scalableminds.webknossos.schema.Tables._ import models.annotation._ -import models.binary.DataSetSQLDAO -import models.project.ProjectSQLDAO -import models.team.TeamSQLDAO -import models.user.{Experience, UserSQL} +import models.binary.DataSetDAO +import models.project.ProjectDAO +import models.team.TeamDAO +import models.user.{Experience, User} import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import play.api.Play.current @@ -25,7 +25,7 @@ import utils.{ObjectId, SQLClient, SQLDAO} import scala.util.Random -case class TaskSQL( +case class Task( _id: ObjectId, _project: ObjectId, _script: Option[ObjectId], @@ -48,10 +48,10 @@ case class TaskSQL( AnnotationService.baseFor(_id) def taskType(implicit ctx: DBAccessContext) = - TaskTypeSQLDAO.findOne(_taskType)(GlobalAccessContext) + TaskTypeDAO.findOne(_taskType)(GlobalAccessContext) def project(implicit ctx: DBAccessContext) = - ProjectSQLDAO.findOne(_project) + ProjectDAO.findOne(_project) def annotations(implicit ctx: DBAccessContext) = AnnotationService.annotationsFor(_id) @@ -72,11 +72,11 @@ case class TaskSQL( def publicWrites(implicit ctx: DBAccessContext): Fox[JsObject] = for { annotationBase <- annotationBase - dataSet <- DataSetSQLDAO.findOne(annotationBase._dataSet) + dataSet <- DataSetDAO.findOne(annotationBase._dataSet) status <- status.getOrElse(CompletionStatus(-1, -1, -1)) taskType <- taskType taskTypeJs <- taskType.publicWrites - scriptInfo <- _script.toFox.flatMap(sid => ScriptSQLDAO.findOne(sid)).futureBox + scriptInfo <- _script.toFox.flatMap(sid => ScriptDAO.findOne(sid)).futureBox scriptJs <- scriptInfo.toFox.flatMap(s => s.publicWrites).futureBox project <- project team <- project.team @@ -102,18 +102,18 @@ case class TaskSQL( } -object TaskSQLDAO extends SQLDAO[TaskSQL, TasksRow, Tasks] { +object TaskDAO extends SQLDAO[Task, TasksRow, Tasks] { val collection = Tasks def idColumn(x: Tasks) = x._Id def isDeletedColumn(x: Tasks) = x.isdeleted - def parse(r: TasksRow): Fox[TaskSQL] = + def parse(r: TasksRow): Fox[Task] = for { editPosition <- Point3D.fromList(parseArrayTuple(r.editposition).map(_.toInt)) ?~> "could not parse edit position" editRotation <- Vector3D.fromList(parseArrayTuple(r.editrotation).map(_.toDouble)) ?~> "could not parse edit rotation" } yield { - TaskSQL( + Task( ObjectId(r._Id), ObjectId(r._Project), r._Script.map(ObjectId(_)), @@ -140,7 +140,7 @@ object TaskSQLDAO extends SQLDAO[TaskSQL, TasksRow, Tasks] { or ((select _organization from webknossos.teams where webknossos.teams._id = (select _team from webknossos.projects p where _project = p._id)) in (select _organization from webknossos.users_ where _id = '${requestingUserId.id}' and isAdmin)))""" - override def findOne(id: ObjectId)(implicit ctx: DBAccessContext): Fox[TaskSQL] = + override def findOne(id: ObjectId)(implicit ctx: DBAccessContext): Fox[Task] = for { accessQuery <- readAccessQuery rList <- run(sql"select #${columns} from #${existingCollectionName} where _id = ${id.id} and #${accessQuery}".as[TasksRow]) @@ -148,7 +148,7 @@ object TaskSQLDAO extends SQLDAO[TaskSQL, TasksRow, Tasks] { parsed <- parse(r) ?~> ("SQLDAO Error: Could not parse database row for object " + id + " in " + collectionName) } yield parsed - override def findAll(implicit ctx: DBAccessContext): Fox[List[TaskSQL]] = { + override def findAll(implicit ctx: DBAccessContext): Fox[List[Task]] = { for { accessQuery <- readAccessQuery r <- run(sql"select #${columns} from #${existingCollectionName} where #${accessQuery}".as[TasksRow]) @@ -156,14 +156,14 @@ object TaskSQLDAO extends SQLDAO[TaskSQL, TasksRow, Tasks] { } yield parsed } - def findAllByTaskType(taskTypeId: ObjectId)(implicit ctx: DBAccessContext): Fox[List[TaskSQL]] = + def findAllByTaskType(taskTypeId: ObjectId)(implicit ctx: DBAccessContext): Fox[List[Task]] = for { accessQuery <- readAccessQuery r <- run(sql"select #${columns} from #${existingCollectionName} where _taskType = ${taskTypeId.id} and #${accessQuery}".as[TasksRow]) parsed <- Fox.combined(r.toList.map(parse)) } yield parsed - def findAllByProject(projectId: ObjectId)(implicit ctx: DBAccessContext): Fox[List[TaskSQL]] = + def findAllByProject(projectId: ObjectId)(implicit ctx: DBAccessContext): Fox[List[Task]] = for { accessQuery <- readAccessQuery r <- run(sql"select #${columns} from #${existingCollectionName} where _project = ${projectId.id} and #${accessQuery}".as[TasksRow]) @@ -192,7 +192,7 @@ object TaskSQLDAO extends SQLDAO[TaskSQL, TasksRow, Tasks] { limit 1 """ - def assignNext(userId: ObjectId, teamIds: List[ObjectId])(implicit ctx: DBAccessContext): Fox[(TaskSQL, ObjectId)] = { + def assignNext(userId: ObjectId, teamIds: List[ObjectId])(implicit ctx: DBAccessContext): Fox[(Task, ObjectId)] = { val annotationId = ObjectId.generate val dummyTracingId = Random.alphanumeric.take(36).mkString @@ -225,7 +225,7 @@ object TaskSQLDAO extends SQLDAO[TaskSQL, TasksRow, Tasks] { } yield (parsed, annotationId) } - def peekNextAssignment(userId: ObjectId, teamIds: List[ObjectId])(implicit ctx: DBAccessContext): Fox[TaskSQL] = { + def peekNextAssignment(userId: ObjectId, teamIds: List[ObjectId])(implicit ctx: DBAccessContext): Fox[Task] = { for { rList <- run(sql"#${findNextTaskQ(userId, teamIds)}".as[TasksRow]) r <- rList.headOption.toFox @@ -239,7 +239,7 @@ object TaskSQLDAO extends SQLDAO[TaskSQL, TasksRow, Tasks] { taskIdsOpt: Option[List[ObjectId]], userIdOpt: Option[ObjectId], randomizeOpt: Option[Boolean] - )(implicit ctx: DBAccessContext): Fox[List[TaskSQL]] = { + )(implicit ctx: DBAccessContext): Fox[List[Task]] = { /* WARNING: This code composes an sql query with #${} without sanitize(). Change with care. */ @@ -248,7 +248,7 @@ object TaskSQLDAO extends SQLDAO[TaskSQL, TasksRow, Tasks] { case _ => "" } val projectFilterFox = projectNameOpt match { - case Some(pName) => for {project <- ProjectSQLDAO.findOneByName(pName)} yield s"(t._project = '${project._id}')" + case Some(pName) => for {project <- ProjectDAO.findOneByName(pName)} yield s"(t._project = '${project._id}')" case _ => Fox.successful("true") } val taskTypeFilter = taskTypeIdOpt.map(ttId => s"(t._taskType = '${ttId}')").getOrElse("true") @@ -310,7 +310,7 @@ object TaskSQLDAO extends SQLDAO[TaskSQL, TasksRow, Tasks] { } } - def insertOne(t: TaskSQL): Fox[Unit] = { + def insertOne(t: Task): Fox[Unit] = { for { _ <- run( sqlu"""insert into webknossos.tasks(_id, _project, _script, _taskType, neededExperience_domain, neededExperience_value, diff --git a/app/models/task/TaskType.scala b/app/models/task/TaskType.scala index 2f4e03b23e..80c8dda847 100755 --- a/app/models/task/TaskType.scala +++ b/app/models/task/TaskType.scala @@ -14,7 +14,7 @@ import slick.jdbc.PostgresProfile.api._ import slick.lifted.Rep import utils.{ObjectId, SQLDAO, SecuredSQLDAO} -case class TaskTypeSQL( +case class TaskType( _id: ObjectId, _team: ObjectId, summary: String, @@ -35,13 +35,13 @@ case class TaskTypeSQL( } } -object TaskTypeSQL { +object TaskType { def fromForm( summary: String, description: String, team: String, settings: AnnotationSettings) = { - TaskTypeSQL( + TaskType( ObjectId.generate, ObjectId(team), summary, @@ -50,14 +50,14 @@ object TaskTypeSQL { } } -object TaskTypeSQLDAO extends SQLDAO[TaskTypeSQL, TasktypesRow, Tasktypes] with SecuredSQLDAO { +object TaskTypeDAO extends SQLDAO[TaskType, TasktypesRow, Tasktypes] with SecuredSQLDAO { val collection = Tasktypes def idColumn(x: Tasktypes): Rep[String] = x._Id def isDeletedColumn(x: Tasktypes): Rep[Boolean] = x.isdeleted - def parse(r: TasktypesRow): Fox[TaskTypeSQL] = - Some(TaskTypeSQL( + def parse(r: TasktypesRow): Fox[TaskType] = + Some(TaskType( ObjectId(r._Id), ObjectId(r._Team), r.summary, @@ -82,7 +82,7 @@ object TaskTypeSQLDAO extends SQLDAO[TaskTypeSQL, TasktypesRow, Tasktypes] with or (select _organization from webknossos.teams where webknossos.teams._id = _team) in (select _organization from webknossos.users_ where _id = '${requestingUserId.id}' and isAdmin))""" - override def findOne(id: ObjectId)(implicit ctx: DBAccessContext): Fox[TaskTypeSQL] = + override def findOne(id: ObjectId)(implicit ctx: DBAccessContext): Fox[TaskType] = for { accessQuery <- readAccessQuery rList <- run(sql"select #${columns} from #${existingCollectionName} where _id = ${id.id} and #${accessQuery}".as[TasktypesRow]) @@ -90,7 +90,7 @@ object TaskTypeSQLDAO extends SQLDAO[TaskTypeSQL, TasktypesRow, Tasktypes] with parsed <- parse(r) ?~> ("SQLDAO Error: Could not parse database row for object " + id + " in " + collectionName) } yield parsed - override def findAll(implicit ctx: DBAccessContext): Fox[List[TaskTypeSQL]] = + override def findAll(implicit ctx: DBAccessContext): Fox[List[TaskType]] = for { accessQuery <- readAccessQuery r <- run(sql"select #${columns} from #${existingCollectionName} where #${accessQuery}".as[TasktypesRow]) @@ -98,7 +98,7 @@ object TaskTypeSQLDAO extends SQLDAO[TaskTypeSQL, TasktypesRow, Tasktypes] with } yield parsed - def insertOne(t: TaskTypeSQL)(implicit ctx: DBAccessContext): Fox[Unit] = { + def insertOne(t: TaskType)(implicit ctx: DBAccessContext): Fox[Unit] = { val allowedModes = writeArrayTuple(t.settings.allowedModes) for { _ <- run(sqlu"""insert into webknossos.taskTypes(_id, _team, summary, description, settings_allowedModes, settings_preferredMode, @@ -109,7 +109,7 @@ object TaskTypeSQLDAO extends SQLDAO[TaskTypeSQL, TasktypesRow, Tasktypes] with } - def updateOne(t: TaskTypeSQL)(implicit ctx: DBAccessContext): Fox[Unit] = + def updateOne(t: TaskType)(implicit ctx: DBAccessContext): Fox[Unit] = for { //note that t.created is skipped _ <- assertUpdateAccess(t._id) _ <- run(sqlu"""update webknossos.taskTypes diff --git a/app/models/team/Organization.scala b/app/models/team/Organization.scala index c8a7de91b9..ea6d2a5060 100755 --- a/app/models/team/Organization.scala +++ b/app/models/team/Organization.scala @@ -11,7 +11,7 @@ import slick.jdbc.PostgresProfile.api._ import slick.lifted.Rep import utils.{ObjectId, SQLDAO} -case class OrganizationSQL( +case class Organization( _id: ObjectId, name: String, additionalInformation: String, @@ -24,10 +24,10 @@ case class OrganizationSQL( ) { def organizationTeamId(implicit ctx: DBAccessContext): Fox[ObjectId] = - OrganizationSQLDAO.findOrganizationTeamId(_id) + OrganizationDAO.findOrganizationTeamId(_id) def teamIds(implicit ctx: DBAccessContext): Fox[List[ObjectId]] = - TeamSQLDAO.findAllIdsByOrganization(_id) + TeamDAO.findAllIdsByOrganization(_id) def publicWrites(implicit ctx: DBAccessContext): Fox[JsObject] = { Fox.successful(Json.obj( @@ -39,7 +39,7 @@ case class OrganizationSQL( } } -object OrganizationSQLDAO extends SQLDAO[OrganizationSQL, OrganizationsRow, Organizations] { +object OrganizationDAO extends SQLDAO[Organization, OrganizationsRow, Organizations] { val collection = Organizations def idColumn(x: Organizations): Rep[String] = x._Id @@ -47,9 +47,9 @@ object OrganizationSQLDAO extends SQLDAO[OrganizationSQL, OrganizationsRow, Orga def isDeletedColumn(x: Organizations): Rep[Boolean] = x.isdeleted - def parse(r: OrganizationsRow): Fox[OrganizationSQL] = + def parse(r: OrganizationsRow): Fox[Organization] = Fox.successful( - OrganizationSQL( + Organization( ObjectId(r._Id), r.name, r.additionalinformation, @@ -64,7 +64,7 @@ object OrganizationSQLDAO extends SQLDAO[OrganizationSQL, OrganizationsRow, Orga override def readAccessQ(requestingUserId: ObjectId) = s"(_id in (select _organization from webknossos.users_ where _id = '${requestingUserId.id}'))" - def findOneByName(name: String)(implicit ctx: DBAccessContext): Fox[OrganizationSQL] = + def findOneByName(name: String)(implicit ctx: DBAccessContext): Fox[Organization] = for { accessQuery <- readAccessQuery rList <- run(sql"select #${columns} from #${existingCollectionName} where name = ${name} and #${accessQuery}".as[OrganizationsRow]) @@ -74,7 +74,7 @@ object OrganizationSQLDAO extends SQLDAO[OrganizationSQL, OrganizationsRow, Orga parsed } - def insertOne(o: OrganizationSQL)(implicit ctx: DBAccessContext): Fox[Unit] = + def insertOne(o: Organization)(implicit ctx: DBAccessContext): Fox[Unit] = for { r <- run( diff --git a/app/models/team/Team.scala b/app/models/team/Team.scala index 105ca5b32e..9805272f6b 100755 --- a/app/models/team/Team.scala +++ b/app/models/team/Team.scala @@ -4,7 +4,7 @@ package models.team import com.scalableminds.util.accesscontext.{DBAccessContext, GlobalAccessContext} import com.scalableminds.util.tools.{Fox, FoxImplicits} import com.scalableminds.webknossos.schema.Tables._ -import models.user.UserSQL +import models.user.User import play.api.Play.current import play.api.i18n.Messages import play.api.i18n.Messages.Implicits._ @@ -15,7 +15,7 @@ import slick.lifted.Rep import utils.{ObjectId, SQLDAO} -case class TeamSQL( +case class Team( _id: ObjectId, _organization: ObjectId, name: String, @@ -24,10 +24,10 @@ case class TeamSQL( isDeleted: Boolean = false ) extends FoxImplicits { - def organization: Fox[OrganizationSQL] = - OrganizationSQLDAO.findOne(_organization)(GlobalAccessContext) + def organization: Fox[Organization] = + OrganizationDAO.findOne(_organization)(GlobalAccessContext) - def couldBeAdministratedBy(user: UserSQL): Boolean = + def couldBeAdministratedBy(user: User): Boolean = user._organization == this._organization def publicWrites(implicit ctx: DBAccessContext): Fox[JsObject] = @@ -42,14 +42,14 @@ case class TeamSQL( } } -object TeamSQLDAO extends SQLDAO[TeamSQL, TeamsRow, Teams] { +object TeamDAO extends SQLDAO[Team, TeamsRow, Teams] { val collection = Teams def idColumn(x: Teams): Rep[String] = x._Id def isDeletedColumn(x: Teams): Rep[Boolean] = x.isdeleted - def parse(r: TeamsRow): Fox[TeamSQL] = { - Fox.successful(TeamSQL( + def parse(r: TeamsRow): Fox[Team] = { + Fox.successful(Team( ObjectId(r._Id), ObjectId(r._Organization), r.name, @@ -67,7 +67,7 @@ object TeamSQLDAO extends SQLDAO[TeamSQL, TeamsRow, Teams] { s"""(not isorganizationteam and _organization in (select _organization from webknossos.users_ where _id = '${requestingUserId.id}' and isAdmin))""" - override def findOne(id: ObjectId)(implicit ctx: DBAccessContext): Fox[TeamSQL] = + override def findOne(id: ObjectId)(implicit ctx: DBAccessContext): Fox[Team] = for { accessQuery <- readAccessQuery rList <- run(sql"select #${columns} from #${existingCollectionName} where _id = ${id.id} and #${accessQuery}".as[TeamsRow]) @@ -75,7 +75,7 @@ object TeamSQLDAO extends SQLDAO[TeamSQL, TeamsRow, Teams] { parsed <- parse(r) ?~> ("SQLDAO Error: Could not parse database row for object " + id + " in " + collectionName) } yield parsed - def findOneByName(name: String)(implicit ctx: DBAccessContext): Fox[TeamSQL] = + def findOneByName(name: String)(implicit ctx: DBAccessContext): Fox[Team] = for { accessQuery <- readAccessQuery rList <- run(sql"select #${columns} from #${existingCollectionName} where name = ${name} and #${accessQuery}".as[TeamsRow]) @@ -83,7 +83,7 @@ object TeamSQLDAO extends SQLDAO[TeamSQL, TeamsRow, Teams] { parsed <- parse(r) } yield parsed - override def findAll(implicit ctx: DBAccessContext): Fox[List[TeamSQL]] = { + override def findAll(implicit ctx: DBAccessContext): Fox[List[Team]] = { for { accessQuery <- readAccessQuery r <- run(sql"select #${columns} from #${existingCollectionName} where #${accessQuery}".as[TeamsRow]) @@ -91,7 +91,7 @@ object TeamSQLDAO extends SQLDAO[TeamSQL, TeamsRow, Teams] { } yield parsed } - def findAllEditable(implicit ctx: DBAccessContext): Fox[List[TeamSQL]] = { + def findAllEditable(implicit ctx: DBAccessContext): Fox[List[Team]] = { for { requestingUserId <- userIdFromCtx accessQuery <- readAccessQuery @@ -103,7 +103,7 @@ object TeamSQLDAO extends SQLDAO[TeamSQL, TeamsRow, Teams] { } yield parsed } - def findAllByOrganization(organizationId: ObjectId)(implicit ctx: DBAccessContext): Fox[List[TeamSQL]] = { + def findAllByOrganization(organizationId: ObjectId)(implicit ctx: DBAccessContext): Fox[List[Team]] = { for { accessQuery <- readAccessQuery r <- run(sql"select #${columns} from #${existingCollectionName} where _organization = ${organizationId.id} and #${accessQuery}".as[TeamsRow]) @@ -119,7 +119,7 @@ object TeamSQLDAO extends SQLDAO[TeamSQL, TeamsRow, Teams] { } yield parsed } - def insertOne(t: TeamSQL)(implicit ctx: DBAccessContext): Fox[Unit] = + def insertOne(t: Team)(implicit ctx: DBAccessContext): Fox[Unit] = for { r <- run( sqlu"""insert into webknossos.teams(_id, _organization, name, created, isOrganizationTeam, isDeleted) diff --git a/app/models/team/TeamMembership.scala b/app/models/team/TeamMembership.scala index d631b5ef9f..ce797ccfab 100755 --- a/app/models/team/TeamMembership.scala +++ b/app/models/team/TeamMembership.scala @@ -10,7 +10,7 @@ import utils.ObjectId case class TeamMembershipSQL(teamId: ObjectId, isTeamManager: Boolean) { def publicWrites(implicit ctx: DBAccessContext): Fox[JsObject] = { for { - team <- TeamSQLDAO.findOne(teamId) + team <- TeamDAO.findOne(teamId) } yield { Json.obj( "id" -> teamId.toString, diff --git a/app/models/user/User.scala b/app/models/user/User.scala index 9853e6d4ad..64497fc12a 100755 --- a/app/models/user/User.scala +++ b/app/models/user/User.scala @@ -5,7 +5,7 @@ import com.mohiva.play.silhouette.api.{Identity, LoginInfo} import com.scalableminds.util.accesscontext._ import com.scalableminds.util.tools.{Fox, FoxImplicits, JsonHelper} import com.scalableminds.webknossos.schema.Tables._ -import models.binary.DataSetSQLDAO +import models.binary.DataSetDAO import models.configuration.{DataSetConfiguration, UserConfiguration} import models.team._ import play.api.Play.current @@ -19,7 +19,7 @@ import slick.lifted.Rep import utils.{ObjectId, SQLDAO, SimpleSQLDAO} -case class UserSQL( +case class User( _id: ObjectId, _organization: ObjectId, email: String, @@ -41,14 +41,14 @@ case class UserSQL( val abreviatedName = (firstName.take(1) + lastName).toLowerCase.replace(" ", "_") - def organization = OrganizationSQLDAO.findOne(_organization)(GlobalAccessContext) + def organization = OrganizationDAO.findOne(_organization)(GlobalAccessContext) - def experiences = UserExperiencesSQLDAO.findAllExperiencesForUser(_id)(GlobalAccessContext) + def experiences = UserExperiencesDAO.findAllExperiencesForUser(_id)(GlobalAccessContext) def userConfigurationStructured = JsonHelper.jsResultToFox(userConfiguration.validate[Map[String, JsValue]]).map(UserConfiguration(_)) - def teamMemberships = UserTeamRolesSQLDAO.findTeamMembershipsForUser(_id)(GlobalAccessContext) + def teamMemberships = UserTeamRolesDAO.findTeamMembershipsForUser(_id)(GlobalAccessContext) def teamManagerMemberships = for { @@ -65,7 +65,7 @@ case class UserSQL( teamMemberships <- teamMemberships } yield teamMemberships.map(_.teamId) - def isTeamManagerOrAdminOf(otherUser: UserSQL): Fox[Boolean] = + def isTeamManagerOrAdminOf(otherUser: User): Fox[Boolean] = for { otherUserTeamIds <- otherUser.teamIds teamManagerTeamIds <- teamManagerTeamIds @@ -73,7 +73,7 @@ case class UserSQL( def isTeamManagerOrAdminOf(_team: ObjectId): Fox[Boolean] = for { - team <- TeamSQLDAO.findOne(_team)(GlobalAccessContext) + team <- TeamDAO.findOne(_team)(GlobalAccessContext) teamManagerTeamIds <- teamManagerTeamIds } yield (teamManagerTeamIds.contains(_team) || this.isAdminOf(team._organization)) @@ -82,7 +82,7 @@ case class UserSQL( isTeamManager <- isTeamManagerInOrg(_organization) } yield (isTeamManager || this.isAdminOf(_organization)) - def isEditableBy(otherUser: UserSQL): Fox[Boolean] = + def isEditableBy(otherUser: User): Fox[Boolean] = for { otherIsTeamManagerOrAdmin <- otherUser.isTeamManagerOrAdminOf(this) teamMemberships <- teamMemberships @@ -96,10 +96,10 @@ case class UserSQL( def isAdminOf(_organization: ObjectId): Boolean = isAdmin && _organization == this._organization - def isAdminOf(otherUser: UserSQL): Boolean = + def isAdminOf(otherUser: User): Boolean = isAdminOf(otherUser._organization) - def publicWrites(requestingUser: UserSQL): Fox[JsObject] = { + def publicWrites(requestingUser: User): Fox[JsObject] = { implicit val ctx = GlobalAccessContext for { isEditable <- isEditableBy(requestingUser) @@ -144,14 +144,14 @@ case class UserSQL( } -object UserSQLDAO extends SQLDAO[UserSQL, UsersRow, Users] { +object UserDAO extends SQLDAO[User, UsersRow, Users] { val collection = Users def idColumn(x: Users): Rep[String] = x._Id def isDeletedColumn(x: Users): Rep[Boolean] = x.isdeleted - def parse(r: UsersRow): Fox[UserSQL] = - Fox.successful(UserSQL( + def parse(r: UsersRow): Fox[User] = + Fox.successful(User( ObjectId(r._Id), ObjectId(r._Organization), r.email, @@ -176,7 +176,7 @@ object UserSQLDAO extends SQLDAO[UserSQL, UsersRow, Users] { s"_organization in (select _organization from webknossos.users_ where _id = '${requestingUserId}' and isAdmin)" - override def findOne(id: ObjectId)(implicit ctx: DBAccessContext): Fox[UserSQL] = + override def findOne(id: ObjectId)(implicit ctx: DBAccessContext): Fox[User] = for { accessQuery <- readAccessQuery rList <- run(sql"select #${columns} from #${existingCollectionName} where _id = ${id} and #${accessQuery}".as[UsersRow]) @@ -184,7 +184,7 @@ object UserSQLDAO extends SQLDAO[UserSQL, UsersRow, Users] { parsed <- parse(r) ?~> ("SQLDAO Error: Could not parse database row for object " + id + " in " + collectionName) } yield parsed - override def findAll(implicit ctx: DBAccessContext): Fox[List[UserSQL]] = { + override def findAll(implicit ctx: DBAccessContext): Fox[List[User]] = { for { accessQuery <- readAccessQuery r <- run(sql"select #${columns} from #${existingCollectionName} where #${accessQuery}".as[UsersRow]) @@ -192,7 +192,7 @@ object UserSQLDAO extends SQLDAO[UserSQL, UsersRow, Users] { } yield parsed } - def findOneByEmail(email: String)(implicit ctx: DBAccessContext): Fox[UserSQL] = + def findOneByEmail(email: String)(implicit ctx: DBAccessContext): Fox[User] = for { accessQuery <- readAccessQuery rList <- run(sql"select #${columns} from #${existingCollectionName} where email = ${email} and #${accessQuery}".as[UsersRow]) @@ -216,7 +216,7 @@ object UserSQLDAO extends SQLDAO[UserSQL, UsersRow, Users] { } yield parsed } - def findAllByIds(ids: List[ObjectId])(implicit ctx: DBAccessContext): Fox[List[UserSQL]] = + def findAllByIds(ids: List[ObjectId])(implicit ctx: DBAccessContext): Fox[List[User]] = for { accessQuery <- readAccessQuery r <- run(sql"select #${columns} from #${existingCollectionName} where _id in #${writeStructTupleWithQuotes(ids.map(_.id))} and #${accessQuery}".as[UsersRow]) @@ -224,7 +224,7 @@ object UserSQLDAO extends SQLDAO[UserSQL, UsersRow, Users] { } yield parsed - def insertOne(u: UserSQL)(implicit ctx: DBAccessContext): Fox[Unit] = + def insertOne(u: User)(implicit ctx: DBAccessContext): Fox[Unit] = for { _ <- run( sqlu"""insert into webknossos.users(_id, _organization, email, firstName, lastName, lastActivity, userConfiguration, md5hash, loginInfo_providerID, @@ -267,7 +267,7 @@ object UserSQLDAO extends SQLDAO[UserSQL, UsersRow, Users] { } } -object UserTeamRolesSQLDAO extends SimpleSQLDAO { +object UserTeamRolesDAO extends SimpleSQLDAO { def findTeamMembershipsForUser(userId: ObjectId)(implicit ctx: DBAccessContext): Fox[List[TeamMembershipSQL]] = { val query = for { @@ -289,14 +289,14 @@ object UserTeamRolesSQLDAO extends SimpleSQLDAO { val clearQuery = sqlu"delete from webknossos.user_team_roles where _user = ${userId}" val insertQueries = teamMemberships.map(insertQuery(userId, _)) for { - _ <- UserSQLDAO.assertUpdateAccess(userId) + _ <- UserDAO.assertUpdateAccess(userId) _ <- run(DBIO.sequence(List(clearQuery) ++ insertQueries).transactionally) } yield () } def insertTeamMembership(userId: ObjectId, teamMembership: TeamMembershipSQL)(implicit ctx: DBAccessContext): Fox[Unit] = for { - _ <- UserSQLDAO.assertUpdateAccess(userId) + _ <- UserDAO.assertUpdateAccess(userId) _ <- run(insertQuery(userId, teamMembership)) } yield () @@ -308,7 +308,7 @@ object UserTeamRolesSQLDAO extends SimpleSQLDAO { } -object UserExperiencesSQLDAO extends SimpleSQLDAO { +object UserExperiencesDAO extends SimpleSQLDAO { def findAllExperiencesForUser(userId: ObjectId)(implicit ctx: DBAccessContext): Fox[Map[String, Int]] = { for { @@ -322,14 +322,14 @@ object UserExperiencesSQLDAO extends SimpleSQLDAO { val clearQuery = sqlu"delete from webknossos.user_experiences where _user = ${userId}" val insertQueries = experiences.map { case (domain, value) => sqlu"insert into webknossos.user_experiences(_user, domain, value) values(${userId}, ${domain}, ${value})"} for { - _ <- UserSQLDAO.assertUpdateAccess(userId) + _ <- UserDAO.assertUpdateAccess(userId) _ <- run(DBIO.sequence(List(clearQuery) ++ insertQueries).transactionally) } yield () } } -object UserDataSetConfigurationSQLDAO extends SimpleSQLDAO { +object UserDataSetConfigurationDAO extends SimpleSQLDAO { def findAllForUser(userId: ObjectId)(implicit ctx: DBAccessContext): Fox[Map[ObjectId, JsValue]] = { for { @@ -355,7 +355,7 @@ object UserDataSetConfigurationSQLDAO extends SimpleSQLDAO { def updateDatasetConfigurationForUserAndDataset(userId: ObjectId, dataSetId: ObjectId, configuration: Map[String, JsValue])(implicit ctx: DBAccessContext): Fox[Unit] = { for { - _ <- UserSQLDAO.assertUpdateAccess(userId) + _ <- UserDAO.assertUpdateAccess(userId) deleteQuery = sqlu"""delete from webknossos.user_dataSetConfigurations where _user = ${userId} and _dataSet = ${dataSetId}""" insertQuery = sqlu"""insert into webknossos.user_dataSetConfigurations(_user, _dataSet, configuration) @@ -373,14 +373,14 @@ object UserDataSetConfigurationSQLDAO extends SimpleSQLDAO { private def insertDatasetConfiguration(userId: ObjectId, dataSetName: String, configuration: Map[String, JsValue])(implicit ctx: DBAccessContext): Fox[Unit] = { for { - dataSet <- DataSetSQLDAO.findOneByName(dataSetName) + dataSet <- DataSetDAO.findOneByName(dataSetName) _ <- insertDatasetConfiguration(userId, dataSet._id, configuration) } yield () } private def insertDatasetConfiguration(userId: ObjectId, dataSetId: ObjectId, configuration: Map[String, JsValue])(implicit ctx: DBAccessContext): Fox[Unit] = { for { - _ <- UserSQLDAO.assertUpdateAccess(userId) + _ <- UserDAO.assertUpdateAccess(userId) _ <- run( sqlu"""insert into webknossos.user_dataSetConfigurations(_user, _dataSet, configuration) values ('#${sanitize(configuration.toString)}', ${userId} and _dataSet = ${dataSetId})""") diff --git a/app/models/user/UserService.scala b/app/models/user/UserService.scala index 9df142a9ca..efee43239f 100755 --- a/app/models/user/UserService.scala +++ b/app/models/user/UserService.scala @@ -9,7 +9,7 @@ import com.scalableminds.util.accesscontext.{DBAccessContext, GlobalAccessContex import com.scalableminds.util.security.SCrypt import com.scalableminds.util.security.SCrypt._ import com.scalableminds.util.tools.{Fox, FoxImplicits} -import models.binary.DataSetSQLDAO +import models.binary.DataSetDAO import models.configuration.{DataSetConfiguration, UserConfiguration} import models.team._ import oxalis.mail.DefaultMails @@ -24,7 +24,7 @@ import utils.ObjectId import scala.concurrent.Future -object UserService extends FoxImplicits with IdentityService[UserSQL] { +object UserService extends FoxImplicits with IdentityService[User] { lazy val Mailer = Akka.system(play.api.Play.current).actorSelection("/user/mailActor") @@ -34,32 +34,32 @@ object UserService extends FoxImplicits with IdentityService[UserSQL] { val tokenDAO = WebknossosSilhouette.environment.tokenDAO def defaultUser = { - UserSQLDAO.findOneByEmail(defaultUserEmail)(GlobalAccessContext) + UserDAO.findOneByEmail(defaultUserEmail)(GlobalAccessContext) } def findByTeams(teams: List[ObjectId])(implicit ctx: DBAccessContext) = { - UserSQLDAO.findAllByTeams(teams) + UserDAO.findAllByTeams(teams) } - def findOneById(userId: ObjectId, useCache: Boolean)(implicit ctx: DBAccessContext): Fox[UserSQL] = { + def findOneById(userId: ObjectId, useCache: Boolean)(implicit ctx: DBAccessContext): Fox[User] = { if (useCache) UserCache.findUser(userId) else - UserCache.store(userId, UserSQLDAO.findOne(userId)) + UserCache.store(userId, UserDAO.findOne(userId)) } def logActivity(_user: ObjectId, lastActivity: Long) = { - UserSQLDAO.updateLastActivity(_user, lastActivity)(GlobalAccessContext) + UserDAO.updateLastActivity(_user, lastActivity)(GlobalAccessContext) } def insert(_organization: ObjectId, email: String, firstName: String, - lastName: String, password: String, isActive: Boolean, teamRole: Boolean = false, loginInfo: LoginInfo, passwordInfo: PasswordInfo, isAdmin: Boolean = false): Fox[UserSQL] = { + lastName: String, password: String, isActive: Boolean, teamRole: Boolean = false, loginInfo: LoginInfo, passwordInfo: PasswordInfo, isAdmin: Boolean = false): Fox[User] = { implicit val ctx = GlobalAccessContext for { - organizationTeamId <- OrganizationSQLDAO.findOne(_organization).flatMap(_.organizationTeamId).toFox - orgTeam <- TeamSQLDAO.findOne(organizationTeamId) + organizationTeamId <- OrganizationDAO.findOne(_organization).flatMap(_.organizationTeamId).toFox + orgTeam <- TeamDAO.findOne(organizationTeamId) teamMemberships = List(TeamMembershipSQL(orgTeam._id, teamRole)) - user = UserSQL( + user = User( ObjectId.generate, _organization, email, @@ -74,64 +74,64 @@ object UserService extends FoxImplicits with IdentityService[UserSQL] { isSuperUser = false, isDeactivated = !isActive ) - _ <- UserSQLDAO.insertOne(user) - _ <- Fox.combined(teamMemberships.map(UserTeamRolesSQLDAO.insertTeamMembership(user._id, _))) + _ <- UserDAO.insertOne(user) + _ <- Fox.combined(teamMemberships.map(UserTeamRolesDAO.insertTeamMembership(user._id, _))) } yield user } def update( - user: UserSQL, + user: User, firstName: String, lastName: String, email: String, activated: Boolean, isAdmin: Boolean, teamMemberships: List[TeamMembershipSQL], - experiences: Map[String, Int])(implicit ctx: DBAccessContext): Fox[UserSQL] = { + experiences: Map[String, Int])(implicit ctx: DBAccessContext): Fox[User] = { if (user.isDeactivated && activated) { Mailer ! Send(DefaultMails.activatedMail(user.name, user.email)) } for { - _ <- UserSQLDAO.updateValues(user._id, firstName, lastName, email, isAdmin, isDeactivated = !activated) - _ <- UserTeamRolesSQLDAO.updateTeamMembershipsForUser(user._id, teamMemberships) - _ <- UserExperiencesSQLDAO.updateExperiencesForUser(user._id, experiences) + _ <- UserDAO.updateValues(user._id, firstName, lastName, email, isAdmin, isDeactivated = !activated) + _ <- UserTeamRolesDAO.updateTeamMembershipsForUser(user._id, teamMemberships) + _ <- UserExperiencesDAO.updateExperiencesForUser(user._id, experiences) _ = UserCache.invalidateUser(user._id) _ <- if (user.email == email) Fox.successful(()) else WebknossosSilhouette.environment.tokenDAO.updateEmail(user.email, email) - updated <- UserSQLDAO.findOne(user._id) + updated <- UserDAO.findOne(user._id) } yield updated } def changePasswordInfo(loginInfo: LoginInfo, passwordInfo: PasswordInfo) = { for { user <- findOneByEmail(loginInfo.providerKey) - _ <- UserSQLDAO.updatePasswordInfo(user._id, passwordInfo)(GlobalAccessContext) + _ <- UserDAO.updatePasswordInfo(user._id, passwordInfo)(GlobalAccessContext) } yield { passwordInfo } } - def findOneByEmail(email: String): Fox[UserSQL] = { - UserSQLDAO.findOneByEmail(email)(GlobalAccessContext) + def findOneByEmail(email: String): Fox[User] = { + UserDAO.findOneByEmail(email)(GlobalAccessContext) } - def updateUserConfiguration(user: UserSQL, configuration: UserConfiguration)(implicit ctx: DBAccessContext) = { - UserSQLDAO.updateUserConfiguration(user._id, configuration).map { + def updateUserConfiguration(user: User, configuration: UserConfiguration)(implicit ctx: DBAccessContext) = { + UserDAO.updateUserConfiguration(user._id, configuration).map { result => UserCache.invalidateUser(user._id) result } } - def updateDataSetConfiguration(user: UserSQL, dataSetName: String, configuration: DataSetConfiguration)(implicit ctx: DBAccessContext) = + def updateDataSetConfiguration(user: User, dataSetName: String, configuration: DataSetConfiguration)(implicit ctx: DBAccessContext) = for { - dataSet <- DataSetSQLDAO.findOneByName(dataSetName) - _ <- UserDataSetConfigurationSQLDAO.updateDatasetConfigurationForUserAndDataset(user._id, dataSet._id, configuration.configuration) + dataSet <- DataSetDAO.findOneByName(dataSetName) + _ <- UserDataSetConfigurationDAO.updateDatasetConfigurationForUserAndDataset(user._id, dataSet._id, configuration.configuration) _ = UserCache.invalidateUser(user._id) } yield () - def retrieve(loginInfo: LoginInfo): Future[Option[UserSQL]] = - UserSQLDAO.findOneByEmail(loginInfo.providerKey)(GlobalAccessContext).futureBox.map(_.toOption) + def retrieve(loginInfo: LoginInfo): Future[Option[User]] = + UserDAO.findOneByEmail(loginInfo.providerKey)(GlobalAccessContext).futureBox.map(_.toOption) def createLoginInfo(email: String): LoginInfo = { LoginInfo(CredentialsProvider.ID, email) diff --git a/app/models/user/time/TimeSpan.scala b/app/models/user/time/TimeSpan.scala index 6ed47c2bf9..c20962f7b1 100755 --- a/app/models/user/time/TimeSpan.scala +++ b/app/models/user/time/TimeSpan.scala @@ -3,7 +3,7 @@ package models.user.time import com.scalableminds.util.accesscontext.DBAccessContext import com.scalableminds.util.tools.{Fox, FoxImplicits} import com.scalableminds.webknossos.schema.Tables._ -import models.annotation.AnnotationSQL +import models.annotation.Annotation import org.joda.time.DateTime import play.api.Play.current import play.api.i18n.Messages @@ -21,7 +21,7 @@ case class TimeSpanRequest(users: List[String], start: Long, end: Long) object TimeSpanRequest { implicit val timeSpanRequest = Json.format[TimeSpanRequest] } -case class TimeSpanSQL( +case class TimeSpan( _id: ObjectId, _user: ObjectId, _annotation: Option[ObjectId], @@ -41,34 +41,34 @@ case class TimeSpanSQL( } } -object TimeSpanSQL { +object TimeSpan { - def groupByMonth(timeSpan: TimeSpanSQL) = { + def groupByMonth(timeSpan: TimeSpan) = { Month(timeSpan.createdAsDateTime.getMonthOfYear, timeSpan.createdAsDateTime.getYear) } - def groupByWeek(timeSpan: TimeSpanSQL) = { + def groupByWeek(timeSpan: TimeSpan) = { Week(timeSpan.createdAsDateTime.getWeekOfWeekyear, timeSpan.createdAsDateTime.getWeekyear) } - def groupByDay(timeSpan: TimeSpanSQL) = { + def groupByDay(timeSpan: TimeSpan) = { Day(timeSpan.createdAsDateTime.getDayOfMonth, timeSpan.createdAsDateTime.getMonthOfYear, timeSpan.createdAsDateTime.getYear) } def createFrom(start: Long, end: Long, _user: ObjectId, _annotation: Option[ObjectId]) = - TimeSpanSQL(ObjectId.generate, _user, _annotation, time = end - start, lastUpdate = end, created = start) + TimeSpan(ObjectId.generate, _user, _annotation, time = end - start, lastUpdate = end, created = start) } -object TimeSpanSQLDAO extends SQLDAO[TimeSpanSQL, TimespansRow, Timespans] { +object TimeSpanDAO extends SQLDAO[TimeSpan, TimespansRow, Timespans] { val collection = Timespans val MAX_TIMESTAMP = 253370761200000L def idColumn(x: Timespans): Rep[String] = x._Id def isDeletedColumn(x: Timespans): Rep[Boolean] = x.isdeleted - def parse(r: TimespansRow): Fox[TimeSpanSQL] = - Fox.successful(TimeSpanSQL( + def parse(r: TimespansRow): Fox[TimeSpan] = + Fox.successful(TimeSpan( ObjectId(r._Id), ObjectId(r._User), r._Annotation.map(ObjectId(_)), @@ -79,7 +79,7 @@ object TimeSpanSQLDAO extends SQLDAO[TimeSpanSQL, TimespansRow, Timespans] { r.isdeleted )) - def findAllByUser(userId: ObjectId, start: Option[Long], end: Option[Long]): Fox[List[TimeSpanSQL]] = + def findAllByUser(userId: ObjectId, start: Option[Long], end: Option[Long]): Fox[List[TimeSpan]] = for { r <- run(Timespans.filter(r => notdel(r) && r._User === userId.id && (r.created >= new java.sql.Timestamp(start.getOrElse(0))) && r.created <= new java.sql.Timestamp(end.getOrElse(MAX_TIMESTAMP))).result) parsed <- Fox.combined(r.toList.map(parse)) @@ -129,26 +129,26 @@ object TimeSpanSQLDAO extends SQLDAO[TimeSpanSQL, TimespansRow, Timespans] { Json.toJson(tuples.map(formatTimespanTuple)) } - def findAllByAnnotation(annotationId: ObjectId, start: Option[Long], end: Option[Long]): Fox[List[TimeSpanSQL]] = + def findAllByAnnotation(annotationId: ObjectId, start: Option[Long], end: Option[Long]): Fox[List[TimeSpan]] = for { r <- run(Timespans.filter(r => notdel(r) && r._Annotation === annotationId.id && (r.created >= new java.sql.Timestamp(start.getOrElse(0))) && r.created <= new java.sql.Timestamp(end.getOrElse(MAX_TIMESTAMP))).result) parsed <- Fox.combined(r.toList.map(parse)) } yield parsed - def findAll(start: Option[Long], end: Option[Long]): Fox[List[TimeSpanSQL]] = + def findAll(start: Option[Long], end: Option[Long]): Fox[List[TimeSpan]] = for { r <- run(Timespans.filter(r => notdel(r) && (r.created >= new java.sql.Timestamp(start.getOrElse(0))) && r.created <= new java.sql.Timestamp(end.getOrElse(MAX_TIMESTAMP))).result) parsed <- Fox.combined(r.toList.map(parse)) } yield parsed - def insertOne(t: TimeSpanSQL)(implicit ctx: DBAccessContext): Fox[Unit] = { + def insertOne(t: TimeSpan)(implicit ctx: DBAccessContext): Fox[Unit] = { for { r <- run(sqlu"""insert into webknossos.timespans(_id, _user, _annotation, time, lastUpdate, numberOfUpdates, created, isDeleted) values(${t._id.id}, ${t._user.id}, ${t._annotation.map(_.id)}, ${t.time}, ${new java.sql.Timestamp(t.lastUpdate)}, ${t.numberOfUpdates}, ${new java.sql.Timestamp(t.created)}, ${t.isDeleted})""") } yield () } - def updateOne(t: TimeSpanSQL)(implicit ctx: DBAccessContext): Fox[Unit] = { + def updateOne(t: TimeSpan)(implicit ctx: DBAccessContext): Fox[Unit] = { for { //note that t.created is skipped _ <- assertUpdateAccess(t._id) ?~> "FAILED: TimeSpanSQLDAO.assertUpdateAccess" r <- run(sqlu"""update webknossos.timespans diff --git a/app/models/user/time/TimeSpanService.scala b/app/models/user/time/TimeSpanService.scala index 6763796393..e23f945bea 100644 --- a/app/models/user/time/TimeSpanService.scala +++ b/app/models/user/time/TimeSpanService.scala @@ -5,9 +5,9 @@ import com.scalableminds.util.accesscontext.{DBAccessContext, GlobalAccessContex import com.scalableminds.util.tools.{Fox, FoxImplicits} import com.typesafe.scalalogging.LazyLogging import models.annotation._ -import models.task.TaskSQLDAO -import models.user.UserSQL -import models.team.OrganizationSQLDAO +import models.task.TaskDAO +import models.user.User +import models.team.OrganizationDAO import net.liftweb.common.Full import oxalis.mail.DefaultMails import oxalis.thirdparty.BrainTracing.Mailer @@ -23,22 +23,22 @@ object TimeSpanService extends FoxImplicits with LazyLogging { private val MaxTracingPause = Play.current.configuration.getInt("oxalis.user.time.tracingPauseInSeconds").getOrElse(60).seconds.toMillis - def logUserInteraction(user: UserSQL, annotation: AnnotationSQL)(implicit ctx: DBAccessContext): Fox[Unit] = { + def logUserInteraction(user: User, annotation: Annotation)(implicit ctx: DBAccessContext): Fox[Unit] = { val timestamp = System.currentTimeMillis logUserInteraction(Seq(timestamp), user, annotation) } - def logUserInteraction(timestamps: Seq[Long], user: UserSQL, annotation: AnnotationSQL)(implicit ctx: DBAccessContext): Fox[Unit] = + def logUserInteraction(timestamps: Seq[Long], user: User, annotation: Annotation)(implicit ctx: DBAccessContext): Fox[Unit] = trackTime(timestamps, user._id, annotation) def loggedTimeOfUser[T]( - user: UserSQL, - groupingF: TimeSpanSQL => T, - start: Option[Long] = None, - end: Option[Long] = None)(implicit ctx: DBAccessContext): Fox[Map[T, Duration]] = + user: User, + groupingF: TimeSpan => T, + start: Option[Long] = None, + end: Option[Long] = None)(implicit ctx: DBAccessContext): Fox[Map[T, Duration]] = for { - timeTrackingOpt <- TimeSpanSQLDAO.findAllByUser(user._id, start, end).futureBox + timeTrackingOpt <- TimeSpanDAO.findAllByUser(user._id, start, end).futureBox } yield { timeTrackingOpt match { case Full(timeSpans) => @@ -49,13 +49,13 @@ object TimeSpanService extends FoxImplicits with LazyLogging { } def loggedTimeOfAnnotation[T]( - annotationId: ObjectId, - groupingF: TimeSpanSQL => T, - start: Option[Long] = None, - end: Option[Long] = None)(implicit ctx: DBAccessContext): Fox[Map[T, Duration]] = + annotationId: ObjectId, + groupingF: TimeSpan => T, + start: Option[Long] = None, + end: Option[Long] = None)(implicit ctx: DBAccessContext): Fox[Map[T, Duration]] = for { - timeTrackingOpt <- TimeSpanSQLDAO.findAllByAnnotation(annotationId, start, end).futureBox + timeTrackingOpt <- TimeSpanDAO.findAllByAnnotation(annotationId, start, end).futureBox } yield { timeTrackingOpt match { case Full(timeSpans) => @@ -65,9 +65,9 @@ object TimeSpanService extends FoxImplicits with LazyLogging { } } - def totalTimeOfUser[T](user: UserSQL, start: Option[Long], end: Option[Long])(implicit ctx: DBAccessContext): Fox[Duration] = + def totalTimeOfUser[T](user: User, start: Option[Long], end: Option[Long])(implicit ctx: DBAccessContext): Fox[Duration] = for { - timeTrackingOpt <- TimeSpanSQLDAO.findAllByUser(user._id, start, end).futureBox + timeTrackingOpt <- TimeSpanDAO.findAllByUser(user._id, start, end).futureBox } yield { timeTrackingOpt match { case Full(timeSpans) => @@ -77,9 +77,9 @@ object TimeSpanService extends FoxImplicits with LazyLogging { } } - def loggedTimePerInterval[T](groupingF: TimeSpanSQL => T, start: Option[Long] = None, end: Option[Long] = None): Fox[Map[T, Duration]] = + def loggedTimePerInterval[T](groupingF: TimeSpan => T, start: Option[Long] = None, end: Option[Long] = None): Fox[Map[T, Duration]] = for { - timeTrackingOpt <- TimeSpanSQLDAO.findAll(start, end).futureBox + timeTrackingOpt <- TimeSpanDAO.findAll(start, end).futureBox } yield { timeTrackingOpt match { case Full(timeSpans) => @@ -91,23 +91,23 @@ object TimeSpanService extends FoxImplicits with LazyLogging { - private val lastUserActivities = mutable.HashMap.empty[ObjectId, TimeSpanSQL] + private val lastUserActivities = mutable.HashMap.empty[ObjectId, TimeSpan] - private def trackTime(timestamps: Seq[Long], _user: ObjectId, _annotation: AnnotationSQL)(implicit ctx: DBAccessContext) = { + private def trackTime(timestamps: Seq[Long], _user: ObjectId, _annotation: Annotation)(implicit ctx: DBAccessContext) = { // Only if the annotation belongs to the user, we are going to log the time on the annotation val annotation = if (_annotation._user == _user) Some(_annotation) else None val start = timestamps.head - var timeSpansToInsert: List[TimeSpanSQL] = List() - var timeSpansToUpdate: List[(TimeSpanSQL, Long)] = List() + var timeSpansToInsert: List[TimeSpan] = List() + var timeSpansToUpdate: List[(TimeSpan, Long)] = List() - def createNewTimeSpan(timestamp: Long, _user: ObjectId, annotation: Option[AnnotationSQL]) = { - val timeSpan = TimeSpanSQL.createFrom(timestamp, timestamp, _user, annotation.map(_._id)) + def createNewTimeSpan(timestamp: Long, _user: ObjectId, annotation: Option[Annotation]) = { + val timeSpan = TimeSpan.createFrom(timestamp, timestamp, _user, annotation.map(_._id)) timeSpansToInsert = timeSpan :: timeSpansToInsert timeSpan } - def updateTimeSpan(timeSpan: TimeSpanSQL, timestamp: Long) = { + def updateTimeSpan(timeSpan: TimeSpan, timestamp: Long) = { timeSpansToUpdate = (timeSpan, timestamp) :: timeSpansToUpdate val duration = timestamp - timeSpan.lastUpdate @@ -141,12 +141,12 @@ object TimeSpanService extends FoxImplicits with LazyLogging { flushToDb(timeSpansToInsert, timeSpansToUpdate)(ctx) } - private def isNotInterrupted(current: Long, last: TimeSpanSQL) = { + private def isNotInterrupted(current: Long, last: TimeSpan) = { val duration = current - last.lastUpdate duration >= 0 && duration < MaxTracingPause } - private def belongsToSameTracing( last: TimeSpanSQL, annotation: Option[AnnotationSQL]) = + private def belongsToSameTracing(last: TimeSpan, annotation: Option[Annotation]) = last._annotation == annotation.map(_.id) private def logTimeToAnnotation( @@ -155,14 +155,14 @@ object TimeSpanService extends FoxImplicits with LazyLogging { // Log time to annotation annotation match { case Some(a: ObjectId) => - AnnotationSQLDAO.logTime(a, duration)(GlobalAccessContext) ?~> "FAILED: AnnotationService.logTime" + AnnotationDAO.logTime(a, duration)(GlobalAccessContext) ?~> "FAILED: AnnotationService.logTime" case _ => Fox.successful(()) // do nothing, this is not a stored annotation } } - def signalOverTime(time: Long, annotationOpt: Option[AnnotationSQL])(implicit ctx: DBAccessContext): Fox[_] = { + def signalOverTime(time: Long, annotationOpt: Option[Annotation])(implicit ctx: DBAccessContext): Fox[_] = { for { annotation <- annotationOpt.toFox user <- annotation.user @@ -185,11 +185,11 @@ object TimeSpanService extends FoxImplicits with LazyLogging { private def logTimeToTask( duration: Long, - annotation: Option[AnnotationSQL]) = { + annotation: Option[Annotation]) = { annotation.flatMap(_._task) match { case Some(taskId) => for { - _ <- TaskSQLDAO.logTime(taskId, duration)(GlobalAccessContext) ?~> "FAILED: TaskSQLDAO.logTime" + _ <- TaskDAO.logTime(taskId, duration)(GlobalAccessContext) ?~> "FAILED: TaskSQLDAO.logTime" _ <- signalOverTime(duration, annotation)(GlobalAccessContext).futureBox //signalOverTime is expected to fail in some cases, hence the .futureBox } yield {} case _ => @@ -200,18 +200,18 @@ object TimeSpanService extends FoxImplicits with LazyLogging { // We intentionally return a Fox[Option] here, since the calling for-comprehension expects an Option[Annotation]. In case // None is passed in as "annotation", we want to pass this None on as Fox.successful(None) and not break the for-comprehension // by returning Fox.empty. - private def getAnnotation(annotation: Option[ObjectId])(implicit ctx: DBAccessContext): Fox[Option[AnnotationSQL]] = { + private def getAnnotation(annotation: Option[ObjectId])(implicit ctx: DBAccessContext): Fox[Option[Annotation]] = { annotation match { case Some(annotationId) => - AnnotationSQLDAO.findOne(annotationId).map(Some(_)) + AnnotationDAO.findOne(annotationId).map(Some(_)) case _ => Fox.successful(None) } } - private def flushToDb(timespansToInsert: List[TimeSpanSQL], timespansToUpdate: List[(TimeSpanSQL, Long)])(implicit ctx: DBAccessContext) = { + private def flushToDb(timespansToInsert: List[TimeSpan], timespansToUpdate: List[(TimeSpan, Long)])(implicit ctx: DBAccessContext) = { val updateResult = for { - _ <- Fox.serialCombined(timespansToInsert)(t => TimeSpanSQLDAO.insertOne(t)) + _ <- Fox.serialCombined(timespansToInsert)(t => TimeSpanDAO.insertOne(t)) _ <- Fox.serialCombined(timespansToUpdate)(t => updateTimeSpanInDb(t._1, t._2)) } yield () @@ -223,12 +223,12 @@ object TimeSpanService extends FoxImplicits with LazyLogging { updateResult } - private def updateTimeSpanInDb(timeSpan: TimeSpanSQL, timestamp: Long)(implicit ctx: DBAccessContext) = { + private def updateTimeSpanInDb(timeSpan: TimeSpan, timestamp: Long)(implicit ctx: DBAccessContext) = { val duration = timestamp - timeSpan.lastUpdate val updated = timeSpan.addTime(duration, timestamp) for { - _ <- TimeSpanSQLDAO.updateOne(updated)(ctx) ?~> "FAILED: TimeSpanDAO.update" + _ <- TimeSpanDAO.updateOne(updated)(ctx) ?~> "FAILED: TimeSpanDAO.update" _ <- logTimeToAnnotation(duration, updated._annotation) ?~> "FAILED: TimeSpanService.logTimeToAnnotation" annotation <- getAnnotation(updated._annotation) _ <- logTimeToTask(duration, annotation) ?~> "FAILED: TimeSpanService.logTimeToTask" diff --git a/app/oxalis/mail/DefaultMails.scala b/app/oxalis/mail/DefaultMails.scala index b081b49557..58ec6e1a9d 100755 --- a/app/oxalis/mail/DefaultMails.scala +++ b/app/oxalis/mail/DefaultMails.scala @@ -1,8 +1,8 @@ package oxalis.mail import com.scalableminds.util.mail.Mail -import models.user.UserSQL -import models.team.OrganizationSQL +import models.user.User +import models.team.Organization import play.api.i18n.Messages import views._ @@ -23,7 +23,7 @@ object DefaultMails { val newOrganizationMailingList = conf.getString("oxalis.newOrganizationMailingList").getOrElse("") - def registerAdminNotifyerMail(user: UserSQL, email: String, brainDBResult: String, organization: OrganizationSQL) = + def registerAdminNotifyerMail(user: User, email: String, brainDBResult: String, organization: Organization) = Mail( from = email, headers = Map("Sender" -> defaultFrom), @@ -31,7 +31,7 @@ object DefaultMails { bodyText = html.mail.registerAdminNotify(user, brainDBResult, uri).body, recipients = List(organization.newUserMailingList)) - def overLimitMail(user: UserSQL, projectName: String, taskId: String, annotationId: String, organization: OrganizationSQL) = + def overLimitMail(user: User, projectName: String, taskId: String, annotationId: String, organization: Organization) = Mail( from = defaultFrom, subject = s"Time limit reached. ${user.abreviatedName} in $projectName", diff --git a/app/oxalis/security/BearerTokenAuthenticatorDAO.scala b/app/oxalis/security/BearerTokenAuthenticatorDAO.scala index 3595562edd..de50c3c415 100644 --- a/app/oxalis/security/BearerTokenAuthenticatorDAO.scala +++ b/app/oxalis/security/BearerTokenAuthenticatorDAO.scala @@ -17,15 +17,15 @@ import utils.{ObjectId, SQLDAO} import scala.concurrent.Future import scala.concurrent.duration._ -case class TokenSQL(_id: ObjectId, - value: String, - loginInfo: LoginInfo, - lastUsedDateTime: DateTime, - expirationDateTime: DateTime, - idleTimeout: Option[FiniteDuration], - tokenType: TokenType, - created: Long = System.currentTimeMillis(), - isDeleted: Boolean = false) { +case class Token(_id: ObjectId, + value: String, + loginInfo: LoginInfo, + lastUsedDateTime: DateTime, + expirationDateTime: DateTime, + idleTimeout: Option[FiniteDuration], + tokenType: TokenType, + created: Long = System.currentTimeMillis(), + isDeleted: Boolean = false) { def toBearerTokenAuthenticator: Fox[BearerTokenAuthenticator] = { Fox.successful(BearerTokenAuthenticator( @@ -38,9 +38,9 @@ case class TokenSQL(_id: ObjectId, } } -object TokenSQL { - def fromBearerTokenAuthenticator(b: BearerTokenAuthenticator, tokenType: TokenType): Fox[TokenSQL] = { - Fox.successful(TokenSQL( +object Token { + def fromBearerTokenAuthenticator(b: BearerTokenAuthenticator, tokenType: TokenType): Fox[Token] = { + Fox.successful(Token( ObjectId.generate, b.id, b.loginInfo, @@ -54,17 +54,17 @@ object TokenSQL { } } -object TokenSQLDAO extends SQLDAO[TokenSQL, TokensRow, Tokens] { +object TokenDAO extends SQLDAO[Token, TokensRow, Tokens] { val collection = Tokens def idColumn(x: Tokens): Rep[String] = x._Id def isDeletedColumn(x: Tokens): Rep[Boolean] = x.isdeleted - def parse(r: TokensRow): Fox[TokenSQL] = + def parse(r: TokensRow): Fox[Token] = for { tokenType <- TokenType.fromString(r.tokentype).toFox } yield { - TokenSQL( + Token( ObjectId(r._Id), r.value, LoginInfo(r.logininfoProviderid, r.logininfoProviderkey), @@ -77,14 +77,14 @@ object TokenSQLDAO extends SQLDAO[TokenSQL, TokensRow, Tokens] { ) } - def findOneByValue(value: String)(implicit ctx: DBAccessContext): Fox[TokenSQL] = + def findOneByValue(value: String)(implicit ctx: DBAccessContext): Fox[Token] = for { rOpt <- run(Tokens.filter(r => notdel(r) && r.value === value).result.headOption) r <- rOpt.toFox parsed <- parse(r) } yield parsed - def findOneByLoginInfo(providerID: String, providerKey: String, tokenType: TokenType)(implicit ctx: DBAccessContext): Fox[TokenSQL] = + def findOneByLoginInfo(providerID: String, providerKey: String, tokenType: TokenType)(implicit ctx: DBAccessContext): Fox[Token] = for { rOpt <- run(Tokens.filter(r => notdel(r) && r.logininfoProviderid === providerID && r.logininfoProviderkey === providerKey && r.tokentype === tokenType.toString).result.headOption) r <- rOpt.toFox @@ -92,7 +92,7 @@ object TokenSQLDAO extends SQLDAO[TokenSQL, TokensRow, Tokens] { } yield parsed - def insertOne(t: TokenSQL)(implicit ctx: DBAccessContext) = + def insertOne(t: Token)(implicit ctx: DBAccessContext) = for { _ <- run(sqlu"""insert into webknossos.tokens(_id, value, loginInfo_providerID, loginInfo_providerKey, lastUsedDateTime, expirationDateTime, idleTimeout, tokenType, created, isDeleted) values(${t._id.id}, ${t.value}, '#${t.loginInfo.providerID}', ${t.loginInfo.providerKey}, ${new java.sql.Timestamp(t.lastUsedDateTime.getMillis)}, @@ -142,29 +142,29 @@ class BearerTokenAuthenticatorDAO extends AuthenticatorDAO[BearerTokenAuthentica override def update(newAuthenticator: BearerTokenAuthenticator): Future[BearerTokenAuthenticator] = { implicit val ctx = GlobalAccessContext (for { - oldAuthenticatorSQL <- TokenSQLDAO.findOneByLoginInfo(newAuthenticator.loginInfo.providerID, newAuthenticator.loginInfo.providerKey, TokenType.Authentication) - _ <- TokenSQLDAO.updateValues(oldAuthenticatorSQL._id, newAuthenticator.id, newAuthenticator.lastUsedDateTime, newAuthenticator.expirationDateTime, newAuthenticator.idleTimeout) + oldAuthenticatorSQL <- TokenDAO.findOneByLoginInfo(newAuthenticator.loginInfo.providerID, newAuthenticator.loginInfo.providerKey, TokenType.Authentication) + _ <- TokenDAO.updateValues(oldAuthenticatorSQL._id, newAuthenticator.id, newAuthenticator.lastUsedDateTime, newAuthenticator.expirationDateTime, newAuthenticator.idleTimeout) updated <- findOneByValue(newAuthenticator.id) } yield updated).toFutureOrThrowException("Could not update Token. Throwing exception because update cannot return a box, as defined by Silhouette trait AuthenticatorDAO") } override def remove(value: String): Future[Unit] = for { - _ <- TokenSQLDAO.deleteOneByValue(value)(GlobalAccessContext).futureBox + _ <- TokenDAO.deleteOneByValue(value)(GlobalAccessContext).futureBox } yield () /* custom functions */ def findOneByValue(value: String)(implicit ctx: DBAccessContext): Fox[BearerTokenAuthenticator] = { for { - tokenSQL <- TokenSQLDAO.findOneByValue(value) + tokenSQL <- TokenDAO.findOneByValue(value) tokenAuthenticator <- tokenSQL.toBearerTokenAuthenticator } yield tokenAuthenticator } def findOneByLoginInfo(loginInfo: LoginInfo, tokenType: TokenType)(implicit ctx: DBAccessContext): Future[Option[BearerTokenAuthenticator]] = (for { - tokenSQL <- TokenSQLDAO.findOneByLoginInfo(loginInfo.providerID, loginInfo.providerKey, tokenType) + tokenSQL <- TokenDAO.findOneByLoginInfo(loginInfo.providerID, loginInfo.providerKey, tokenType) tokenAuthenticator <- tokenSQL.toBearerTokenAuthenticator } yield tokenAuthenticator).toFutureOption @@ -180,16 +180,16 @@ class BearerTokenAuthenticatorDAO extends AuthenticatorDAO[BearerTokenAuthentica private def insert(authenticator: BearerTokenAuthenticator, tokenType: TokenType)(implicit ctx: DBAccessContext): Fox[Unit] = for { - tokenSQL <- TokenSQL.fromBearerTokenAuthenticator(authenticator, tokenType) - _ <- TokenSQLDAO.insertOne(tokenSQL) + tokenSQL <- Token.fromBearerTokenAuthenticator(authenticator, tokenType) + _ <- TokenDAO.insertOne(tokenSQL) } yield () def deleteAllExpired(implicit ctx: DBAccessContext): Fox[Unit] = - TokenSQLDAO.deleteAllExpired + TokenDAO.deleteAllExpired def updateEmail(oldEmail: String, newEmail: String)(implicit ctx: DBAccessContext): Fox[Unit] = { for { - _ <- TokenSQLDAO.updateEmail(oldEmail, newEmail) + _ <- TokenDAO.updateEmail(oldEmail, newEmail) } yield () } } diff --git a/app/oxalis/security/Environment.scala b/app/oxalis/security/Environment.scala index 8f66e7bb09..b95c4e3025 100644 --- a/app/oxalis/security/Environment.scala +++ b/app/oxalis/security/Environment.scala @@ -5,7 +5,7 @@ import com.mohiva.play.silhouette.api.util.Clock import com.mohiva.play.silhouette.api.{Environment, EventBus, RequestProvider} import com.mohiva.play.silhouette.impl.authenticators.{BearerTokenAuthenticatorSettings, CookieAuthenticatorSettings} import com.mohiva.play.silhouette.impl.util.{DefaultFingerprintGenerator, SecureRandomIDGenerator} -import models.user.{UserSQL, UserService} +import models.user.{User, UserService} import net.ceedubs.ficus.Ficus._ import net.ceedubs.ficus.readers.ArbitraryTypeReader._ import play.api.Configuration @@ -14,7 +14,7 @@ import scala.concurrent.ExecutionContext import scala.concurrent.ExecutionContext.Implicits.global -class WebknossosEnvironment @Inject()(configuration: Configuration)(implicit val executionContext: ExecutionContext) extends Environment[UserSQL, CombinedAuthenticator] { +class WebknossosEnvironment @Inject()(configuration: Configuration)(implicit val executionContext: ExecutionContext) extends Environment[User, CombinedAuthenticator] { val eventBusObject = EventBus() val cookieSettings = configuration.underlying.as[CookieAuthenticatorSettings]("silhouette.cookieAuthenticator") val tokenSettings = configuration.underlying.as[BearerTokenAuthenticatorSettings]("silhouette.tokenAuthenticator") @@ -24,7 +24,7 @@ class WebknossosEnvironment @Inject()(configuration: Configuration)(implicit val val combinedAuthenticatorService = CombinedAuthenticatorService(cookieSettings, tokenSettings, tokenDAO, fingerprintGenerator, idGenerator, Clock()) - override def identityService: IdentityService[UserSQL] = UserService + override def identityService: IdentityService[User] = UserService override def authenticatorService: AuthenticatorService[CombinedAuthenticator] = combinedAuthenticatorService diff --git a/app/oxalis/security/Secured.scala b/app/oxalis/security/Secured.scala index f9975623f6..9989a86d95 100755 --- a/app/oxalis/security/Secured.scala +++ b/app/oxalis/security/Secured.scala @@ -3,13 +3,13 @@ package oxalis.security import play.api.i18n._ import play.api.Play import com.scalableminds.util.tools.FoxImplicits -import models.user.{UserSQL} +import models.user.{User} import play.api.Play.current import play.api.libs.concurrent.Execution.Implicits._ import com.mohiva.play.silhouette.api.{Environment, Silhouette} -object WebknossosSilhouette extends Silhouette[UserSQL, CombinedAuthenticator] with FoxImplicits{ +object WebknossosSilhouette extends Silhouette[User, CombinedAuthenticator] with FoxImplicits{ val config = Play.configuration val lang = new DefaultLangs(config) @@ -17,7 +17,7 @@ object WebknossosSilhouette extends Silhouette[UserSQL, CombinedAuthenticator] w val environment = new WebknossosEnvironment(config) - override protected def env: Environment[UserSQL, CombinedAuthenticator] = environment + override protected def env: Environment[User, CombinedAuthenticator] = environment override def messagesApi: MessagesApi = new DefaultMessagesApi(messagesAPIEnvironment, config, lang) } diff --git a/app/oxalis/security/URLSharing.scala b/app/oxalis/security/URLSharing.scala index 3cb2b7efec..4ae9c5ae8a 100644 --- a/app/oxalis/security/URLSharing.scala +++ b/app/oxalis/security/URLSharing.scala @@ -6,7 +6,7 @@ package oxalis.security import java.security.SecureRandom import com.scalableminds.util.accesscontext.{DBAccessContext, DBAccessContextPayload} -import models.user.UserSQL +import models.user.User case class SharingTokenContainer(sharingToken: String) extends DBAccessContextPayload @@ -17,7 +17,7 @@ object URLSharing { def fallbackTokenAccessContext(sharingToken: Option[String])(implicit ctx: DBAccessContext) = { ctx.data match { - case Some(user: UserSQL) => ctx + case Some(user: User) => ctx case _ => DBAccessContext(sharingToken.map(SharingTokenContainer(_))) } } diff --git a/app/oxalis/security/WebknossosBearerTokenAuthenticatorService.scala b/app/oxalis/security/WebknossosBearerTokenAuthenticatorService.scala index b00e939057..a02ab4d04b 100644 --- a/app/oxalis/security/WebknossosBearerTokenAuthenticatorService.scala +++ b/app/oxalis/security/WebknossosBearerTokenAuthenticatorService.scala @@ -8,7 +8,7 @@ import com.mohiva.play.silhouette.impl.authenticators.BearerTokenAuthenticatorSe import com.mohiva.play.silhouette.impl.authenticators.{BearerTokenAuthenticator, BearerTokenAuthenticatorService, BearerTokenAuthenticatorSettings} import com.scalableminds.util.accesscontext.{DBAccessContext, GlobalAccessContext} import com.scalableminds.util.tools.{Fox, FoxImplicits} -import models.user.{UserSQL, UserService} +import models.user.{User, UserService} import oxalis.security.TokenType.TokenType import play.api.Play.current import play.api.i18n.Messages @@ -65,14 +65,14 @@ class WebknossosBearerTokenAuthenticatorService(settings: BearerTokenAuthenticat tokenId } - def userForToken(tokenValue: String)(implicit ctx: DBAccessContext): Fox[UserSQL] = + def userForToken(tokenValue: String)(implicit ctx: DBAccessContext): Fox[User] = for { tokenAuthenticator <- dao.findOneByValue(tokenValue) ?~> Messages("auth.invalidToken") _ <- (tokenAuthenticator.isValid) ?~> Messages("auth.invalidToken") user <- UserService.findOneByEmail(tokenAuthenticator.loginInfo.providerKey) } yield user - def userForTokenOpt(tokenOpt: Option[String])(implicit ctx: DBAccessContext): Fox[UserSQL] = tokenOpt match { + def userForTokenOpt(tokenOpt: Option[String])(implicit ctx: DBAccessContext): Fox[User] = tokenOpt match { case Some(token) => userForToken(token) case _ => Fox.empty } diff --git a/app/oxalis/thirdparty/BrainTracing.scala b/app/oxalis/thirdparty/BrainTracing.scala index 81ba572735..3610b61e61 100755 --- a/app/oxalis/thirdparty/BrainTracing.scala +++ b/app/oxalis/thirdparty/BrainTracing.scala @@ -2,7 +2,7 @@ package oxalis.thirdparty import com.scalableminds.util.tools.{Fox, FoxImplicits} import com.typesafe.scalalogging.LazyLogging -import models.user.UserSQL +import models.user.User import play.api.Play import play.api.Play.current import play.api.libs.concurrent.Akka @@ -26,13 +26,13 @@ object BrainTracing extends LazyLogging with FoxImplicits { lazy val Mailer = Akka.system(play.api.Play.current).actorSelection("/user/mailActor") - def registerIfNeeded(user: UserSQL): Fox[String] = + def registerIfNeeded(user: User): Fox[String] = for { organization <- user.organization result <- (if (organization.name == "Connectomics department" && isActive) register(user).toFox else Fox.successful("braintracing.none")) } yield result - private def register(user: UserSQL): Future[String] = { + private def register(user: User): Future[String] = { val result = Promise[String]() val brainTracingRequest = WS .url(CREATE_URL) diff --git a/app/oxalis/user/ActivityMonitor.scala b/app/oxalis/user/ActivityMonitor.scala index 9c238ccda9..020dd65d66 100755 --- a/app/oxalis/user/ActivityMonitor.scala +++ b/app/oxalis/user/ActivityMonitor.scala @@ -4,7 +4,7 @@ import akka.actor._ import akka.agent.Agent import com.newrelic.api.agent.NewRelic import com.typesafe.scalalogging.LazyLogging -import models.user.{UserSQL, UserService} +import models.user.{User, UserService} import play.api.libs.concurrent.Execution.Implicits._ import utils.ObjectId @@ -12,7 +12,7 @@ import scala.concurrent.duration._ case object FlushActivities -case class UserActivity(user: UserSQL, time: Long) +case class UserActivity(user: User, time: Long) class ActivityMonitor extends Actor with LazyLogging { implicit val system = context.system diff --git a/app/oxalis/user/UserCache.scala b/app/oxalis/user/UserCache.scala index e8875e9153..95d34ba7e0 100755 --- a/app/oxalis/user/UserCache.scala +++ b/app/oxalis/user/UserCache.scala @@ -2,7 +2,7 @@ package oxalis.user import com.scalableminds.util.accesscontext.GlobalAccessContext import com.scalableminds.util.tools.Fox -import models.user.{UserSQL, UserSQLDAO} +import models.user.{User, UserDAO} import play.api.Play.current import play.api.cache.Cache import utils.ObjectId @@ -16,11 +16,11 @@ object UserCache { def findUser(id: ObjectId) = { Cache.getOrElse(cacheKeyForUser(id), userCacheTimeout) { - UserSQLDAO.findOne(id)(GlobalAccessContext) + UserDAO.findOne(id)(GlobalAccessContext) } } - def store(id: ObjectId, user: Fox[UserSQL]) = { + def store(id: ObjectId, user: Fox[User]) = { Cache.set(cacheKeyForUser(id), user) user } diff --git a/app/oxalis/view/SessionData.scala b/app/oxalis/view/SessionData.scala index 6490cc6b76..c9f7242cb8 100755 --- a/app/oxalis/view/SessionData.scala +++ b/app/oxalis/view/SessionData.scala @@ -1,6 +1,6 @@ package oxalis.view -import models.user.UserSQL +import models.user.User import play.api.mvc.Flash trait FlashMessages{ @@ -21,19 +21,19 @@ trait FlashMessages{ } trait SessionData{ - def userOpt: Option[UserSQL] + def userOpt: Option[User] def flash: Flash } case class UnAuthedSessionData(flash: Flash) extends SessionData { val userOpt = None } -case class AuthedSessionData(user: UserSQL, flash: Flash) extends SessionData { +case class AuthedSessionData(user: User, flash: Flash) extends SessionData { val userOpt = Some(user) } object SessionData{ - def apply(user: Option[UserSQL], flash: Flash) = { + def apply(user: Option[User], flash: Flash) = { user match{ case Some(u) => AuthedSessionData(u, flash) diff --git a/app/utils/SQLHelpers.scala b/app/utils/SQLHelpers.scala index 9b4e2b0f00..fe368b0e09 100644 --- a/app/utils/SQLHelpers.scala +++ b/app/utils/SQLHelpers.scala @@ -8,7 +8,7 @@ import com.newrelic.api.agent.NewRelic import com.scalableminds.util.accesscontext.DBAccessContext import com.scalableminds.util.tools.{Fox, FoxImplicits} import com.typesafe.scalalogging.LazyLogging -import models.user.UserSQL +import models.user.User import net.liftweb.common.Full import oxalis.security.SharingTokenContainer import play.api.i18n.Messages @@ -170,7 +170,7 @@ trait SecuredSQLDAO extends SimpleSQLDAO { def userIdFromCtx(implicit ctx: DBAccessContext): Fox[ObjectId] = { ctx.data match { - case Some(user: UserSQL) => Fox.successful(user._id) + case Some(user: User) => Fox.successful(user._id) case _ => Fox.failure("Access denied.") } } diff --git a/app/views/mail/registerAdminNotify.scala.html b/app/views/mail/registerAdminNotify.scala.html index 4af12a93ee..4db233ce75 100755 --- a/app/views/mail/registerAdminNotify.scala.html +++ b/app/views/mail/registerAdminNotify.scala.html @@ -1,4 +1,4 @@ -@( user: models.user.UserSQL, brainDBresult: String, uri: String ) +@( user: models.user.User, brainDBresult: String, uri: String ) The new user @user.name registered at oxalis.at. Result when trying to register her/him on braintracing.org: @brainDBresult