philomena/lib/philomena_web/controllers/image/related_controller.ex

75 lines
1.9 KiB
Elixir
Raw Normal View History

2019-12-21 00:02:03 +01:00
defmodule PhilomenaWeb.Image.RelatedController do
use PhilomenaWeb, :controller
alias PhilomenaWeb.ImageLoader
alias Philomena.Interactions
alias Philomena.Images.Image
alias Philomena.Elasticsearch
import Ecto.Query
2019-12-21 00:02:03 +01:00
plug PhilomenaWeb.CanaryMapPlug, index: :show
2020-01-11 05:20:19 +01:00
plug :load_and_authorize_resource,
model: Image,
id_name: "image_id",
persisted: true,
preload: [:faves, tags: :aliases]
2019-12-21 00:02:03 +01:00
def index(conn, _params) do
image = conn.assigns.image
user = conn.assigns.current_user
tags_to_match =
image.tags
2020-01-11 05:20:19 +01:00
|> Enum.reject(&(&1.category == "rating"))
2019-12-21 00:02:03 +01:00
|> Enum.sort_by(& &1.images_count)
|> Enum.take(10)
|> Enum.map(& &1.id)
low_count_tags =
tags_to_match
|> Enum.take(5)
|> Enum.map(&%{term: %{tag_ids: &1}})
high_count_tags =
tags_to_match
|> Enum.take(-5)
|> Enum.map(&%{term: %{tag_ids: &1}})
favs_to_match =
image.faves
|> Enum.take(11)
|> Enum.map(&%{term: %{favourited_by_user_ids: &1.user_id}})
2020-01-11 05:20:19 +01:00
query = %{
bool: %{
must: [
%{bool: %{should: low_count_tags, boost: 2}},
%{bool: %{should: high_count_tags, boost: 3, minimum_should_match: "5%"}},
%{bool: %{should: favs_to_match, boost: 0.2, minimum_should_match: "5%"}}
],
must_not: %{term: %{id: image.id}}
2019-12-21 00:02:03 +01:00
}
2020-01-11 05:20:19 +01:00
}
2019-12-21 00:02:03 +01:00
{images, _tags} =
ImageLoader.query(
conn,
query,
2020-05-29 03:04:35 +02:00
sorts: &%{query: &1, sorts: [%{_score: :desc}]},
2019-12-21 00:02:03 +01:00
pagination: %{conn.assigns.image_pagination | page_number: 1}
)
images = Elasticsearch.search_records(images, preload(Image, tags: :aliases))
2019-12-21 00:02:03 +01:00
interactions = Interactions.user_interactions(images, user)
2020-01-11 05:20:19 +01:00
render(conn, "index.html",
title: "##{image.id} - Related Images",
2021-10-28 02:03:11 +02:00
layout_class: "layout--wide",
2020-01-11 05:20:19 +01:00
images: images,
interactions: interactions
)
2019-12-21 00:02:03 +01:00
end
end