PageRenderTime 27ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/server/app/models/SlugMapping.scala

https://gitlab.com/guodman/webcbv
Scala | 67 lines | 56 code | 11 blank | 0 comment | 4 complexity | 795510f2d9a2d4ecd6dd57b022a0238d MD5 | raw file
  1. package models
  2. import java.io.File
  3. import com.mongodb.casbah.Imports._
  4. class SlugMapping(val path: String) {
  5. var _id: ObjectId = null
  6. def key: String = SlugMapping.pathToKey(path)
  7. def slug: String = Comic.getComicSlug(path)
  8. def pageCount: Int = _pages
  9. var _pages: Int = -1
  10. def save = {
  11. var builder = MongoDBObject.newBuilder
  12. builder += "_id" -> _id
  13. builder += "path" -> path
  14. builder += "key" -> key
  15. builder += "slug" -> slug
  16. builder += "pages" -> _pages
  17. SlugMapping.dbCollection += builder.result
  18. }
  19. }
  20. object SlugMapping {
  21. val dbCollection = Constants.db("slugMapping")
  22. def factory(db: DBObject): SlugMapping = {
  23. val r = new SlugMapping(db.getAsOrElse[String]("path", ""))
  24. r._id = db.getAs[ObjectId]("_id").get
  25. r._pages = db.getAs[Int]("pages").getOrElse({
  26. val c = Comic.getByPath(r.path)
  27. if (c.isValid) {
  28. c.pageCount
  29. } else {
  30. 0
  31. }
  32. })
  33. return r
  34. }
  35. def getByKey(key: String): SlugMapping = {
  36. val r = dbCollection.findOne(MongoDBObject("key" -> key))
  37. return r.map(factory).orNull
  38. }
  39. def getByPath(path: String): SlugMapping = {
  40. val r = dbCollection.findOne(MongoDBObject("path" -> path))
  41. return r.map(factory).orNull
  42. }
  43. def generateFromPath(path: String): SlugMapping = {
  44. val f = new File(path)
  45. if (Comic.isComicFile(f)) {
  46. val c = new SlugMapping(path)
  47. c._pages = Comic.getByPath(path).pageCount
  48. return c
  49. } else {
  50. return null
  51. }
  52. }
  53. def pathToKey(path: String): String = {
  54. path.replaceAll("""[\.]""", "")
  55. }
  56. }