RecordUtils.scala 2.45 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
 * Media Converter
 * Extracts media files from Fedora repository
 * Copyright (C) 2020  Memoriav
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package ch.memobase

import ch.memobase.models._
Sebastian Schüpbach's avatar
Sebastian Schüpbach committed
23
import ujson.{Str, Value}
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

import scala.collection.mutable.ArrayBuffer
import scala.util.{Success, Try}

trait RecordUtils {

  protected def getJsonldGraph(msg: String): ArrayBuffer[Value] = {
    ujson.read(msg).obj("@graph").arr
  }

  private def chooseEventType(eventAsString: String): Event = eventAsString match {
    case "Create" => Create
    case "Update" => Update
    case "Delete" => Delete
    case s => UnknownEvent(s)
  }

  protected def isDigitalObject(obj: ujson.Obj): Boolean = {
    hasKeyValue(obj, "type") {
Sebastian Schüpbach's avatar
Sebastian Schüpbach committed
43
      MemobaseResource(_) == DigitalObject
44
45
46
47
48
    }
  }

  protected def isPreviewImage(obj: ujson.Obj): Boolean = {
    hasKeyValue(obj, "type") {
Sebastian Schüpbach's avatar
Sebastian Schüpbach committed
49
      MemobaseResource(_) == Thumbnail
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
    }
  }

  protected def isProcessableMimeType(obj: ujson.Obj): Boolean = {
    hasKeyValue(obj, "hasMimeType") {
      value => Conversions.getMediaFileType(value).isDefined
    }
  }

  protected def isLocalRecord(obj: ujson.Obj, externalBaseUrl: String): Boolean = {
    hasKeyValue(obj, "locator") {
      value => value.startsWith(externalBaseUrl)
    }
  }

  private def hasKeyValue(obj: ujson.Obj, key: String)(valueFun: String => Boolean): Boolean = {
    Try(obj.value(key)) match {
      case Success(id: Str) => valueFun(id.value)
      case _ => false
    }
  }

  protected def getEventType(objList: ArrayBuffer[Value]): Option[Event] = {
    objList
      .collectFirst {
        case v if isRecord(v.obj) && v.obj.contains("eventType") => chooseEventType(v.obj("eventType").str)
      }
  }

  private def isRecord(obj: ujson.Obj): Boolean = {
    hasKeyValue(obj, "@type") {
      _ == "https://www.ica.org/standards/RiC/ontology#Record"
    }
  }

}