lib/mihari/models/artifact.rb in mihari-6.2.0 vs lib/mihari/models/artifact.rb in mihari-6.3.0

- old
+ new

@@ -76,10 +76,22 @@ decayed_at = base_time - (artifact_lifetime || -1).seconds artifact.created_at < decayed_at end # + # Count artifacts + # + # @param [Mihari::Structs::Filters::Artifact::SearchFilter] filter + # + # @return [Integer] + # + def count(filter) + relation = build_relation(filter) + relation.distinct("artifact.id").count + end + + # # Enrich whois record # # @param [Mihari::Enrichers::Whois] enricher # def enrich_whois(enricher = Enrichers::Whois.new) @@ -103,11 +115,11 @@ # Enrich reverse DNS names # # @param [Mihari::Enrichers::Shodan] enricher # def enrich_reverse_dns(enricher = Enrichers::Shodan.new) - return unless can_enrich_revese_dns? + return unless can_enrich_reverse_dns? self.reverse_dns_names = ReverseDnsName.build_by_ip(data, enricher: enricher) end # @@ -193,10 +205,60 @@ def enrich_by_enricher(enricher) methods = ENRICH_METHODS_BY_ENRICHER[enricher.class] || [] methods.each { |method| send(method, enricher) if respond_to?(method) } end + class << self + # + # Search artifacts + # + # @param [Mihari::Structs::Filters::Artifact::SearchFilterWithPagination] filter + # + # @return [Array<Artifact>] + # + def search(filter) + limit = filter.limit.to_i + raise ArgumentError, "limit should be bigger than zero" unless limit.positive? + + page = filter.page.to_i + raise ArgumentError, "page should be bigger than zero" unless page.positive? + + offset = (page - 1) * limit + + relation = build_relation(filter.without_pagination) + relation.limit(limit).offset(offset).order(id: :desc) + end + + # + # Count artifacts + # + # @param [Mihari::Structs::Filters::Artifact::SearchFilter] filter + # + # @return [Integer] + # + def count(filter) + relation = build_relation(filter) + relation.distinct("artifacts.id").count + end + + # + # @param [Mihari::Structs::Filters::Artifact::SearchFilter] filter + # + # @return [Mihari::Models::Artifact] + # + def build_relation(filter) + relation = eager_load(alert: :tags) + + relation = relation.where(alert: { rule_id: filter.rule_id }) if filter.rule_id + relation = relation.where(alert: { tags: { name: filter.tag } }) if filter.tag + relation = relation.where("artifacts.created_at >= ?", filter.from_at) if filter.from_at + relation = relation.where("artifacts.created_at <= ?", filter.to_at) if filter.to_at + + relation + end + end + private def ipinfo @ipinfo ||= Enrichers::IPInfo.new end @@ -217,10 +279,10 @@ def can_enrich_dns? %w[domain url].include?(data_type) && dns_records.empty? end - def can_enrich_revese_dns? + def can_enrich_reverse_dns? data_type == "ip" && reverse_dns_names.empty? end def can_enrich_geolocation? data_type == "ip" && geolocation.nil?