/app/controllers/dos/FileStore.scala

https://github.com/delving/dos · Scala · 61 lines · 27 code · 11 blank · 23 comment · 3 complexity · e18df94dc719a378580d6b565117c16a MD5 · raw file

  1. /*
  2. * Copyright 2011 Delving B.V.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package controllers.dos
  17. import org.bson.types.ObjectId
  18. import play.mvc.results.{RenderBinary, Result}
  19. import play.mvc.{Util, Controller}
  20. import com.mongodb.gridfs.GridFSDBFile
  21. import com.mongodb.casbah.commons.MongoDBObject
  22. /**
  23. * Common controller for handling files, no matter from where.
  24. *
  25. * @author Manuel Bernhardt <bernhardt.manuel@gmail.com>
  26. */
  27. object FileStore extends Controller {
  28. // ~~~ public HTTP API
  29. def get(id: String): Result = {
  30. if (!ObjectId.isValid(id)) return Error("Invalid ID " + id)
  31. val oid = new ObjectId(id)
  32. val file = fileStore.findOne(oid) getOrElse (return NotFound("Could not find file with ID " + id))
  33. new RenderBinary(file.inputStream, file.filename, file.length, file.contentType, false)
  34. }
  35. // ~~~ public scala API
  36. @Util def getFilesForItemId(id: ObjectId): List[StoredFile] = fileStore.find(MongoDBObject(ITEM_POINTER_FIELD -> id)).map(fileToStoredFile).toList
  37. // ~~~ private
  38. private[dos] def fileToStoredFile(f: GridFSDBFile) = {
  39. val id = f.getId.asInstanceOf[ObjectId]
  40. val thumbnail = if (FileUpload.isImage(f)) {
  41. fileStore.findOne(MongoDBObject(FILE_POINTER_FIELD -> id)) match {
  42. case Some(t) => Some(t.id.asInstanceOf[ObjectId])
  43. case None => None
  44. }
  45. } else {
  46. None
  47. }
  48. StoredFile(id, f.getFilename, f.getContentType, f.getLength, thumbnail)
  49. }
  50. }