diff --git a/.iex.exs b/.iex.exs index ed172734..0430b6b1 100644 --- a/.iex.exs +++ b/.iex.exs @@ -1,3 +1,13 @@ -alias Philomena.{Repo, Comments.Comment, Galleries.Gallery, Posts.Post, Images.Image, Topics.Topic, Tags.Tag, Users.User} +alias Philomena.{ + Repo, + Comments.Comment, + Galleries.Gallery, + Posts.Post, + Images.Image, + Topics.Topic, + Tags.Tag, + Users.User +} + import Ecto.Query import Ecto.Changeset diff --git a/config/dev.exs b/config/dev.exs index f5e22575..3c21fbda 100644 --- a/config/dev.exs +++ b/config/dev.exs @@ -68,11 +68,9 @@ config :logger, :console, format: "[$level] $message\n" config :logger, compile_time_purge_matching: [[application: :remote_ip]] # Set up mailer -config :philomena, PhilomenaWeb.Mailer, - adapter: Bamboo.LocalAdapter +config :philomena, PhilomenaWeb.Mailer, adapter: Bamboo.LocalAdapter -config :philomena, :mailer_address, - "noreply@philomena.lc" +config :philomena, :mailer_address, "noreply@philomena.lc" # Use this to debug slime templates # config :slime, :keep_lines, true diff --git a/lib/camo/image.ex b/lib/camo/image.ex index b0d495fe..252b49ec 100644 --- a/lib/camo/image.ex +++ b/lib/camo/image.ex @@ -6,6 +6,7 @@ defmodule Camo.Image do input else camo_digest = :crypto.hmac(:sha, camo_key(), input) |> Base.encode16(case: :lower) + camo_uri = %URI{ host: camo_host(), path: "/" <> camo_digest, @@ -28,4 +29,4 @@ defmodule Camo.Image do defp camo_host do Application.get_env(:philomena, :camo_host) end -end \ No newline at end of file +end diff --git a/lib/mix/tasks/reindex_all.ex b/lib/mix/tasks/reindex_all.ex index bdf3b42a..cc7383b8 100644 --- a/lib/mix/tasks/reindex_all.ex +++ b/lib/mix/tasks/reindex_all.ex @@ -2,7 +2,16 @@ defmodule Mix.Tasks.ReindexAll do use Mix.Task alias Philomena.Elasticsearch - alias Philomena.{Comments.Comment, Galleries.Gallery, Posts.Post, Images.Image, Reports.Report, Tags.Tag} + + alias Philomena.{ + Comments.Comment, + Galleries.Gallery, + Posts.Post, + Images.Image, + Reports.Report, + Tags.Tag + } + alias Philomena.{Comments, Galleries, Posts, Images, Tags} alias Philomena.Polymorphic alias Philomena.Repo @@ -10,13 +19,19 @@ defmodule Mix.Tasks.ReindexAll do @shortdoc "Destroys and recreates all Elasticsearch indices." def run(_) do - if Mix.env == "prod" do + if Mix.env() == "prod" do raise "do not run this task in production" end {:ok, _apps} = Application.ensure_all_started(:philomena) - for {context, schema} <- [{Images, Image}, {Comments, Comment}, {Galleries, Gallery}, {Tags, Tag}, {Posts, Post}] do + for {context, schema} <- [ + {Images, Image}, + {Comments, Comment}, + {Galleries, Gallery}, + {Tags, Tag}, + {Posts, Post} + ] do Elasticsearch.delete_index!(schema) Elasticsearch.create_index!(schema) diff --git a/lib/philomena/adverts.ex b/lib/philomena/adverts.ex index 5fa62b47..d20c81cb 100644 --- a/lib/philomena/adverts.ex +++ b/lib/philomena/adverts.ex @@ -10,7 +10,6 @@ defmodule Philomena.Adverts do alias Philomena.Adverts.Advert alias Philomena.Adverts.Uploader - def random_live do now = DateTime.utc_now() @@ -38,18 +37,19 @@ defmodule Philomena.Adverts do end def click(%Advert{} = advert) do - spawn fn -> + spawn(fn -> query = where(Advert, id: ^advert.id) Repo.update_all(query, inc: [clicks: 1]) - end + end) end defp record_impression(nil), do: nil + defp record_impression(advert) do - spawn fn -> + spawn(fn -> query = where(Advert, id: ^advert.id) Repo.update_all(query, inc: [impressions: 1]) - end + end) advert end diff --git a/lib/philomena/adverts/advert.ex b/lib/philomena/adverts/advert.ex index c1425083..996a22f7 100644 --- a/lib/philomena/adverts/advert.ex +++ b/lib/philomena/adverts/advert.ex @@ -50,8 +50,13 @@ defmodule Philomena.Adverts.Advert do def image_changeset(advert, attrs) do advert |> cast(attrs, [ - :image, :image_mime_type, :image_size, :image_width, :image_height, - :uploaded_image, :removed_image + :image, + :image_mime_type, + :image_size, + :image_width, + :image_height, + :uploaded_image, + :removed_image ]) |> validate_required([:image]) |> validate_inclusion(:image_mime_type, ["image/png", "image/jpeg", "image/gif"]) diff --git a/lib/philomena/analyzers.ex b/lib/philomena/analyzers.ex index 95188bf4..1a3961ec 100644 --- a/lib/philomena/analyzers.ex +++ b/lib/philomena/analyzers.ex @@ -41,15 +41,16 @@ defmodule Philomena.Analyzers do """ @spec analyze(Plug.Upload.t() | String.t()) :: {:ok, map()} | :error def analyze(%Plug.Upload{path: path}), do: analyze(path) + def analyze(path) when is_binary(path) do with {:ok, mime} <- Mime.file(path), - {:ok, analyzer} <- analyzer(mime) - do + {:ok, analyzer} <- analyzer(mime) do {:ok, analyzer.analyze(path)} else error -> error end end + def analyze(_path), do: :error -end \ No newline at end of file +end diff --git a/lib/philomena/analyzers/gif.ex b/lib/philomena/analyzers/gif.ex index f0efa1c8..4685a23f 100644 --- a/lib/philomena/analyzers/gif.ex +++ b/lib/philomena/analyzers/gif.ex @@ -18,7 +18,7 @@ defmodule Philomena.Analyzers.Gif do {output, 0} -> len = output - |> String.split("\n", parts: 2, trim: true) + |> String.split("\n", parts: 2, trim: true) |> length() len > 1 @@ -29,10 +29,20 @@ defmodule Philomena.Analyzers.Gif do end defp duration(false, _file), do: 0.0 + defp duration(true, file) do - with {output, 0} <- System.cmd("ffprobe", ["-i", file, "-show_entries", "format=duration", "-v", "quiet", "-of", "csv=p=0"]), - {duration, _} <- Float.parse(output) - do + with {output, 0} <- + System.cmd("ffprobe", [ + "-i", + file, + "-show_entries", + "format=duration", + "-v", + "quiet", + "-of", + "csv=p=0" + ]), + {duration, _} <- Float.parse(output) do duration else _ -> @@ -58,4 +68,4 @@ defmodule Philomena.Analyzers.Gif do {0, 0} end end -end \ No newline at end of file +end diff --git a/lib/philomena/analyzers/jpeg.ex b/lib/philomena/analyzers/jpeg.ex index fbff77d4..a3a52a22 100644 --- a/lib/philomena/analyzers/jpeg.ex +++ b/lib/philomena/analyzers/jpeg.ex @@ -25,4 +25,4 @@ defmodule Philomena.Analyzers.Jpeg do {0, 0} end end -end \ No newline at end of file +end diff --git a/lib/philomena/analyzers/png.ex b/lib/philomena/analyzers/png.ex index 83c88c6d..6e7e78c7 100644 --- a/lib/philomena/analyzers/png.ex +++ b/lib/philomena/analyzers/png.ex @@ -13,7 +13,16 @@ defmodule Philomena.Analyzers.Png do end defp animated?(file) do - System.cmd("ffprobe", ["-i", file, "-v", "quiet", "-show_entries", "stream=codec_name", "-of", "csv=p=0"]) + System.cmd("ffprobe", [ + "-i", + file, + "-v", + "quiet", + "-show_entries", + "stream=codec_name", + "-of", + "csv=p=0" + ]) |> case do {"apng\n", 0} -> true @@ -42,4 +51,4 @@ defmodule Philomena.Analyzers.Png do {0, 0} end end -end \ No newline at end of file +end diff --git a/lib/philomena/analyzers/svg.ex b/lib/philomena/analyzers/svg.ex index cc1c2eff..37036150 100644 --- a/lib/philomena/analyzers/svg.ex +++ b/lib/philomena/analyzers/svg.ex @@ -26,4 +26,4 @@ defmodule Philomena.Analyzers.Svg do {0, 0} end end -end \ No newline at end of file +end diff --git a/lib/philomena/analyzers/webm.ex b/lib/philomena/analyzers/webm.ex index f3f88514..f139a6fc 100644 --- a/lib/philomena/analyzers/webm.ex +++ b/lib/philomena/analyzers/webm.ex @@ -10,9 +10,18 @@ defmodule Philomena.Analyzers.Webm do end defp duration(file) do - with {output, 0} <- System.cmd("ffprobe", ["-i", file, "-show_entries", "format=duration", "-v", "quiet", "-of", "csv=p=0"]), - {duration, _} <- Float.parse(output) - do + with {output, 0} <- + System.cmd("ffprobe", [ + "-i", + file, + "-show_entries", + "format=duration", + "-v", + "quiet", + "-of", + "csv=p=0" + ]), + {duration, _} <- Float.parse(output) do duration else _ -> @@ -21,7 +30,16 @@ defmodule Philomena.Analyzers.Webm do end defp dimensions(file) do - System.cmd("ffprobe", ["-i", file, "-show_entries", "stream=width,height", "-v", "quiet", "-of", "csv=p=0"]) + System.cmd("ffprobe", [ + "-i", + file, + "-show_entries", + "stream=width,height", + "-v", + "quiet", + "-of", + "csv=p=0" + ]) |> case do {output, 0} -> [width, height] = @@ -36,4 +54,4 @@ defmodule Philomena.Analyzers.Webm do {0, 0} end end -end \ No newline at end of file +end diff --git a/lib/philomena/attribution.ex b/lib/philomena/attribution.ex index c93ee739..53fca736 100644 --- a/lib/philomena/attribution.ex +++ b/lib/philomena/attribution.ex @@ -20,4 +20,4 @@ defprotocol Philomena.Attribution do """ @spec anonymous?(struct()) :: true | false def anonymous?(object) -end \ No newline at end of file +end diff --git a/lib/philomena/badges/award.ex b/lib/philomena/badges/award.ex index f39403ff..72691d32 100644 --- a/lib/philomena/badges/award.ex +++ b/lib/philomena/badges/award.ex @@ -30,5 +30,6 @@ defmodule Philomena.Badges.Award do put_change(changeset, :awarded_on, now) end + defp put_awarded_on(changeset), do: changeset end diff --git a/lib/philomena/bans.ex b/lib/philomena/bans.ex index af534ac1..ee463130 100644 --- a/lib/philomena/bans.ex +++ b/lib/philomena/bans.ex @@ -331,10 +331,11 @@ defmodule Philomena.Bans do """ def exists_for?(user, ip, fingerprint) do now = DateTime.utc_now() + queries = subnet_query(ip, now) ++ - fingerprint_query(fingerprint, now) ++ - user_query(user, now) + fingerprint_query(fingerprint, now) ++ + user_query(user, now) bans = queries @@ -343,38 +344,56 @@ defmodule Philomena.Bans do # Don't return a ban if the user is currently signed in. case is_nil(user) do - true -> Enum.at(bans, 0) + true -> Enum.at(bans, 0) false -> user_ban(bans) end end defp fingerprint_query(nil, _now), do: [] + defp fingerprint_query(fingerprint, now) do [ Fingerprint - |> select([f], %{reason: f.reason, valid_until: f.valid_until, generated_ban_id: f.generated_ban_id, type: ^"FingerprintBan"}) + |> select([f], %{ + reason: f.reason, + valid_until: f.valid_until, + generated_ban_id: f.generated_ban_id, + type: ^"FingerprintBan" + }) |> where([f], f.enabled and f.valid_until > ^now) |> where([f], f.fingerprint == ^fingerprint) ] end defp subnet_query(nil, _now), do: [] + defp subnet_query(ip, now) do {:ok, inet} = EctoNetwork.INET.cast(ip) [ Subnet - |> select([s], %{reason: s.reason, valid_until: s.valid_until, generated_ban_id: s.generated_ban_id, type: ^"SubnetBan"}) + |> select([s], %{ + reason: s.reason, + valid_until: s.valid_until, + generated_ban_id: s.generated_ban_id, + type: ^"SubnetBan" + }) |> where([s], s.enabled and s.valid_until > ^now) |> where(fragment("specification >>= ?", ^inet)) ] end defp user_query(nil, _now), do: [] + defp user_query(user, now) do [ User - |> select([u], %{reason: u.reason, valid_until: u.valid_until, generated_ban_id: u.generated_ban_id, type: ^"UserBan"}) + |> select([u], %{ + reason: u.reason, + valid_until: u.valid_until, + generated_ban_id: u.generated_ban_id, + type: ^"UserBan" + }) |> where([u], u.enabled and u.valid_until > ^now) |> where([u], u.user_id == ^user.id) ] @@ -382,12 +401,13 @@ defmodule Philomena.Bans do defp union_all_queries([query]), do: query + defp union_all_queries([query | rest]), do: query |> union_all(^union_all_queries(rest)) defp user_ban(bans) do bans - |> Enum.filter(& &1.type == "UserBan") + |> Enum.filter(&(&1.type == "UserBan")) |> Enum.at(0) end end diff --git a/lib/philomena/batch.ex b/lib/philomena/batch.ex index 72e996db..29d03582 100644 --- a/lib/philomena/batch.ex +++ b/lib/philomena/batch.ex @@ -27,6 +27,7 @@ defmodule Philomena.Batch do end defp query_batches(_queryable, _opts, _callback, []), do: [] + defp query_batches(queryable, opts, callback, ids) do id_field = Keyword.get(opts, :id_field, :id) diff --git a/lib/philomena/captcha.ex b/lib/philomena/captcha.ex index 7648e4dc..48b8759b 100644 --- a/lib/philomena/captcha.ex +++ b/lib/philomena/captcha.ex @@ -1,7 +1,7 @@ defmodule Philomena.Captcha do defstruct [:image_base64, :solution, :solution_id] - @numbers ~W(1 2 3 4 5 6) + @numbers ~W(1 2 3 4 5 6) @images ~W(1 2 3 4 5 6) @base_path File.cwd!() <> "/assets/static/images/captcha" @@ -26,9 +26,15 @@ defmodule Philomena.Captcha do @background_file @base_path <> "/background.png" @geometry %{ - 1 => "+0+0", 2 => "+120+0", 3 => "+240+0", - 4 => "+0+120", 5 => "+120+120", 6 => "+240+120", - 7 => "+0+240", 8 => "+120+240", 9 => "+240+240" + 1 => "+0+0", + 2 => "+120+0", + 3 => "+240+0", + 4 => "+0+120", + 5 => "+120+120", + 6 => "+240+120", + 7 => "+0+240", + 8 => "+120+240", + 9 => "+240+240" } @distortion_1 [ @@ -60,7 +66,8 @@ defmodule Philomena.Captcha do # Base arguments args = [ - "-page", "360x360", + "-page", + "360x360", @background_file ] @@ -71,8 +78,18 @@ defmodule Philomena.Captcha do |> Enum.flat_map(fn {num, index} -> if num do [ - "(", @image_files[solution[num]], ")", "-geometry", @geometry[index + 1], "-composite", - "(", @number_files[num], ")", "-geometry", @geometry[index + 1], "-composite" + "(", + @image_files[solution[num]], + ")", + "-geometry", + @geometry[index + 1], + "-composite", + "(", + @number_files[num], + ")", + "-geometry", + @geometry[index + 1], + "-composite" ] else [] @@ -99,6 +116,7 @@ defmodule Philomena.Captcha do solution_id = :crypto.strong_rand_bytes(12) |> Base.encode16(case: :lower) + solution_id = "cp_" <> solution_id {:ok, _ok} = Redix.command(:redix, ["SET", solution_id, Jason.encode!(solution)]) @@ -116,8 +134,7 @@ defmodule Philomena.Captcha do # have minimal impact if the race succeeds. with {:ok, sol} <- Redix.command(:redix, ["GET", solution_id]), {:ok, _del} <- Redix.command(:redix, ["DEL", solution_id]), - {:ok, sol} <- Jason.decode(to_string(sol)) - do + {:ok, sol} <- Jason.decode(to_string(sol)) do Map.equal?(solution, sol) else _ -> diff --git a/lib/philomena/channels.ex b/lib/philomena/channels.ex index 9b3920cc..cfdbbc70 100644 --- a/lib/philomena/channels.ex +++ b/lib/philomena/channels.ex @@ -118,6 +118,7 @@ defmodule Philomena.Channels do """ def create_subscription(_channel, nil), do: {:ok, nil} + def create_subscription(channel, user) do %Subscription{channel_id: channel.id, user_id: user.id} |> Subscription.changeset(%{}) @@ -144,6 +145,7 @@ defmodule Philomena.Channels do end def subscribed?(_channel, nil), do: false + def subscribed?(channel, user) do Subscription |> where(channel_id: ^channel.id, user_id: ^user.id) @@ -151,6 +153,7 @@ defmodule Philomena.Channels do end def subscriptions(_channels, nil), do: %{} + def subscriptions(channels, user) do channel_ids = Enum.map(channels, & &1.id) diff --git a/lib/philomena/comments.ex b/lib/philomena/comments.ex index bfd02b11..86ecd78d 100644 --- a/lib/philomena/comments.ex +++ b/lib/philomena/comments.ex @@ -52,7 +52,7 @@ defmodule Philomena.Comments do Image |> where(id: ^image.id) - Multi.new + Multi.new() |> Multi.insert(:comment, comment) |> Multi.update_all(:image, image_query, inc: [comments_count: 1]) |> Multi.run(:subscribe, fn _repo, _changes -> @@ -62,7 +62,7 @@ defmodule Philomena.Comments do end def notify_comment(comment) do - spawn fn -> + spawn(fn -> image = comment |> Repo.preload(:image) @@ -84,7 +84,7 @@ defmodule Philomena.Comments do action: "commented on" } ) - end + end) comment end @@ -106,10 +106,9 @@ defmodule Philomena.Comments do current_body = comment.body current_reason = comment.edit_reason - comment_changes = - Comment.changeset(comment, attrs, now) + comment_changes = Comment.changeset(comment, attrs, now) - Multi.new + Multi.new() |> Multi.update(:comment, comment_changes) |> Multi.run(:version, fn _repo, _changes -> Versions.create_version("Comment", comment.id, editor.id, %{ @@ -190,24 +189,24 @@ defmodule Philomena.Comments do end def reindex_comment(%Comment{} = comment) do - spawn fn -> + spawn(fn -> Comment |> preload(^indexing_preloads()) |> where(id: ^comment.id) |> Repo.one() |> Elasticsearch.index_document(Comment) - end + end) comment end def reindex_comments(image) do - spawn fn -> + spawn(fn -> Comment |> preload(^indexing_preloads()) |> where(image_id: ^image.id) |> Elasticsearch.reindex(Comment) - end + end) image end diff --git a/lib/philomena/comments/attribution.ex b/lib/philomena/comments/attribution.ex index 5ac1a5fe..66bcb74d 100644 --- a/lib/philomena/comments/attribution.ex +++ b/lib/philomena/comments/attribution.ex @@ -10,4 +10,4 @@ defimpl Philomena.Attribution, for: Philomena.Comments.Comment do def anonymous?(comment) do !!comment.anonymous end -end \ No newline at end of file +end diff --git a/lib/philomena/comments/elasticsearch_index.ex b/lib/philomena/comments/elasticsearch_index.ex index 421def79..b5779124 100644 --- a/lib/philomena/comments/elasticsearch_index.ex +++ b/lib/philomena/comments/elasticsearch_index.ex @@ -33,8 +33,10 @@ defmodule Philomena.Comments.ElasticsearchIndex do user_id: %{type: "keyword"}, author: %{type: "keyword"}, image_tag_ids: %{type: "keyword"}, - anonymous: %{type: "keyword"}, # boolean - hidden_from_users: %{type: "keyword"}, # boolean + # boolean + anonymous: %{type: "keyword"}, + # boolean + hidden_from_users: %{type: "keyword"}, body: %{type: "text", analyzer: "snowball"} } } diff --git a/lib/philomena/comments/query.ex b/lib/philomena/comments/query.ex index c2e5c989..ca9f8797 100644 --- a/lib/philomena/comments/query.ex +++ b/lib/philomena/comments/query.ex @@ -60,23 +60,23 @@ defmodule Philomena.Comments.Query do defp user_fields do fields = anonymous_fields() - Keyword.merge(fields, [ + Keyword.merge(fields, custom_fields: fields[:custom_fields] ++ ~W(my), transforms: Map.merge(fields[:transforms], %{"my" => &user_my_transform/2}) - ]) + ) end defp moderator_fields do fields = user_fields() - Keyword.merge(fields, [ + Keyword.merge(fields, literal_fields: ~W(image_id user_id author fingerprint), ip_fields: ~W(ip), bool_fields: ~W(anonymous deleted), custom_fields: fields[:custom_fields] -- ~W(author user_id), aliases: Map.merge(fields[:aliases], %{"deleted" => "hidden_from_users"}), transforms: Map.drop(fields[:transforms], ~W(author user_id)) - ]) + ) end defp parse(fields, context, query_string) do diff --git a/lib/philomena/commissions/commission.ex b/lib/philomena/commissions/commission.ex index 10577785..e3a9262a 100644 --- a/lib/philomena/commissions/commission.ex +++ b/lib/philomena/commissions/commission.ex @@ -25,7 +25,15 @@ defmodule Philomena.Commissions.Commission do @doc false def changeset(commission, attrs) do commission - |> cast(attrs, [:information, :contact, :will_create, :will_not_create, :open, :sheet_image_id, :categories]) + |> cast(attrs, [ + :information, + :contact, + :will_create, + :will_not_create, + :open, + :sheet_image_id, + :categories + ]) |> drop_blank_categories() |> validate_required([:user_id, :information, :contact, :open]) |> validate_length(:information, max: 700, count: :bytes) @@ -37,25 +45,25 @@ defmodule Philomena.Commissions.Commission do categories = changeset |> get_field(:categories) - |> Enum.filter(& &1 not in [nil, ""]) + |> Enum.filter(&(&1 not in [nil, ""])) change(changeset, categories: categories) end def categories do [ - "Anthro": "Anthro", + Anthro: "Anthro", "Canon Characters": "Canon Characters", - "Comics": "Comics", + Comics: "Comics", "Fetish Art": "Fetish Art", "Human and EqG": "Human and EqG", - "NSFW": "NSFW", + NSFW: "NSFW", "Original Characters": "Original Characters", "Original Species": "Original Species", - "Pony": "Pony", - "Requests": "Requests", - "Safe": "Safe", - "Shipping": "Shipping", + Pony: "Pony", + Requests: "Requests", + Safe: "Safe", + Shipping: "Shipping", "Violence and Gore": "Violence and Gore" ] end diff --git a/lib/philomena/conversations.ex b/lib/philomena/conversations.ex index a9d41269..846ae947 100644 --- a/lib/philomena/conversations.ex +++ b/lib/philomena/conversations.ex @@ -92,52 +92,64 @@ defmodule Philomena.Conversations do def count_unread_conversations(user) do Conversation - |> where([c], - ( - (c.to_id == ^user.id and c.to_read == false) or - (c.from_id == ^user.id and c.from_read == false) - ) - and not ( - (c.to_id == ^user.id and c.to_hidden == true) or - (c.from_id == ^user.id and c.from_hidden == true) - ) + |> where( + [c], + ((c.to_id == ^user.id and c.to_read == false) or + (c.from_id == ^user.id and c.from_read == false)) and + not ((c.to_id == ^user.id and c.to_hidden == true) or + (c.from_id == ^user.id and c.from_hidden == true)) ) |> Repo.aggregate(:count, :id) end - def mark_conversation_read(conversation, user, read \\ true) - def mark_conversation_read(%Conversation{to_id: user_id, from_id: user_id} = conversation, %{id: user_id}, read) do + def mark_conversation_read( + %Conversation{to_id: user_id, from_id: user_id} = conversation, + %{id: user_id}, + read + ) do conversation |> Conversation.read_changeset(%{to_read: read, from_read: read}) |> Repo.update() end + def mark_conversation_read(%Conversation{to_id: user_id} = conversation, %{id: user_id}, read) do conversation |> Conversation.read_changeset(%{to_read: read}) |> Repo.update() end + def mark_conversation_read(%Conversation{from_id: user_id} = conversation, %{id: user_id}, read) do conversation |> Conversation.read_changeset(%{from_read: read}) |> Repo.update() end - def mark_conversation_read(_conversation, _user, _read), do: {:ok, nil} + def mark_conversation_read(_conversation, _user, _read), do: {:ok, nil} def mark_conversation_hidden(conversation, user, hidden \\ true) - def mark_conversation_hidden(%Conversation{to_id: user_id} = conversation, %{id: user_id}, hidden) do + def mark_conversation_hidden( + %Conversation{to_id: user_id} = conversation, + %{id: user_id}, + hidden + ) do conversation |> Conversation.hidden_changeset(%{to_hidden: hidden}) |> Repo.update() end - def mark_conversation_hidden(%Conversation{from_id: user_id} = conversation, %{id: user_id}, hidden) do + + def mark_conversation_hidden( + %Conversation{from_id: user_id} = conversation, + %{id: user_id}, + hidden + ) do conversation |> Conversation.hidden_changeset(%{from_hidden: hidden}) |> Repo.update() end + def mark_conversation_hidden(_conversation, _user, _read), do: {:ok, nil} alias Philomena.Conversations.Message @@ -181,9 +193,11 @@ defmodule Philomena.Conversations do now = DateTime.utc_now() - Multi.new + Multi.new() |> Multi.insert(:message, message) - |> Multi.update_all(:conversation, conversation_query, set: [from_read: false, to_read: false, last_message_at: now]) + |> Multi.update_all(:conversation, conversation_query, + set: [from_read: false, to_read: false, last_message_at: now] + ) |> Repo.isolated_transaction(:serializable) end diff --git a/lib/philomena/dnp_entries.ex b/lib/philomena/dnp_entries.ex index 613b879a..03946710 100644 --- a/lib/philomena/dnp_entries.ex +++ b/lib/philomena/dnp_entries.ex @@ -50,7 +50,7 @@ defmodule Philomena.DnpEntries do """ def create_dnp_entry(user, tags, attrs \\ %{}) do - tag = Enum.find(tags, &to_string(&1.id) == attrs["tag_id"]) + tag = Enum.find(tags, &(to_string(&1.id) == attrs["tag_id"])) %DnpEntry{} |> DnpEntry.creation_changeset(attrs, tag, user) @@ -70,7 +70,7 @@ defmodule Philomena.DnpEntries do """ def update_dnp_entry(%DnpEntry{} = dnp_entry, tags, attrs) do - tag = Enum.find(tags, &to_string(&1.id) == attrs["tag_id"]) + tag = Enum.find(tags, &(to_string(&1.id) == attrs["tag_id"])) dnp_entry |> DnpEntry.update_changeset(attrs, tag) diff --git a/lib/philomena/dnp_entries/dnp_entry.ex b/lib/philomena/dnp_entries/dnp_entry.ex index 6f8c9d1a..201fe73e 100644 --- a/lib/philomena/dnp_entries/dnp_entry.ex +++ b/lib/philomena/dnp_entries/dnp_entry.ex @@ -53,6 +53,7 @@ defmodule Philomena.DnpEntries.DnpEntry do defp validate_conditions(%Ecto.Changeset{changes: %{dnp_type: "Other"}} = changeset), do: validate_required(changeset, [:conditions]) + defp validate_conditions(changeset), do: changeset @@ -70,12 +71,18 @@ defmodule Philomena.DnpEntries.DnpEntry do def reasons do [ - {"No Edits", "I would like to prevent edited versions of my artwork from being uploaded in the future"}, - {"Artist Tag Change", "I would like my artist tag to be changed to something that can not be connected to my current name"}, - {"Uploader Credit Change", "I would like the uploader credit for already existing uploads of my art to be assigned to me"}, - {"Certain Type/Location Only", "I only want to allow art of a certain type or from a certain location to be uploaded to Derpibooru"}, - {"With Permission Only", "I only want people with my permission to be allowed to upload my art to Derpibooru"}, - {"Artist Upload Only", "I want to be the only person allowed to upload my art to Derpibooru"}, + {"No Edits", + "I would like to prevent edited versions of my artwork from being uploaded in the future"}, + {"Artist Tag Change", + "I would like my artist tag to be changed to something that can not be connected to my current name"}, + {"Uploader Credit Change", + "I would like the uploader credit for already existing uploads of my art to be assigned to me"}, + {"Certain Type/Location Only", + "I only want to allow art of a certain type or from a certain location to be uploaded to Derpibooru"}, + {"With Permission Only", + "I only want people with my permission to be allowed to upload my art to Derpibooru"}, + {"Artist Upload Only", + "I want to be the only person allowed to upload my art to Derpibooru"}, {"Other", "I would like a DNP entry under other conditions"} ] end diff --git a/lib/philomena/duplicate_reports.ex b/lib/philomena/duplicate_reports.ex index 798ba04c..38d620ff 100644 --- a/lib/philomena/duplicate_reports.ex +++ b/lib/philomena/duplicate_reports.ex @@ -20,7 +20,9 @@ defmodule Philomena.DuplicateReports do |> where([i, _it], i.duplication_checked != true) |> Repo.all() |> Enum.map(fn target -> - create_duplicate_report(source, target, %{}, %{"reason" => "Automated Perceptual dedupe match"}) + create_duplicate_report(source, target, %{}, %{ + "reason" => "Automated Perceptual dedupe match" + }) end) end @@ -32,7 +34,9 @@ defmodule Philomena.DuplicateReports do where: it.ne >= ^(intensities.ne - dist) and it.ne <= ^(intensities.ne + dist), where: it.sw >= ^(intensities.sw - dist) and it.sw <= ^(intensities.sw + dist), where: it.se >= ^(intensities.se - dist) and it.se <= ^(intensities.se + dist), - where: i.image_aspect_ratio >= ^(aspect_ratio - aspect_dist) and i.image_aspect_ratio <= ^(aspect_ratio + aspect_dist), + where: + i.image_aspect_ratio >= ^(aspect_ratio - aspect_dist) and + i.image_aspect_ratio <= ^(aspect_ratio + aspect_dist), limit: 20 end @@ -83,8 +87,10 @@ defmodule Philomena.DuplicateReports do DuplicateReport |> where( [dr], - (dr.image_id == ^duplicate_report.image_id and dr.duplicate_of_image_id == ^duplicate_report.duplicate_of_image_id) or - (dr.image_id == ^duplicate_report.duplicate_of_image_id and dr.duplicate_of_image_id == ^duplicate_report.image_id) + (dr.image_id == ^duplicate_report.image_id and + dr.duplicate_of_image_id == ^duplicate_report.duplicate_of_image_id) or + (dr.image_id == ^duplicate_report.duplicate_of_image_id and + dr.duplicate_of_image_id == ^duplicate_report.image_id) ) |> where([dr], dr.id != ^duplicate_report.id) |> repo.update_all(set: [state: "rejected"]) diff --git a/lib/philomena/duplicate_reports/duplicate_report.ex b/lib/philomena/duplicate_reports/duplicate_report.ex index 34dfbf4c..d25b1cbe 100644 --- a/lib/philomena/duplicate_reports/duplicate_report.ex +++ b/lib/philomena/duplicate_reports/duplicate_report.ex @@ -62,7 +62,7 @@ defmodule Philomena.DuplicateReports.DuplicateReport do target_id = get_field(changeset, :duplicate_of_image_id) case source_id == target_id do - true -> add_error(changeset, :image_id, "must be different from the target") + true -> add_error(changeset, :image_id, "must be different from the target") false -> changeset end end diff --git a/lib/philomena/elasticsearch.ex b/lib/philomena/elasticsearch.ex index b9684788..10e151ef 100644 --- a/lib/philomena/elasticsearch.ex +++ b/lib/philomena/elasticsearch.ex @@ -109,7 +109,13 @@ defmodule Philomena.Elasticsearch do def search_results(module, elastic_query, pagination_params \\ %{}) do page_number = pagination_params[:page_number] || 1 page_size = pagination_params[:page_size] || 25 - elastic_query = Map.merge(elastic_query, %{from: (page_number - 1) * page_size, size: page_size, _source: false}) + + elastic_query = + Map.merge(elastic_query, %{ + from: (page_number - 1) * page_size, + size: page_size, + _source: false + }) results = search(module, elastic_query) time = results["took"] diff --git a/lib/philomena/filename.ex b/lib/philomena/filename.ex index 0ff8b274..43b081a1 100644 --- a/lib/philomena/filename.ex +++ b/lib/philomena/filename.ex @@ -32,4 +32,4 @@ defmodule Philomena.Filename do |> to_string() |> String.replace(~r/[^0-9]/, "") end -end \ No newline at end of file +end diff --git a/lib/philomena/filters.ex b/lib/philomena/filters.ex index f1892c70..907281a4 100644 --- a/lib/philomena/filters.ex +++ b/lib/philomena/filters.ex @@ -120,7 +120,7 @@ defmodule Philomena.Filters do end def recent_and_user_filters(user) do - user_filters = + user_filters = Filter |> select([f], %{id: f.id, name: f.name, recent: ^"f"}) |> where(user_id: ^user.id) @@ -139,8 +139,8 @@ defmodule Philomena.Filters do end) |> Enum.group_by( fn - %{recent: "t"} -> "Recent Filters" - _user -> "Your Filters" + %{recent: "t"} -> "Recent Filters" + _user -> "Your Filters" end, fn %{id: id, name: name} -> [key: name, value: id] diff --git a/lib/philomena/filters/filter.ex b/lib/philomena/filters/filter.ex index 0f8068f3..5e8b3928 100644 --- a/lib/philomena/filters/filter.ex +++ b/lib/philomena/filters/filter.ex @@ -34,7 +34,14 @@ defmodule Philomena.Filters.Filter do |> Map.get(:user) filter - |> cast(attrs, [:spoilered_tag_list, :hidden_tag_list, :description, :name, :spoilered_complex_str, :hidden_complex_str]) + |> cast(attrs, [ + :spoilered_tag_list, + :hidden_tag_list, + :description, + :name, + :spoilered_complex_str, + :hidden_complex_str + ]) |> TagList.propagate_tag_list(:spoilered_tag_list, :spoilered_tag_ids) |> TagList.propagate_tag_list(:hidden_tag_list, :hidden_tag_ids) |> validate_required([:name, :description]) diff --git a/lib/philomena/forums.ex b/lib/philomena/forums.ex index 009be8f8..f77df915 100644 --- a/lib/philomena/forums.ex +++ b/lib/philomena/forums.ex @@ -105,6 +105,7 @@ defmodule Philomena.Forums do end def subscribed?(_forum, nil), do: false + def subscribed?(forum, user) do Subscription |> where(forum_id: ^forum.id, user_id: ^user.id) @@ -112,6 +113,7 @@ defmodule Philomena.Forums do end def create_subscription(_forum, nil), do: {:ok, nil} + def create_subscription(forum, user) do %Subscription{forum_id: forum.id, user_id: user.id} |> Subscription.changeset(%{}) @@ -138,6 +140,7 @@ defmodule Philomena.Forums do end def clear_notification(_forum, nil), do: nil + def clear_notification(forum, user) do Notifications.delete_unread_notification("Forum", forum.id, user) end diff --git a/lib/philomena/forums/forum.ex b/lib/philomena/forums/forum.ex index eda67fd1..e70327d8 100644 --- a/lib/philomena/forums/forum.ex +++ b/lib/philomena/forums/forum.ex @@ -28,7 +28,9 @@ defmodule Philomena.Forums.Forum do |> cast(attrs, [:name, :short_name, :description, :access_level]) |> validate_required([:name, :short_name, :description, :access_level]) |> validate_inclusion(:access_level, ~W(normal assistant staff)) - |> validate_format(:short_name, ~r/\A[a-z]+\z/, message: "must consist only of lowercase letters") + |> validate_format(:short_name, ~r/\A[a-z]+\z/, + message: "must consist only of lowercase letters" + ) |> unique_constraint(:short_name, name: :index_forums_on_short_name) end end diff --git a/lib/philomena/galleries.ex b/lib/philomena/galleries.ex index 395e8e4f..399937d2 100644 --- a/lib/philomena/galleries.ex +++ b/lib/philomena/galleries.ex @@ -123,21 +123,21 @@ defmodule Philomena.Galleries do end def reindex_gallery(%Gallery{} = gallery) do - spawn fn -> + spawn(fn -> Gallery |> preload(^indexing_preloads()) |> where(id: ^gallery.id) |> Repo.one() |> Elasticsearch.index_document(Gallery) - end + end) gallery end def unindex_gallery(%Gallery{} = gallery) do - spawn fn -> + spawn(fn -> Elasticsearch.delete_document(gallery.id, Gallery) - end + end) gallery end @@ -198,7 +198,7 @@ defmodule Philomena.Galleries do end def notify_gallery(gallery) do - spawn fn -> + spawn(fn -> subscriptions = gallery |> Repo.preload(:subscriptions) @@ -215,13 +215,13 @@ defmodule Philomena.Galleries do action: "added images to" } ) - end + end) gallery end def reorder_gallery(gallery, image_ids) do - spawn fn -> + spawn(fn -> interactions = Interaction |> where([gi], gi.image_id in ^image_ids) @@ -234,6 +234,7 @@ defmodule Philomena.Galleries do |> Map.new(fn {interaction, index} -> {index, interaction.position} end) images_present = Map.new(interactions, &{&1.image_id, true}) + requested = image_ids |> Enum.filter(&images_present[&1]) @@ -272,7 +273,7 @@ defmodule Philomena.Galleries do # Now update all the associated images Images.reindex_images(Map.keys(requested)) - end + end) gallery end @@ -283,6 +284,7 @@ defmodule Philomena.Galleries do alias Philomena.Galleries.Subscription def subscribed?(_gallery, nil), do: false + def subscribed?(gallery, user) do Subscription |> where(gallery_id: ^gallery.id, user_id: ^user.id) @@ -325,6 +327,7 @@ defmodule Philomena.Galleries do end def clear_notification(_gallery, nil), do: nil + def clear_notification(gallery, user) do Notifications.delete_unread_notification("Gallery", gallery.id, user) end diff --git a/lib/philomena/galleries/elasticsearch_index.ex b/lib/philomena/galleries/elasticsearch_index.ex index 9a0b0d79..a948609f 100644 --- a/lib/philomena/galleries/elasticsearch_index.ex +++ b/lib/philomena/galleries/elasticsearch_index.ex @@ -25,15 +25,18 @@ defmodule Philomena.Galleries.ElasticsearchIndex do _all: %{enabled: false}, dynamic: false, properties: %{ - id: %{type: "integer"}, # keyword + # keyword + id: %{type: "integer"}, image_count: %{type: "integer"}, watcher_count: %{type: "integer"}, updated_at: %{type: "date"}, created_at: %{type: "date"}, title: %{type: "keyword"}, - creator: %{type: "keyword"}, # missing creator_id + # missing creator_id + creator: %{type: "keyword"}, image_ids: %{type: "keyword"}, - watcher_ids: %{type: "keyword"}, # ??? + # ??? + watcher_ids: %{type: "keyword"}, description: %{type: "text", analyzer: "snowball"} } } diff --git a/lib/philomena/http.ex b/lib/philomena/http.ex index b4b5f135..56f8ca1e 100644 --- a/lib/philomena/http.ex +++ b/lib/philomena/http.ex @@ -1,5 +1,8 @@ defmodule Philomena.Http do - @user_agent ["User-Agent": "Mozilla/5.0 (X11; Philomena; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0"] + @user_agent [ + "User-Agent": + "Mozilla/5.0 (X11; Philomena; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0" + ] def get!(url, headers \\ [], options \\ []) do headers = Keyword.merge(@user_agent, headers) |> add_host(url) @@ -19,7 +22,7 @@ defmodule Philomena.Http do defp add_host(headers, url) do %{host: host} = URI.parse(url) - Keyword.merge(["Host": host, "Connection": "close"], headers) + Keyword.merge([Host: host, Connection: "close"], headers) end defp proxy_host do diff --git a/lib/philomena/image_faves.ex b/lib/philomena/image_faves.ex index 615247f1..626660b5 100644 --- a/lib/philomena/image_faves.ex +++ b/lib/philomena/image_faves.ex @@ -23,7 +23,7 @@ defmodule Philomena.ImageFaves do Image |> where(id: ^image.id) - Multi.new + Multi.new() |> Multi.insert(:fave, fave) |> Multi.update_all(:inc_faves_count, image_query, inc: [faves_count: 1]) |> Multi.run(:inc_fave_stat, fn _repo, _changes -> @@ -45,7 +45,7 @@ defmodule Philomena.ImageFaves do Image |> where(id: ^image.id) - Multi.new + Multi.new() |> Multi.delete_all(:unfave, fave_query) |> Multi.run(:dec_faves_count, fn repo, %{unfave: {faves, nil}} -> {count, nil} = diff --git a/lib/philomena/image_hides.ex b/lib/philomena/image_hides.ex index 1e0b9047..3a6dc79b 100644 --- a/lib/philomena/image_hides.ex +++ b/lib/philomena/image_hides.ex @@ -22,7 +22,7 @@ defmodule Philomena.ImageHides do Image |> where(id: ^image.id) - Multi.new + Multi.new() |> Multi.insert(:hide, hide) |> Multi.update_all(:inc_hides_count, image_query, inc: [hides_count: 1]) end @@ -41,7 +41,7 @@ defmodule Philomena.ImageHides do Image |> where(id: ^image.id) - Multi.new + Multi.new() |> Multi.delete_all(:unhide, hide_query) |> Multi.run(:dec_hides_count, fn repo, %{unhide: {hides, nil}} -> {count, nil} = diff --git a/lib/philomena/image_navigator.ex b/lib/philomena/image_navigator.ex index e30c040f..6397d5fa 100644 --- a/lib/philomena/image_navigator.ex +++ b/lib/philomena/image_navigator.ex @@ -70,7 +70,7 @@ defmodule Philomena.ImageNavigator do defp extract_filters(%{"galleries.position" => term} = sort, image, rel) do # Extract gallery ID and current position gid = term.nested.filter.term["galleries.id"] - pos = Enum.find(image[:galleries], & &1.id == gid).position + pos = Enum.find(image[:galleries], &(&1.id == gid)).position # Sort in the other direction if we are going backwards sd = term.order @@ -111,9 +111,11 @@ defmodule Philomena.ImageNavigator do filters |> Enum.with_index() |> Enum.map(fn - {filter, 0} -> filter.this + {filter, 0} -> + filter.this + {filter, i} -> - filters_so_far = + filters_so_far = filters |> Enum.take(i) |> Enum.map(& &1.for_next) @@ -144,13 +146,13 @@ defmodule Philomena.ImageNavigator do %{ this: %{ nested: %{ - path: :galleries, + path: :galleries, query: %{range: %{"galleries.position" => %{dir => val}}} } }, next: %{ nested: %{ - path: :galleries, + path: :galleries, query: %{range: %{"galleries.position" => %{@range_map[dir] => val}}} } } diff --git a/lib/philomena/image_scope.ex b/lib/philomena/image_scope.ex index 3488d1d1..b8765486 100644 --- a/lib/philomena/image_scope.ex +++ b/lib/philomena/image_scope.ex @@ -11,7 +11,7 @@ defmodule Philomena.ImageScope do defp scope(list, conn, key, key_atom) do case conn.params[key] do nil -> list - "" -> list + "" -> list val -> [{key_atom, val} | list] end end diff --git a/lib/philomena/image_sorter.ex b/lib/philomena/image_sorter.ex index 0ff932e8..004d723d 100644 --- a/lib/philomena/image_sorter.ex +++ b/lib/philomena/image_sorter.ex @@ -52,17 +52,19 @@ defmodule Philomena.ImageSorter do {gallery, _rest} -> %{ queries: [], - sorts: [%{ - "galleries.position" => %{ - order: sd, - nested: %{ - path: :galleries, - filter: %{ - term: %{"galleries.id" => gallery} + sorts: [ + %{ + "galleries.position" => %{ + order: sd, + nested: %{ + path: :galleries, + filter: %{ + term: %{"galleries.id" => gallery} + } } } } - }], + ], constant_score: true } @@ -77,13 +79,15 @@ defmodule Philomena.ImageSorter do defp random_query(seed, sd) do %{ - queries: [%{ - function_score: %{ - query: %{match_all: %{}}, - random_score: %{seed: seed, field: :id}, - boost_mode: :replace + queries: [ + %{ + function_score: %{ + query: %{match_all: %{}}, + random_score: %{seed: seed, field: :id}, + boost_mode: :replace + } } - }], + ], sorts: [%{"_score" => sd}], constant_score: true } diff --git a/lib/philomena/image_votes.ex b/lib/philomena/image_votes.ex index 7998565e..29d84f81 100644 --- a/lib/philomena/image_votes.ex +++ b/lib/philomena/image_votes.ex @@ -23,12 +23,14 @@ defmodule Philomena.ImageVotes do Image |> where(id: ^image.id) - upvotes = if up, do: 1, else: 0 + upvotes = if up, do: 1, else: 0 downvotes = if up, do: 0, else: 1 - Multi.new + Multi.new() |> Multi.insert(:vote, vote) - |> Multi.update_all(:inc_vote_count, image_query, inc: [upvotes_count: upvotes, downvotes_count: downvotes, score: upvotes - downvotes]) + |> Multi.update_all(:inc_vote_count, image_query, + inc: [upvotes_count: upvotes, downvotes_count: downvotes, score: upvotes - downvotes] + ) |> Multi.run(:inc_vote_stat, fn _repo, _changes -> UserStatistics.inc_stat(user, :votes_cast, 1) end) @@ -55,13 +57,16 @@ defmodule Philomena.ImageVotes do Image |> where(id: ^image.id) - Multi.new + Multi.new() |> Multi.delete_all(:unupvote, upvote_query) |> Multi.delete_all(:undownvote, downvote_query) - |> Multi.run(:dec_votes_count, fn repo, %{unupvote: {upvotes, nil}, undownvote: {downvotes, nil}} -> + |> Multi.run(:dec_votes_count, fn repo, + %{unupvote: {upvotes, nil}, undownvote: {downvotes, nil}} -> {count, nil} = image_query - |> repo.update_all(inc: [upvotes_count: -upvotes, downvotes_count: -downvotes, score: downvotes - upvotes]) + |> repo.update_all( + inc: [upvotes_count: -upvotes, downvotes_count: -downvotes, score: downvotes - upvotes] + ) UserStatistics.inc_stat(user, :votes_cast, -(upvotes + downvotes)) diff --git a/lib/philomena/images.ex b/lib/philomena/images.ex index 2b81570f..795020ed 100644 --- a/lib/philomena/images.ex +++ b/lib/philomena/images.ex @@ -63,7 +63,7 @@ defmodule Philomena.Images do |> Image.tag_changeset(attrs, [], tags) |> Uploader.analyze_upload(attrs) - Multi.new + Multi.new() |> Multi.insert(:image, image) |> Multi.run(:name_caches, fn repo, %{image: image} -> image @@ -217,7 +217,7 @@ defmodule Philomena.Images do Ecto.build_assoc(image, :source_changes) |> SourceChange.creation_changeset(attrs, attribution) - Multi.new + Multi.new() |> Multi.update(:image, image_changes) |> Multi.run(:source_change, fn repo, _changes -> case image_changes.changes do @@ -235,7 +235,7 @@ defmodule Philomena.Images do old_tags = Tags.get_or_create_tags(attrs["old_tag_input"]) new_tags = Tags.get_or_create_tags(attrs["tag_input"]) - Multi.new + Multi.new() |> Multi.run(:image, fn repo, _chg -> image |> repo.preload(:tags) @@ -253,7 +253,7 @@ defmodule Philomena.Images do tag_changes = added_tags |> Enum.map(&tag_change_attributes(attribution, image, &1, true, attribution[:user])) - + {count, nil} = repo.insert_all(TagChange, tag_changes) {:ok, count} @@ -296,9 +296,10 @@ defmodule Philomena.Images do defp tag_change_attributes(attribution, image, tag, added, user) do now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second) + user_id = case user do - nil -> nil + nil -> nil user -> user.id end @@ -340,7 +341,12 @@ defmodule Philomena.Images do case result do {:ok, changes} -> - update_first_seen_at(duplicate_of_image, image.first_seen_at, duplicate_of_image.first_seen_at) + update_first_seen_at( + duplicate_of_image, + image.first_seen_at, + duplicate_of_image.first_seen_at + ) + tags = Tags.copy_tags(image, duplicate_of_image) Comments.migrate_comments(image, duplicate_of_image) Interactions.migrate_interactions(image, duplicate_of_image) @@ -356,7 +362,7 @@ defmodule Philomena.Images do min_time = case NaiveDateTime.compare(time_1, time_2) do :gt -> time_2 - _ -> time_1 + _ -> time_1 end Image @@ -398,7 +404,7 @@ defmodule Philomena.Images do def unhide_image(%Image{hidden_from_users: true} = image) do key = image.hidden_image_key - Multi.new + Multi.new() |> Multi.update(:image, Image.unhide_changeset(image)) |> Multi.run(:tags, fn repo, %{image: image} -> image = Repo.preload(image, :tags, force: true) @@ -417,6 +423,7 @@ defmodule Philomena.Images do end) |> Repo.isolated_transaction(:serializable) end + def unhide_image(image), do: {:ok, image} def batch_update(image_ids, added_tags, removed_tags, tag_change_attributes) do @@ -445,26 +452,33 @@ defmodule Philomena.Images do now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second) tag_change_attributes = Map.merge(tag_change_attributes, %{created_at: now, updated_at: now}) - Repo.transaction fn -> - {added_count, inserted} = Repo.insert_all(Tagging, insertions, on_conflict: :nothing, returning: [:image_id, :tag_id]) + Repo.transaction(fn -> + {added_count, inserted} = + Repo.insert_all(Tagging, insertions, + on_conflict: :nothing, + returning: [:image_id, :tag_id] + ) + {removed_count, deleted} = Repo.delete_all(deletions) inserted = Enum.map(inserted, &[&1.image_id, &1.tag_id]) - added_changes = Enum.map(inserted, fn [image_id, tag_id] -> - Map.merge(tag_change_attributes, %{image_id: image_id, tag_id: tag_id, added: true}) - end) + added_changes = + Enum.map(inserted, fn [image_id, tag_id] -> + Map.merge(tag_change_attributes, %{image_id: image_id, tag_id: tag_id, added: true}) + end) - removed_changes = Enum.map(deleted, fn [image_id, tag_id] -> - Map.merge(tag_change_attributes, %{image_id: image_id, tag_id: tag_id, added: false}) - end) + removed_changes = + Enum.map(deleted, fn [image_id, tag_id] -> + Map.merge(tag_change_attributes, %{image_id: image_id, tag_id: tag_id, added: false}) + end) changes = added_changes ++ removed_changes Repo.insert_all(TagChange, changes) Repo.update_all(where(Tag, [t], t.id in ^added_tags), inc: [images_count: added_count]) Repo.update_all(where(Tag, [t], t.id in ^removed_tags), inc: [images_count: -removed_count]) - end + end) end @doc """ @@ -503,23 +517,33 @@ defmodule Philomena.Images do end def reindex_images(image_ids) do - spawn fn -> + spawn(fn -> Image |> preload(^indexing_preloads()) |> where([i], i.id in ^image_ids) |> Elasticsearch.reindex(Image) - end + end) image_ids end def indexing_preloads do - [:user, :favers, :downvoters, :upvoters, :hiders, :deleter, :gallery_interactions, tags: [:aliases, :aliased_tag]] + [ + :user, + :favers, + :downvoters, + :upvoters, + :hiders, + :deleter, + :gallery_interactions, + tags: [:aliases, :aliased_tag] + ] end alias Philomena.Images.Subscription def subscribed?(_image, nil), do: false + def subscribed?(image, user) do Subscription |> where(image_id: ^image.id, user_id: ^user.id) @@ -539,6 +563,7 @@ defmodule Philomena.Images do """ def create_subscription(_image, nil), do: {:ok, nil} + def create_subscription(image, user) do %Subscription{image_id: image.id, user_id: user.id} |> Subscription.changeset(%{}) @@ -565,6 +590,7 @@ defmodule Philomena.Images do end def clear_notification(_image, nil), do: nil + def clear_notification(image, user) do Notifications.delete_unread_notification("Image", image.id, user) end diff --git a/lib/philomena/images/attribution.ex b/lib/philomena/images/attribution.ex index b2695ccb..b17e62e3 100644 --- a/lib/philomena/images/attribution.ex +++ b/lib/philomena/images/attribution.ex @@ -10,4 +10,4 @@ defimpl Philomena.Attribution, for: Philomena.Images.Image do def anonymous?(image) do !!image.anonymous end -end \ No newline at end of file +end diff --git a/lib/philomena/images/hider.ex b/lib/philomena/images/hider.ex index 3a305be6..9c214e7d 100644 --- a/lib/philomena/images/hider.ex +++ b/lib/philomena/images/hider.ex @@ -24,11 +24,12 @@ defmodule Philomena.Images.Hider do do: Path.join([image_thumbnail_root(), time_identifier(created_at), to_string(id)]) defp image_thumb_dir(%Image{created_at: created_at, id: id}, key), - do: Path.join([image_thumbnail_root(), time_identifier(created_at), to_string(id) <> "-" <> key]) + do: + Path.join([image_thumbnail_root(), time_identifier(created_at), to_string(id) <> "-" <> key]) defp time_identifier(time), do: Enum.join([time.year, time.month, time.day], "/") defp image_thumbnail_root, do: Application.get_env(:philomena, :image_file_root) <> "/thumbs" -end \ No newline at end of file +end diff --git a/lib/philomena/images/image.ex b/lib/philomena/images/image.ex index 1630082d..f138a73f 100644 --- a/lib/philomena/images/image.ex +++ b/lib/philomena/images/image.ex @@ -122,22 +122,41 @@ defmodule Philomena.Images.Image do def image_changeset(image, attrs) do image |> cast(attrs, [ - :image, :image_name, :image_width, :image_height, :image_size, - :image_format, :image_mime_type, :image_aspect_ratio, - :image_orig_sha512_hash, :image_sha512_hash, :uploaded_image, - :removed_image, :image_is_animated - ]) - |> validate_required([ - :image, :image_width, :image_height, :image_size, - :image_format, :image_mime_type, :image_aspect_ratio, - :image_orig_sha512_hash, :image_sha512_hash, :uploaded_image, + :image, + :image_name, + :image_width, + :image_height, + :image_size, + :image_format, + :image_mime_type, + :image_aspect_ratio, + :image_orig_sha512_hash, + :image_sha512_hash, + :uploaded_image, + :removed_image, :image_is_animated ]) - |> validate_number(:image_size, greater_than: 0, less_than_or_equal_to: 26214400) + |> validate_required([ + :image, + :image_width, + :image_height, + :image_size, + :image_format, + :image_mime_type, + :image_aspect_ratio, + :image_orig_sha512_hash, + :image_sha512_hash, + :uploaded_image, + :image_is_animated + ]) + |> validate_number(:image_size, greater_than: 0, less_than_or_equal_to: 26_214_400) |> validate_number(:image_width, greater_than: 0, less_than_or_equal_to: 32767) |> validate_number(:image_height, greater_than: 0, less_than_or_equal_to: 32767) |> validate_length(:image_name, max: 255, count: :bytes) - |> validate_inclusion(:image_mime_type, ~W(image/gif image/jpeg image/png image/svg+xml video/webm)) + |> validate_inclusion( + :image_mime_type, + ~W(image/gif image/jpeg image/png image/svg+xml video/webm) + ) |> unsafe_validate_unique([:image_orig_sha512_hash], Repo) end @@ -260,8 +279,7 @@ defmodule Philomena.Images.Image do tags |> Enum.map_join(", ", & &1.name) - tag_ids = - tags |> Enum.map(& &1.id) + tag_ids = tags |> Enum.map(& &1.id) aliases = Tag diff --git a/lib/philomena/images/query.ex b/lib/philomena/images/query.ex index 54de4913..face1303 100644 --- a/lib/philomena/images/query.ex +++ b/lib/philomena/images/query.ex @@ -61,10 +61,12 @@ defmodule Philomena.Images.Query do defp anonymous_fields do [ - int_fields: ~W(id width height comment_count score upvotes downvotes faves uploader_id faved_by_id tag_count), + int_fields: + ~W(id width height comment_count score upvotes downvotes faves uploader_id faved_by_id tag_count), float_fields: ~W(aspect_ratio wilson_score), date_fields: ~W(created_at updated_at first_seen_at), - literal_fields: ~W(faved_by orig_sha512_hash sha512_hash uploader source_url original_format), + literal_fields: + ~W(faved_by orig_sha512_hash sha512_hash uploader source_url original_format), ngram_fields: ~W(description), custom_fields: ~W(gallery_id), default_field: {"namespaced_tags.name", :term}, @@ -79,30 +81,35 @@ defmodule Philomena.Images.Query do defp user_fields do fields = anonymous_fields() - Keyword.merge(fields, [ + Keyword.merge(fields, custom_fields: fields[:custom_fields] ++ ~W(my), transforms: Map.merge(fields[:transforms], %{"my" => &user_my_transform/2}) - ]) + ) end defp moderator_fields do fields = user_fields() - Keyword.merge(fields, [ - int_fields: fields[:int_fields] ++ ~W(upvoted_by_id downvoted_by_id true_uploader_id hidden_by_id deleted_by_user_id), - literal_fields: fields[:literal_fields] ++ ~W(fingerprint upvoted_by downvoted_by true_uploader hidden_by deleted_by_user), + Keyword.merge(fields, + int_fields: + fields[:int_fields] ++ + ~W(upvoted_by_id downvoted_by_id true_uploader_id hidden_by_id deleted_by_user_id), + literal_fields: + fields[:literal_fields] ++ + ~W(fingerprint upvoted_by downvoted_by true_uploader hidden_by deleted_by_user), ip_fields: ~W(ip), bool_fields: ~W(deleted), - aliases: Map.merge(fields[:aliases], %{ - "upvoted_by" => "upvoters", - "downvoted_by" => "downvoters", - "upvoted_by_id" => "upvoter_ids", - "downvoted_by_id" => "downvoter_ids", - "hidden_by" => "hidden_by_users", - "hidden_by_id" => "hidden_by_user_ids", - "deleted" => "hidden_from_users" - }) - ]) + aliases: + Map.merge(fields[:aliases], %{ + "upvoted_by" => "upvoters", + "downvoted_by" => "downvoters", + "upvoted_by_id" => "upvoter_ids", + "downvoted_by_id" => "downvoter_ids", + "hidden_by" => "hidden_by_users", + "hidden_by_id" => "hidden_by_user_ids", + "deleted" => "hidden_from_users" + }) + ) end defp parse(fields, context, query_string) do diff --git a/lib/philomena/images/tag_differ.ex b/lib/philomena/images/tag_differ.ex index 17dd0ea0..93d4ef6d 100644 --- a/lib/philomena/images/tag_differ.ex +++ b/lib/philomena/images/tag_differ.ex @@ -9,12 +9,11 @@ defmodule Philomena.Images.TagDiffer do old_set = to_set(old_tags) new_set = to_set(new_tags) - tags = changeset |> get_field(:tags) - added_tags = added_set(old_set, new_set) + tags = changeset |> get_field(:tags) + added_tags = added_set(old_set, new_set) removed_tags = removed_set(old_set, new_set) - {tags, actually_added, actually_removed} = - apply_changes(tags, added_tags, removed_tags) + {tags, actually_added, actually_removed} = apply_changes(tags, added_tags, removed_tags) changeset |> put_change(:added_tags, actually_added) @@ -34,8 +33,7 @@ defmodule Philomena.Images.TagDiffer do |> List.flatten() |> to_set() - added_and_implied_set = - Map.merge(added_set, implied_set) + added_and_implied_set = Map.merge(added_set, implied_set) oc_set = added_and_implied_set @@ -51,6 +49,7 @@ defmodule Philomena.Images.TagDiffer do end defp get_oc_tag([]), do: Map.new() + defp get_oc_tag(_any_oc_tag) do Tag |> where(name: "oc") @@ -82,10 +81,10 @@ defmodule Philomena.Images.TagDiffer do tag_set |> Map.drop(Map.keys(desired_tags)) - tags = desired_tags |> to_tag_list() - actually_added = actually_added |> to_tag_list() + tags = desired_tags |> to_tag_list() + actually_added = actually_added |> to_tag_list() actually_removed = actually_removed |> to_tag_list() {tags, actually_added, actually_removed} end -end \ No newline at end of file +end diff --git a/lib/philomena/images/tag_validator.ex b/lib/philomena/images/tag_validator.ex index 88de8145..a1d588fe 100644 --- a/lib/philomena/images/tag_validator.ex +++ b/lib/philomena/images/tag_validator.ex @@ -1,11 +1,11 @@ defmodule Philomena.Images.TagValidator do import Ecto.Changeset - @safe_rating MapSet.new(["safe"]) + @safe_rating MapSet.new(["safe"]) @sexual_ratings MapSet.new(["suggestive", "questionable", "explicit"]) @horror_ratings MapSet.new(["semi-grimdark", "grimdark"]) - @gross_rating MapSet.new(["grotesque"]) - @empty MapSet.new() + @gross_rating MapSet.new(["grotesque"]) + @empty MapSet.new() def validate_tags(changeset) do tags = changeset |> get_field(:tags) @@ -14,7 +14,7 @@ defmodule Philomena.Images.TagValidator do end defp validate_tag_input(changeset, tags) do - tag_set = extract_names(tags) + tag_set = extract_names(tags) rating_set = ratings(tag_set) changeset @@ -26,10 +26,10 @@ defmodule Philomena.Images.TagValidator do end defp ratings(%MapSet{} = tag_set) do - safe = MapSet.intersection(tag_set, @safe_rating) + safe = MapSet.intersection(tag_set, @safe_rating) sexual = MapSet.intersection(tag_set, @sexual_ratings) horror = MapSet.intersection(tag_set, @horror_ratings) - gross = MapSet.intersection(tag_set, @gross_rating) + gross = MapSet.intersection(tag_set, @gross_rating) %{ safe: safe, @@ -50,16 +50,20 @@ defmodule Philomena.Images.TagValidator do end end - defp validate_has_rating(changeset, %{safe: s, sexual: x, horror: h, gross: g}) when s == @empty and x == @empty and h == @empty and g == @empty do + defp validate_has_rating(changeset, %{safe: s, sexual: x, horror: h, gross: g}) + when s == @empty and x == @empty and h == @empty and g == @empty do changeset |> add_error(:tag_input, "must contain at least one rating tag") end + defp validate_has_rating(changeset, _ratings), do: changeset - defp validate_safe(changeset, %{safe: s, sexual: x, horror: h, gross: g}) when s != @empty and (x != @empty or h != @empty or g != @empty) do + defp validate_safe(changeset, %{safe: s, sexual: x, horror: h, gross: g}) + when s != @empty and (x != @empty or h != @empty or g != @empty) do changeset |> add_error(:tag_input, "may not contain any other rating if safe") end + defp validate_safe(changeset, _ratings), do: changeset defp validate_sexual_exclusion(changeset, %{sexual: x}) do @@ -89,4 +93,4 @@ defmodule Philomena.Images.TagValidator do |> Enum.map(& &1.name) |> MapSet.new() end -end \ No newline at end of file +end diff --git a/lib/philomena/images/thumbnailer.ex b/lib/philomena/images/thumbnailer.ex index 8e9a236a..a58a2816 100644 --- a/lib/philomena/images/thumbnailer.ex +++ b/lib/philomena/images/thumbnailer.ex @@ -22,7 +22,6 @@ defmodule Philomena.Images.Thumbnailer do full: nil ] - def generate_thumbnails(image_id) do image = Repo.get!(Image, image_id) file = image_file(image) @@ -36,11 +35,9 @@ defmodule Philomena.Images.Thumbnailer do recompute_meta(image, file, &Image.process_changeset/2) end - defp apply_edit_script(image, changes), do: Enum.map(changes, &apply_change(image, &1)) - defp apply_change(image, {:intensities, intensities}), do: ImageIntensities.create_image_intensity(image, intensities) @@ -50,14 +47,12 @@ defmodule Philomena.Images.Thumbnailer do defp apply_change(image, {:thumbnails, thumbnails}), do: Enum.map(thumbnails, &apply_thumbnail(image, image_thumb_dir(image), &1)) - defp apply_thumbnail(_image, thumb_dir, {:copy, new_file, destination}), do: copy(new_file, Path.join(thumb_dir, destination)) defp apply_thumbnail(image, thumb_dir, {:symlink_original, destination}), do: symlink(image_file(image), Path.join(thumb_dir, destination)) - defp generate_dupe_reports(image), do: DuplicateReports.generate_reports(image) @@ -70,7 +65,6 @@ defmodule Philomena.Images.Thumbnailer do |> Repo.update!() end - # Copy from source to destination, creating parent directories along # the way and setting the appropriate permission bits when necessary. defp copy(source, destination) do @@ -109,7 +103,6 @@ defmodule Philomena.Images.Thumbnailer do |> File.mkdir_p!() end - defp image_file(%Image{image: image}), do: Path.join(image_file_root(), image) @@ -119,7 +112,6 @@ defmodule Philomena.Images.Thumbnailer do defp time_identifier(time), do: Enum.join([time.year, time.month, time.day], "/") - defp image_file_root, do: Application.get_env(:philomena, :image_file_root) diff --git a/lib/philomena/images/uploader.ex b/lib/philomena/images/uploader.ex index 6688eeb5..35b96394 100644 --- a/lib/philomena/images/uploader.ex +++ b/lib/philomena/images/uploader.ex @@ -21,4 +21,4 @@ defmodule Philomena.Images.Uploader do defp image_file_root do Application.get_env(:philomena, :image_file_root) end -end \ No newline at end of file +end diff --git a/lib/philomena/intensities.ex b/lib/philomena/intensities.ex index a20697a5..250d0fea 100644 --- a/lib/philomena/intensities.ex +++ b/lib/philomena/intensities.ex @@ -20,4 +20,4 @@ defmodule Philomena.Intensities do :error end end -end \ No newline at end of file +end diff --git a/lib/philomena/interactions.ex b/lib/philomena/interactions.ex index 1590e4e9..33703e0c 100644 --- a/lib/philomena/interactions.ex +++ b/lib/philomena/interactions.ex @@ -13,7 +13,7 @@ defmodule Philomena.Interactions do def user_interactions(images, user) do ids = - images + images |> Enum.flat_map(fn nil -> [] %{id: id} -> [id] @@ -23,25 +23,45 @@ defmodule Philomena.Interactions do hide_interactions = ImageHide - |> select([h], %{image_id: h.image_id, user_id: h.user_id, interaction_type: ^"hidden", value: ^""}) + |> select([h], %{ + image_id: h.image_id, + user_id: h.user_id, + interaction_type: ^"hidden", + value: ^"" + }) |> where([h], h.image_id in ^ids) |> where(user_id: ^user.id) fave_interactions = ImageFave - |> select([f], %{image_id: f.image_id, user_id: f.user_id, interaction_type: ^"faved", value: ^""}) + |> select([f], %{ + image_id: f.image_id, + user_id: f.user_id, + interaction_type: ^"faved", + value: ^"" + }) |> where([f], f.image_id in ^ids) |> where(user_id: ^user.id) upvote_interactions = ImageVote - |> select([v], %{image_id: v.image_id, user_id: v.user_id, interaction_type: ^"voted", value: ^"up"}) + |> select([v], %{ + image_id: v.image_id, + user_id: v.user_id, + interaction_type: ^"voted", + value: ^"up" + }) |> where([v], v.image_id in ^ids) |> where(user_id: ^user.id, up: true) downvote_interactions = ImageVote - |> select([v], %{image_id: v.image_id, user_id: v.user_id, interaction_type: ^"voted", value: ^"down"}) + |> select([v], %{ + image_id: v.image_id, + user_id: v.user_id, + interaction_type: ^"voted", + value: ^"down" + }) |> where([v], v.image_id in ^ids) |> where(user_id: ^user.id, up: false) @@ -61,10 +81,20 @@ defmodule Philomena.Interactions do new_hides = Enum.map(source.hiders, &%{image_id: target.id, user_id: &1.id, created_at: now}) new_faves = Enum.map(source.favers, &%{image_id: target.id, user_id: &1.id, created_at: now}) - new_upvotes = Enum.map(source.upvoters, &%{image_id: target.id, user_id: &1.id, created_at: now, up: true}) - new_downvotes = Enum.map(source.downvoters, &%{image_id: target.id, user_id: &1.id, created_at: now, up: false}) - Multi.new + new_upvotes = + Enum.map( + source.upvoters, + &%{image_id: target.id, user_id: &1.id, created_at: now, up: true} + ) + + new_downvotes = + Enum.map( + source.downvoters, + &%{image_id: target.id, user_id: &1.id, created_at: now, up: false} + ) + + Multi.new() |> Multi.run(:hides, fn repo, %{} -> {count, nil} = repo.insert_all(ImageHide, new_hides, on_conflict: :nothing) @@ -85,7 +115,8 @@ defmodule Philomena.Interactions do {:ok, count} end) - |> Multi.run(:image, fn repo, %{hides: hides, faves: faves, upvotes: upvotes, downvotes: downvotes} -> + |> Multi.run(:image, fn repo, + %{hides: hides, faves: faves, upvotes: upvotes, downvotes: downvotes} -> image_query = where(Image, id: ^target.id) repo.update_all( @@ -106,6 +137,7 @@ defmodule Philomena.Interactions do defp union_all_queries([query]), do: query + defp union_all_queries([query | rest]), do: query |> union_all(^union_all_queries(rest)) -end \ No newline at end of file +end diff --git a/lib/philomena/mime.ex b/lib/philomena/mime.ex index 6c1c5571..9ef37285 100644 --- a/lib/philomena/mime.ex +++ b/lib/philomena/mime.ex @@ -30,8 +30,8 @@ defmodule Philomena.Mime do def true_mime("audio/webm"), do: {:ok, "video/webm"} def true_mime(mime) - when mime in ~W(image/gif image/jpeg image/png image/svg+xml video/webm), - do: {:ok, mime} + when mime in ~W(image/gif image/jpeg image/png image/svg+xml video/webm), + do: {:ok, mime} def true_mime(_mime), do: :error -end \ No newline at end of file +end diff --git a/lib/philomena/notifications.ex b/lib/philomena/notifications.ex index 48d85ff9..a82094b3 100644 --- a/lib/philomena/notifications.ex +++ b/lib/philomena/notifications.ex @@ -185,13 +185,14 @@ defmodule Philomena.Notifications do end def notify(_actor_child, [], _params), do: nil + def notify(actor_child, subscriptions, params) do # Don't push to the user that created the notification subscriptions = case actor_child do %{user_id: id} -> subscriptions - |> Enum.reject(& &1.user_id == id) + |> Enum.reject(&(&1.user_id == id)) _ -> subscriptions diff --git a/lib/philomena/poll_options/poll_option.ex b/lib/philomena/poll_options/poll_option.ex index 9b6f10ef..7034ed4d 100644 --- a/lib/philomena/poll_options/poll_option.ex +++ b/lib/philomena/poll_options/poll_option.ex @@ -32,6 +32,7 @@ defmodule Philomena.PollOptions.PollOption do defp ignore_if_blank(%{valid?: false, changes: changes} = changeset) when changes == %{}, do: %{changeset | action: :ignore} + defp ignore_if_blank(changeset), do: changeset end diff --git a/lib/philomena/poll_votes.ex b/lib/philomena/poll_votes.ex index d967ebbb..10829031 100644 --- a/lib/philomena/poll_votes.ex +++ b/lib/philomena/poll_votes.ex @@ -47,13 +47,12 @@ defmodule Philomena.PollVotes do |> Multi.run(:existing_votes, fn _repo, _changes -> # Don't proceed if any votes exist case voted?(poll, user) do - true -> {:error, []} + true -> {:error, []} _false -> {:ok, []} end end) |> Multi.run(:new_votes, fn repo, _changes -> - {_count, votes} = - repo.insert_all(PollVote, poll_votes, returning: true) + {_count, votes} = repo.insert_all(PollVote, poll_votes, returning: true) {:ok, votes} end) @@ -91,13 +90,15 @@ defmodule Philomena.PollVotes do case poll.vote_method do "single" -> Enum.take(votes, 1) - _other -> votes + _other -> votes end end + defp filter_options(_user, _poll, _now, _attrs), do: [] def voted?(nil, _user), do: false def voted?(_poll, nil), do: false + def voted?(%{id: poll_id}, %{id: user_id}) do PollVote |> join(:inner, [pv], _ in assoc(pv, :poll_option)) diff --git a/lib/philomena/polls/poll.ex b/lib/philomena/polls/poll.ex index 1d1d3ee6..eac14246 100644 --- a/lib/philomena/polls/poll.ex +++ b/lib/philomena/polls/poll.ex @@ -44,6 +44,7 @@ defmodule Philomena.Polls.Poll do defp ignore_if_blank(%{valid?: false, changes: changes} = changeset) when changes == %{}, do: %{changeset | action: :ignore} + defp ignore_if_blank(changeset), do: changeset diff --git a/lib/philomena/polymorphic.ex b/lib/philomena/polymorphic.ex index 1d604601..9427b210 100644 --- a/lib/philomena/polymorphic.ex +++ b/lib/philomena/polymorphic.ex @@ -49,6 +49,7 @@ defmodule Philomena.Polymorphic do {type, ids} -> pre = Map.get(@preloads, type, []) + rows = @classes[type] |> where([m], m.id in ^ids) diff --git a/lib/philomena/posts.ex b/lib/philomena/posts.ex index 332c87a1..7d7a2ddc 100644 --- a/lib/philomena/posts.ex +++ b/lib/philomena/posts.ex @@ -55,7 +55,7 @@ defmodule Philomena.Posts do Forum |> where(id: ^topic.forum_id) - Multi.new + Multi.new() |> Multi.run(:post, fn repo, _ -> last_position = Post @@ -71,7 +71,10 @@ defmodule Philomena.Posts do end) |> Multi.run(:update_topic, fn repo, %{post: %{id: post_id}} -> {count, nil} = - repo.update_all(topic_query, inc: [post_count: 1], set: [last_post_id: post_id, last_replied_to_at: now]) + repo.update_all(topic_query, + inc: [post_count: 1], + set: [last_post_id: post_id, last_replied_to_at: now] + ) {:ok, count} end) @@ -88,7 +91,7 @@ defmodule Philomena.Posts do end def notify_post(post) do - spawn fn -> + spawn(fn -> topic = post |> Repo.preload(:topic) @@ -110,7 +113,7 @@ defmodule Philomena.Posts do action: "posted a new reply in" } ) - end + end) post end @@ -132,10 +135,9 @@ defmodule Philomena.Posts do current_body = post.body current_reason = post.edit_reason - post_changes = - Post.changeset(post, attrs, now) + post_changes = Post.changeset(post, attrs, now) - Multi.new + Multi.new() |> Multi.update(:post, post_changes) |> Multi.run(:version, fn _repo, _changes -> Versions.create_version("Post", post.id, editor.id, %{ @@ -203,13 +205,13 @@ defmodule Philomena.Posts do end def reindex_post(%Post{} = post) do - spawn fn -> + spawn(fn -> Post |> preload(^indexing_preloads()) |> where(id: ^post.id) |> Repo.one() |> Elasticsearch.index_document(Post) - end + end) post end diff --git a/lib/philomena/posts/attribution.ex b/lib/philomena/posts/attribution.ex index 0ee12d39..007718ab 100644 --- a/lib/philomena/posts/attribution.ex +++ b/lib/philomena/posts/attribution.ex @@ -10,4 +10,4 @@ defimpl Philomena.Attribution, for: Philomena.Posts.Post do def anonymous?(post) do !!post.anonymous end -end \ No newline at end of file +end diff --git a/lib/philomena/posts/query.ex b/lib/philomena/posts/query.ex index 9eef61f4..599c8001 100644 --- a/lib/philomena/posts/query.ex +++ b/lib/philomena/posts/query.ex @@ -59,22 +59,22 @@ defmodule Philomena.Posts.Query do defp user_fields do fields = anonymous_fields() - Keyword.merge(fields, [ + Keyword.merge(fields, custom_fields: fields[:custom_fields] ++ ~W(my), transforms: Map.merge(fields[:transforms], %{"my" => &user_my_transform/2}) - ]) + ) end defp moderator_fields do fields = user_fields() - Keyword.merge(fields, [ + Keyword.merge(fields, literal_fields: ~W(forum_id topic_id user_id author fingerprint), ip_fields: ~W(ip), bool_fields: ~W(anonymous deleted), custom_fields: fields[:custom_fields] -- ~W(author user_id), transforms: Map.drop(fields[:transforms], ["user_id", "author"]) - ]) + ) end defp parse(fields, context, query_string) do diff --git a/lib/philomena/processors.ex b/lib/philomena/processors.ex index 23452c31..0a6b4afb 100644 --- a/lib/philomena/processors.ex +++ b/lib/philomena/processors.ex @@ -66,4 +66,4 @@ defmodule Philomena.Processors do def intensities(analysis, file) do processor(analysis.mime_type).intensities(analysis, file) end -end \ No newline at end of file +end diff --git a/lib/philomena/processors/gif.ex b/lib/philomena/processors/gif.ex index fe79ddaa..11b5a5ad 100644 --- a/lib/philomena/processors/gif.ex +++ b/lib/philomena/processors/gif.ex @@ -26,12 +26,10 @@ defmodule Philomena.Processors.Gif do intensities end - defp optimize(file) do optimized = Briefly.create!(extname: ".gif") - {_output, 0} = - System.cmd("gifsicle", ["--careful", "-O2", file, "-o", optimized]) + {_output, 0} = System.cmd("gifsicle", ["--careful", "-O2", file, "-o", optimized]) optimized end @@ -40,7 +38,18 @@ defmodule Philomena.Processors.Gif do preview = Briefly.create!(extname: ".png") {_output, 0} = - System.cmd("ffmpeg", ["-loglevel", "0", "-y", "-i", file, "-ss", to_string(duration / 2), "-frames:v", "1", preview]) + System.cmd("ffmpeg", [ + "-loglevel", + "0", + "-y", + "-i", + file, + "-ss", + to_string(duration / 2), + "-frames:v", + "1", + preview + ]) preview end @@ -49,7 +58,16 @@ defmodule Philomena.Processors.Gif do palette = Briefly.create!(extname: ".png") {_output, 0} = - System.cmd("ffmpeg", ["-loglevel", "0", "-y", "-i", file, "-vf", "palettegen=stats_mode=diff", palette]) + System.cmd("ffmpeg", [ + "-loglevel", + "0", + "-y", + "-i", + file, + "-vf", + "palettegen=stats_mode=diff", + palette + ]) palette end @@ -59,7 +77,12 @@ defmodule Philomena.Processors.Gif do [{:symlink_original, "full.gif"}] ++ generate_videos(file) end - defp scale_if_smaller(palette, file, {width, height}, {thumb_name, {target_width, target_height}}) do + defp scale_if_smaller( + palette, + file, + {width, height}, + {thumb_name, {target_width, target_height}} + ) do if width > target_width or height > target_height do scaled = scale(palette, file, {target_width, target_height}) @@ -72,25 +95,73 @@ defmodule Philomena.Processors.Gif do defp scale(palette, file, {width, height}) do scaled = Briefly.create!(extname: ".gif") - scale_filter = "scale=w=#{width}:h=#{height}:force_original_aspect_ratio=decrease" + scale_filter = "scale=w=#{width}:h=#{height}:force_original_aspect_ratio=decrease" palette_filter = "paletteuse=dither=bayer:bayer_scale=5:diff_mode=rectangle" - filter_graph = "[0:v] #{scale_filter} [x]; [x][1:v] #{palette_filter}" + filter_graph = "[0:v] #{scale_filter} [x]; [x][1:v] #{palette_filter}" {_output, 0} = - System.cmd("ffmpeg", ["-loglevel", "0", "-y", "-i", file, "-i", palette, "-lavfi", filter_graph, scaled]) + System.cmd("ffmpeg", [ + "-loglevel", + "0", + "-y", + "-i", + file, + "-i", + palette, + "-lavfi", + filter_graph, + scaled + ]) scaled end defp generate_videos(file) do webm = Briefly.create!(extname: ".webm") - mp4 = Briefly.create!(extname: ".mp4") + mp4 = Briefly.create!(extname: ".mp4") {_output, 0} = - System.cmd("ffmpeg", ["-loglevel", "0", "-y", "-i", file, "-pix_fmt", "yuv420p", "-c:v", "libvpx", "-quality", "good", "-b:v", "5M", webm]) + System.cmd("ffmpeg", [ + "-loglevel", + "0", + "-y", + "-i", + file, + "-pix_fmt", + "yuv420p", + "-c:v", + "libvpx", + "-quality", + "good", + "-b:v", + "5M", + webm + ]) + {_output, 0} = - System.cmd("ffmpeg", ["-loglevel", "0", "-y", "-i", file, "-vf", "scale=ceil(iw/2)*2:ceil(ih/2)*2", "-c:v", "libx264", "-preset", "medium", "-pix_fmt", "yuv420p", "-profile:v", "main", "-crf", "18", "-b:v", "5M", mp4]) - + System.cmd("ffmpeg", [ + "-loglevel", + "0", + "-y", + "-i", + file, + "-vf", + "scale=ceil(iw/2)*2:ceil(ih/2)*2", + "-c:v", + "libx264", + "-preset", + "medium", + "-pix_fmt", + "yuv420p", + "-profile:v", + "main", + "-crf", + "18", + "-b:v", + "5M", + mp4 + ]) + [ {:copy, webm, "full.webm"}, {:copy, mp4, "full.mp4"} diff --git a/lib/philomena/processors/jpeg.ex b/lib/philomena/processors/jpeg.ex index eae7ab08..ae972c5a 100644 --- a/lib/philomena/processors/jpeg.ex +++ b/lib/philomena/processors/jpeg.ex @@ -23,12 +23,10 @@ defmodule Philomena.Processors.Jpeg do intensities end - defp strip(file) do stripped = Briefly.create!(extname: ".jpg") - {_output, 0} = - System.cmd("convert", [file, "-auto-orient", "-strip", stripped]) + {_output, 0} = System.cmd("convert", [file, "-auto-orient", "-strip", stripped]) stripped end @@ -36,8 +34,7 @@ defmodule Philomena.Processors.Jpeg do defp optimize(file) do optimized = Briefly.create!(extname: ".jpg") - {_output, 0} = - System.cmd("jpegtran", ["-optimize", "-outfile", optimized, file]) + {_output, 0} = System.cmd("jpegtran", ["-optimize", "-outfile", optimized, file]) optimized end @@ -62,9 +59,9 @@ defmodule Philomena.Processors.Jpeg do {_output, 0} = System.cmd("ffmpeg", ["-loglevel", "0", "-y", "-i", file, "-vf", scale_filter, scaled]) - {_output, 0} = - System.cmd("jpegtran", ["-optimize", "-outfile", scaled, scaled]) + + {_output, 0} = System.cmd("jpegtran", ["-optimize", "-outfile", scaled, scaled]) scaled end -end \ No newline at end of file +end diff --git a/lib/philomena/processors/png.ex b/lib/philomena/processors/png.ex index 5b919a83..32d5d240 100644 --- a/lib/philomena/processors/png.ex +++ b/lib/philomena/processors/png.ex @@ -23,7 +23,6 @@ defmodule Philomena.Processors.Png do intensities end - defp optimize(file) do optimized = Briefly.create!(extname: ".png") @@ -52,12 +51,14 @@ defmodule Philomena.Processors.Png do defp scale(file, {width, height}) do scaled = Briefly.create!(extname: ".png") - scale_filter = "scale=w=#{width}:h=#{height}:force_original_aspect_ratio=decrease,format=rgb32" + + scale_filter = + "scale=w=#{width}:h=#{height}:force_original_aspect_ratio=decrease,format=rgb32" {_output, 0} = System.cmd("ffmpeg", ["-loglevel", "0", "-y", "-i", file, "-vf", scale_filter, scaled]) - {_output, 0} = - System.cmd("optipng", ["-i0", "-o1", "-quiet", "-clobber", scaled]) + + {_output, 0} = System.cmd("optipng", ["-i0", "-o1", "-quiet", "-clobber", scaled]) scaled end diff --git a/lib/philomena/processors/svg.ex b/lib/philomena/processors/svg.ex index 8a1d72b4..705cee34 100644 --- a/lib/philomena/processors/svg.ex +++ b/lib/philomena/processors/svg.ex @@ -21,12 +21,10 @@ defmodule Philomena.Processors.Svg do intensities end - defp preview(file) do preview = Briefly.create!(extname: ".png") - {_output, 0} = - System.cmd("safe-rsvg-convert", [file, preview]) + {_output, 0} = System.cmd("safe-rsvg-convert", [file, preview]) preview end @@ -47,9 +45,9 @@ defmodule Philomena.Processors.Svg do {_output, 0} = System.cmd("ffmpeg", ["-loglevel", "0", "-y", "-i", preview, "-vf", scale_filter, scaled]) - {_output, 0} = - System.cmd("optipng", ["-i0", "-o1", "-quiet", "-clobber", scaled]) + + {_output, 0} = System.cmd("optipng", ["-i0", "-o1", "-quiet", "-clobber", scaled]) scaled end -end \ No newline at end of file +end diff --git a/lib/philomena/processors/webm.ex b/lib/philomena/processors/webm.ex index 17b2f019..6bd3f924 100644 --- a/lib/philomena/processors/webm.ex +++ b/lib/philomena/processors/webm.ex @@ -25,12 +25,22 @@ defmodule Philomena.Processors.Webm do intensities end - defp preview(duration, file) do preview = Briefly.create!(extname: ".png") {_output, 0} = - System.cmd("ffmpeg", ["-loglevel", "0", "-y", "-i", file, "-ss", to_string(duration / 2), "-frames:v", "1", preview]) + System.cmd("ffmpeg", [ + "-loglevel", + "0", + "-y", + "-i", + file, + "-ss", + to_string(duration / 2), + "-frames:v", + "1", + preview + ]) preview end @@ -44,7 +54,13 @@ defmodule Philomena.Processors.Webm do ] end - defp scale_if_smaller(file, palette, duration, dimensions, {thumb_name, {target_width, target_height}}) do + defp scale_if_smaller( + file, + palette, + duration, + dimensions, + {thumb_name, {target_width, target_height}} + ) do {webm, mp4} = scale_videos(file, palette, dimensions, {target_width, target_height}) cond do @@ -68,27 +84,83 @@ defmodule Philomena.Processors.Webm do defp scale_videos(file, _palette, dimensions, target_dimensions) do {width, height} = box_dimensions(dimensions, target_dimensions) webm = Briefly.create!(extname: ".webm") - mp4 = Briefly.create!(extname: ".mp4") + mp4 = Briefly.create!(extname: ".mp4") scale_filter = "scale=w=#{width}:h=#{height}" {_output, 0} = - System.cmd("ffmpeg", ["-loglevel", "0", "-y", "-i", file, "-c:v", "libvpx", "-quality", "good", "-cpu-used", "3", "-auto-alt-ref", "0", "-crf", "10", "-b:v", "5M", "-vf", scale_filter, webm]) + System.cmd("ffmpeg", [ + "-loglevel", + "0", + "-y", + "-i", + file, + "-c:v", + "libvpx", + "-quality", + "good", + "-cpu-used", + "3", + "-auto-alt-ref", + "0", + "-crf", + "10", + "-b:v", + "5M", + "-vf", + scale_filter, + webm + ]) + {_output, 0} = - System.cmd("ffmpeg", ["-loglevel", "0", "-y", "-i", file, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-profile:v", "main", "-preset", "medium", "-crf", "18", "-b:v", "5M", "-vf", scale_filter, mp4]) + System.cmd("ffmpeg", [ + "-loglevel", + "0", + "-y", + "-i", + file, + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + "-profile:v", + "main", + "-preset", + "medium", + "-crf", + "18", + "-b:v", + "5M", + "-vf", + scale_filter, + mp4 + ]) {webm, mp4} end defp scale_gif(file, palette, duration, {width, height}) do gif = Briefly.create!(extname: ".gif") - scale_filter = "scale=w=#{width}:h=#{height}:force_original_aspect_ratio=decrease" + scale_filter = "scale=w=#{width}:h=#{height}:force_original_aspect_ratio=decrease" palette_filter = "paletteuse=dither=bayer:bayer_scale=5:diff_mode=rectangle" - rate_filter = "fps=1/#{duration / 10},settb=1/2,setpts=N" - filter_graph = "[0:v] #{scale_filter},#{rate_filter} [x]; [x][1:v] #{palette_filter}" + rate_filter = "fps=1/#{duration / 10},settb=1/2,setpts=N" + filter_graph = "[0:v] #{scale_filter},#{rate_filter} [x]; [x][1:v] #{palette_filter}" {_output, 0} = - System.cmd("ffmpeg", ["-loglevel", "0", "-y", "-i", file, "-i", palette, "-lavfi", filter_graph, "-r", "2", gif]) - + System.cmd("ffmpeg", [ + "-loglevel", + "0", + "-y", + "-i", + file, + "-i", + palette, + "-lavfi", + filter_graph, + "-r", + "2", + gif + ]) + gif end @@ -96,7 +168,16 @@ defmodule Philomena.Processors.Webm do palette = Briefly.create!(extname: ".png") {_output, 0} = - System.cmd("ffmpeg", ["-loglevel", "0", "-y", "-i", file, "-vf", "palettegen=stats_mode=diff", palette]) + System.cmd("ffmpeg", [ + "-loglevel", + "0", + "-y", + "-i", + file, + "-vf", + "palettegen=stats_mode=diff", + palette + ]) palette end @@ -104,8 +185,8 @@ defmodule Philomena.Processors.Webm do # x264 requires image dimensions to be a multiple of 2 # -2 = ~1 def box_dimensions({width, height}, {target_width, target_height}) do - ratio = min(target_width / width, target_height / height) - new_width = min(max(trunc(width * ratio) &&& -2, 2), target_width) + ratio = min(target_width / width, target_height / height) + new_width = min(max(trunc(width * ratio) &&& -2, 2), target_width) new_height = min(max(trunc(height * ratio) &&& -2, 2), target_height) {new_width, new_height} diff --git a/lib/philomena/repo.ex b/lib/philomena/repo.ex index 68ab4b49..ea3f05be 100644 --- a/lib/philomena/repo.ex +++ b/lib/philomena/repo.ex @@ -15,7 +15,8 @@ defmodule Philomena.Repo do def isolated_transaction(%Multi{} = multi, level) do Multi.append( - Multi.new |> Multi.run(:isolate, fn repo, _chg -> + Multi.new() + |> Multi.run(:isolate, fn repo, _chg -> repo.query!("SET TRANSACTION ISOLATION LEVEL #{@levels[level]}") {:ok, nil} end), diff --git a/lib/philomena/reports.ex b/lib/philomena/reports.ex index 07e17c72..7331c7e5 100644 --- a/lib/philomena/reports.ex +++ b/lib/philomena/reports.ex @@ -123,14 +123,14 @@ defmodule Philomena.Reports do end def reindex_reports(report_ids) do - spawn fn -> + spawn(fn -> Report |> where([r], r.id in ^report_ids) |> preload([:user, :admin]) |> Repo.all() |> Polymorphic.load_polymorphic(reportable: [reportable_id: :reportable_type]) |> Enum.map(&Elasticsearch.index_document(&1, Report)) - end + end) report_ids end diff --git a/lib/philomena/reports/attribution.ex b/lib/philomena/reports/attribution.ex index 5f264b05..33a61ed2 100644 --- a/lib/philomena/reports/attribution.ex +++ b/lib/philomena/reports/attribution.ex @@ -10,4 +10,4 @@ defimpl Philomena.Attribution, for: Philomena.Reports.Report do def anonymous?(_report) do false end -end \ No newline at end of file +end diff --git a/lib/philomena/reports/query.ex b/lib/philomena/reports/query.ex index 905a17f0..b2a76517 100644 --- a/lib/philomena/reports/query.ex +++ b/lib/philomena/reports/query.ex @@ -5,7 +5,8 @@ defmodule Philomena.Reports.Query do [ int_fields: ~W(id image_id), date_fields: ~W(created_at), - literal_fields: ~W(state user user_id admin admin_id reportable_type reportable_id fingerprint), + literal_fields: + ~W(state user user_id admin admin_id reportable_type reportable_id fingerprint), ip_fields: ~W(ip), bool_fields: ~W(open), ngram_fields: ~W(reason), diff --git a/lib/philomena/reports/report.ex b/lib/philomena/reports/report.ex index f64fd754..5179eecc 100644 --- a/lib/philomena/reports/report.ex +++ b/lib/philomena/reports/report.ex @@ -61,7 +61,15 @@ defmodule Philomena.Reports.Report do |> cast(attrs, [:category, :reason]) |> merge_category() |> change(attribution) - |> validate_required([:reportable_id, :reportable_type, :category, :reason, :ip, :fingerprint, :user_agent]) + |> validate_required([ + :reportable_id, + :reportable_type, + :category, + :reason, + :ip, + :fingerprint, + :user_agent + ]) end defp merge_category(changeset) do diff --git a/lib/philomena/schema/ban_id.ex b/lib/philomena/schema/ban_id.ex index a0f9201f..c1c8ee02 100644 --- a/lib/philomena/schema/ban_id.ex +++ b/lib/philomena/schema/ban_id.ex @@ -6,5 +6,6 @@ defmodule Philomena.Schema.BanId do put_change(changeset, :generated_ban_id, "#{prefix}#{ban_id}") end + def put_ban_id(changeset, _prefix), do: changeset end diff --git a/lib/philomena/schema/search.ex b/lib/philomena/schema/search.ex index 971f7fdb..46de1c06 100644 --- a/lib/philomena/schema/search.ex +++ b/lib/philomena/schema/search.ex @@ -11,7 +11,7 @@ defmodule Philomena.Schema.Search do {:ok, _} -> changeset - _ -> + _ -> add_error(changeset, field, "is invalid") end end diff --git a/lib/philomena/schema/tag_list.ex b/lib/philomena/schema/tag_list.ex index 1062d42d..fdead530 100644 --- a/lib/philomena/schema/tag_list.ex +++ b/lib/philomena/schema/tag_list.ex @@ -47,6 +47,6 @@ defmodule Philomena.Schema.TagList do (list || "") |> String.split(",") |> Enum.map(&String.trim(&1)) - |> Enum.filter(& &1 != "") + |> Enum.filter(&(&1 != "")) end end diff --git a/lib/philomena/scrapers/deviantart.ex b/lib/philomena/scrapers/deviantart.ex index f86b93df..70b08128 100644 --- a/lib/philomena/scrapers/deviantart.ex +++ b/lib/philomena/scrapers/deviantart.ex @@ -48,7 +48,8 @@ defmodule Philomena.Scrapers.Deviantart do end defp try_intermediary_hires!(%{images: [image]} = data) do - [domain, object_uuid, object_name] = Regex.run(@cdnint_regex, image.url, capture: :all_but_first) + [domain, object_uuid, object_name] = + Regex.run(@cdnint_regex, image.url, capture: :all_but_first) built_url = "#{domain}/intermediary/f/#{object_uuid}/#{object_name}" @@ -57,13 +58,13 @@ defmodule Philomena.Scrapers.Deviantart do # This is the high resolution URL. %{ - data | - images: [ - %{ - url: built_url, - camo_url: image.camo_url - } - ] + data + | images: [ + %{ + url: built_url, + camo_url: image.camo_url + } + ] } _ -> @@ -76,24 +77,24 @@ defmodule Philomena.Scrapers.Deviantart do cond do String.match?(image.url, @png_regex) -> %{ - data | - images: [ - %{ - url: String.replace(image.url, @png_regex, "\\1.png\\3"), - camo_url: image.camo_url - } - ] + data + | images: [ + %{ + url: String.replace(image.url, @png_regex, "\\1.png\\3"), + camo_url: image.camo_url + } + ] } String.match?(image.url, @jpg_regex) -> %{ - data | - images: [ - %{ - url: String.replace(image.url, @jpg_regex, "\\g{1}100\\3"), - camo_url: image.camo_url - } - ] + data + | images: [ + %{ + url: String.replace(image.url, @jpg_regex, "\\g{1}100\\3"), + camo_url: image.camo_url + } + ] } true -> @@ -104,6 +105,7 @@ defmodule Philomena.Scrapers.Deviantart do defp try_old_hires!(%{source_url: source, images: [image]} = data) do [serial] = Regex.run(@serial_regex, source, capture: :all_but_first) + base36 = serial |> String.to_integer() @@ -118,13 +120,13 @@ defmodule Philomena.Scrapers.Deviantart do {_location, link} = Enum.find(headers, fn {header, _val} -> header == "Location" end) %{ - data | - images: [ - %{ - url: link, - camo_url: image.camo_url - } - ] + data + | images: [ + %{ + url: link, + camo_url: image.camo_url + } + ] } _ -> @@ -135,6 +137,7 @@ defmodule Philomena.Scrapers.Deviantart do # Workaround for benoitc/hackney#273 defp follow_redirect(_url, 0), do: nil + defp follow_redirect(url, max_times) do case Philomena.Http.get!(url) do %HTTPoison.Response{headers: headers, status_code: code} when code in [301, 302] -> diff --git a/lib/philomena/scrapers/raw.ex b/lib/philomena/scrapers/raw.ex index 548f34c5..6a478d08 100644 --- a/lib/philomena/scrapers/raw.ex +++ b/lib/philomena/scrapers/raw.ex @@ -27,4 +27,4 @@ defmodule Philomena.Scrapers.Raw do ] } end -end \ No newline at end of file +end diff --git a/lib/philomena/scrapers/tumblr.ex b/lib/philomena/scrapers/tumblr.ex index a720e932..7b22446d 100644 --- a/lib/philomena/scrapers/tumblr.ex +++ b/lib/philomena/scrapers/tumblr.ex @@ -16,7 +16,10 @@ defmodule Philomena.Scrapers.Tumblr do def scrape(uri, url) do [post_id] = Regex.run(@url_regex, url, capture: :all_but_first) - api_url = "https://api.tumblr.com/v2/blog/#{uri.host}/posts/photo?id=#{post_id}&api_key=#{tumblr_api_key()}" + api_url = + "https://api.tumblr.com/v2/blog/#{uri.host}/posts/photo?id=#{post_id}&api_key=#{ + tumblr_api_key() + }" Philomena.Http.get!(api_url) |> json!() @@ -36,7 +39,7 @@ defmodule Philomena.Scrapers.Tumblr do image = upsize(photo["original_size"]["url"]) %{"url" => preview} = - Enum.find(photo["alt_sizes"], & &1["width"] == 400) || %{"url" => image} + Enum.find(photo["alt_sizes"], &(&1["width"] == 400)) || %{"url" => image} %{url: image, camo_url: Camo.Image.image_url(preview)} end) @@ -94,4 +97,4 @@ defmodule Philomena.Scrapers.Tumblr do defp tumblr_api_key do Application.get_env(:philomena, :tumblr_api_key) end -end \ No newline at end of file +end diff --git a/lib/philomena/scrapers/twitter.ex b/lib/philomena/scrapers/twitter.ex index 31ffc594..967b3682 100644 --- a/lib/philomena/scrapers/twitter.ex +++ b/lib/philomena/scrapers/twitter.ex @@ -17,7 +17,12 @@ defmodule Philomena.Scrapers.Twitter do defp extract_data(tweet) do images = tweet["entities"]["media"] - |> Enum.map(&%{url: &1["media_url_https"] <> ":orig", camo_url: Camo.Image.image_url(&1["media_url_https"])}) + |> Enum.map( + &%{ + url: &1["media_url_https"] <> ":orig", + camo_url: Camo.Image.image_url(&1["media_url_https"]) + } + ) %{ source_url: tweet["url"], @@ -34,7 +39,10 @@ defmodule Philomena.Scrapers.Twitter do [user, status_id] = Regex.run(@url_regex, url, capture: :all_but_first) mobile_url = "https://mobile.twitter.com/#{user}/status/#{status_id}" - api_url = "https://api.twitter.com/2/timeline/conversation/#{status_id}.json?tweet_mode=extended" + + api_url = + "https://api.twitter.com/2/timeline/conversation/#{status_id}.json?tweet_mode=extended" + url = "https://twitter.com/#{user}/status/#{status_id}" {gt, bearer} = @@ -42,7 +50,7 @@ defmodule Philomena.Scrapers.Twitter do |> Map.get(:body) |> extract_guest_token_and_bearer() - Philomena.Http.get!(api_url, ["Authorization": "Bearer #{bearer}", "x-guest-token": gt]) + Philomena.Http.get!(api_url, Authorization: "Bearer #{bearer}", "x-guest-token": gt) |> Map.get(:body) |> Jason.decode!() |> Map.get("globalObjects") diff --git a/lib/philomena/servers/config.ex b/lib/philomena/servers/config.ex index c95a8b9a..58455d40 100644 --- a/lib/philomena/servers/config.ex +++ b/lib/philomena/servers/config.ex @@ -43,12 +43,12 @@ defmodule Philomena.Servers.Config do defp maybe_update_state(state, key, false) do Map.put(state, key, load_config(key)) end + defp maybe_update_state(state, _key, _true), do: state defp load_config(name) do with {:ok, text} <- File.read("#{app_dir()}/config/#{name}.json"), - {:ok, json} <- Jason.decode(text) - do + {:ok, json} <- Jason.decode(text) do json end end diff --git a/lib/philomena/servers/image_processor.ex b/lib/philomena/servers/image_processor.ex index f8904570..68e48557 100644 --- a/lib/philomena/servers/image_processor.ex +++ b/lib/philomena/servers/image_processor.ex @@ -42,4 +42,4 @@ defmodule Philomena.Servers.ImageProcessor do def handle_call(:wait, _from, []) do {:reply, nil, []} end -end \ No newline at end of file +end diff --git a/lib/philomena/servers/user_fingerprint_updater.ex b/lib/philomena/servers/user_fingerprint_updater.ex index ef169620..ed421b12 100644 --- a/lib/philomena/servers/user_fingerprint_updater.ex +++ b/lib/philomena/servers/user_fingerprint_updater.ex @@ -14,10 +14,12 @@ defmodule Philomena.Servers.UserFingerprintUpdater do {:ok, spawn_link(&init/0)} end - def cast(user_id, <<"c", _rest::binary>> = fingerprint, updated_at) when byte_size(fingerprint) <= 12 do + def cast(user_id, <<"c", _rest::binary>> = fingerprint, updated_at) + when byte_size(fingerprint) <= 12 do pid = Process.whereis(:fingerprint_updater) if pid, do: send(pid, {user_id, fingerprint, updated_at}) end + def cast(_user_id, _fingerprint, _updated_at), do: nil defp init do @@ -27,9 +29,14 @@ defmodule Philomena.Servers.UserFingerprintUpdater do defp run do user_fps = Enum.map(receive_all(), &into_insert_all/1) - update_query = update(UserFingerprint, inc: [uses: 1], set: [updated_at: fragment("EXCLUDED.updated_at")]) - Repo.insert_all(UserFingerprint, user_fps, on_conflict: update_query, conflict_target: [:user_id, :fingerprint]) + update_query = + update(UserFingerprint, inc: [uses: 1], set: [updated_at: fragment("EXCLUDED.updated_at")]) + + Repo.insert_all(UserFingerprint, user_fps, + on_conflict: update_query, + conflict_target: [:user_id, :fingerprint] + ) :timer.sleep(:timer.seconds(60)) diff --git a/lib/philomena/servers/user_ip_updater.ex b/lib/philomena/servers/user_ip_updater.ex index 096ae21f..e8ea2889 100644 --- a/lib/philomena/servers/user_ip_updater.ex +++ b/lib/philomena/servers/user_ip_updater.ex @@ -26,7 +26,9 @@ defmodule Philomena.Servers.UserIpUpdater do defp run do user_ips = Enum.map(receive_all(), &into_insert_all/1) - update_query = update(UserIp, inc: [uses: 1], set: [updated_at: fragment("EXCLUDED.updated_at")]) + + update_query = + update(UserIp, inc: [uses: 1], set: [updated_at: fragment("EXCLUDED.updated_at")]) Repo.insert_all(UserIp, user_ips, on_conflict: update_query, conflict_target: [:user_id, :ip]) diff --git a/lib/philomena/servers/user_link_updater.ex b/lib/philomena/servers/user_link_updater.ex index 13064cd7..8c76451f 100644 --- a/lib/philomena/servers/user_link_updater.ex +++ b/lib/philomena/servers/user_link_updater.ex @@ -3,11 +3,11 @@ defmodule Philomena.Servers.UserLinkUpdater do alias Philomena.Repo import Ecto.Query - @seven_days 7*24*60*60 - @three_days 3*24*60*60 - @twelve_hours 12*60*60 - @one_hour 60*60 - @two_minutes 2*60 + @seven_days 7 * 24 * 60 * 60 + @three_days 3 * 24 * 60 * 60 + @twelve_hours 12 * 60 * 60 + @one_hour 60 * 60 + @two_minutes 2 * 60 def child_spec([]) do %{ diff --git a/lib/philomena/sha512.ex b/lib/philomena/sha512.ex index 4b86ff26..1b500440 100644 --- a/lib/philomena/sha512.ex +++ b/lib/philomena/sha512.ex @@ -8,4 +8,4 @@ defmodule Philomena.Sha512 do |> :crypto.hash_final() |> Base.encode16(case: :lower) end -end \ No newline at end of file +end diff --git a/lib/philomena/slug.ex b/lib/philomena/slug.ex index 1569aa5e..385782d4 100644 --- a/lib/philomena/slug.ex +++ b/lib/philomena/slug.ex @@ -27,11 +27,16 @@ defmodule Philomena.Slug do @spec destructive_slug(String.t()) :: String.t() def destructive_slug(input) when is_binary(input) do input - |> String.replace(~r/[^ -~]/, "") # 1 - |> String.replace(~r/[^a-zA-Z0-9]+/, "-") # 2 - |> String.replace(~r/\A-|-\z/, "") # 3 - |> String.downcase() # 4 + # 1 + |> String.replace(~r/[^ -~]/, "") + # 2 + |> String.replace(~r/[^a-zA-Z0-9]+/, "-") + # 3 + |> String.replace(~r/\A-|-\z/, "") + # 4 + |> String.downcase() end + def destructive_slug(_input), do: "" def slug(string) when is_binary(string) do diff --git a/lib/philomena/source_changes/attribution.ex b/lib/philomena/source_changes/attribution.ex index dc97ff22..7bc8fa43 100644 --- a/lib/philomena/source_changes/attribution.ex +++ b/lib/philomena/source_changes/attribution.ex @@ -10,4 +10,4 @@ defimpl Philomena.Attribution, for: Philomena.SourceChanges.SourceChange do def anonymous?(source_change) do source_change.user_id == source_change.image.user_id and !!source_change.image.anonymous end -end \ No newline at end of file +end diff --git a/lib/philomena/static_pages.ex b/lib/philomena/static_pages.ex index 8db02d76..9960aa09 100644 --- a/lib/philomena/static_pages.ex +++ b/lib/philomena/static_pages.ex @@ -53,7 +53,7 @@ defmodule Philomena.StaticPages do """ def create_static_page(user, attrs \\ %{}) do static_page = StaticPage.changeset(%StaticPage{}, attrs) - + Multi.new() |> Multi.insert(:static_page, static_page) |> Multi.run(:version, fn repo, %{static_page: static_page} -> diff --git a/lib/philomena/tag_changes.ex b/lib/philomena/tag_changes.ex index 4d96cf4a..77dbce85 100644 --- a/lib/philomena/tag_changes.ex +++ b/lib/philomena/tag_changes.ex @@ -42,22 +42,25 @@ defmodule Philomena.TagChanges do end) |> select([t], [t.image_id, t.tag_id]) - to_add = - Enum.map(removed, &%{image_id: &1.image_id, tag_id: &1.tag_id}) + to_add = Enum.map(removed, &%{image_id: &1.image_id, tag_id: &1.tag_id}) Repo.transaction(fn -> - {_count, inserted} = Repo.insert_all(Tagging, to_add, on_conflict: :nothing, returning: [:image_id, :tag_id]) + {_count, inserted} = + Repo.insert_all(Tagging, to_add, on_conflict: :nothing, returning: [:image_id, :tag_id]) + {_count, deleted} = Repo.delete_all(to_remove) inserted = Enum.map(inserted, &[&1.image_id, &1.tag_id]) - added_changes = Enum.map(inserted, fn [image_id, tag_id] -> - Map.merge(tag_change_attributes, %{image_id: image_id, tag_id: tag_id, added: true}) - end) + added_changes = + Enum.map(inserted, fn [image_id, tag_id] -> + Map.merge(tag_change_attributes, %{image_id: image_id, tag_id: tag_id, added: true}) + end) - removed_changes = Enum.map(deleted, fn [image_id, tag_id] -> - Map.merge(tag_change_attributes, %{image_id: image_id, tag_id: tag_id, added: false}) - end) + removed_changes = + Enum.map(deleted, fn [image_id, tag_id] -> + Map.merge(tag_change_attributes, %{image_id: image_id, tag_id: tag_id, added: false}) + end) Repo.insert_all(TagChange, added_changes ++ removed_changes) @@ -68,15 +71,18 @@ defmodule Philomena.TagChanges do added_upserts = inserted |> Enum.group_by(fn [_image_id, tag_id] -> tag_id end) - |> Enum.map(fn {tag_id, instances} -> Map.merge(tag_attributes, %{id: tag_id, images_count: length(instances)}) end) + |> Enum.map(fn {tag_id, instances} -> + Map.merge(tag_attributes, %{id: tag_id, images_count: length(instances)}) + end) removed_upserts = deleted |> Enum.group_by(fn [_image_id, tag_id] -> tag_id end) - |> Enum.map(fn {tag_id, instances} -> Map.merge(tag_attributes, %{id: tag_id, images_count: -length(instances)}) end) + |> Enum.map(fn {tag_id, instances} -> + Map.merge(tag_attributes, %{id: tag_id, images_count: -length(instances)}) + end) - update_query = - update(Tag, inc: [images_count: fragment("EXCLUDED.images_count")]) + update_query = update(Tag, inc: [images_count: fragment("EXCLUDED.images_count")]) upserts = added_upserts ++ removed_upserts diff --git a/lib/philomena/tag_changes/attribution.ex b/lib/philomena/tag_changes/attribution.ex index 4a686613..0060fd7f 100644 --- a/lib/philomena/tag_changes/attribution.ex +++ b/lib/philomena/tag_changes/attribution.ex @@ -10,4 +10,4 @@ defimpl Philomena.Attribution, for: Philomena.TagChanges.TagChange do def anonymous?(tag_change) do tag_change.user_id == tag_change.image.user_id and !!tag_change.image.anonymous end -end \ No newline at end of file +end diff --git a/lib/philomena/tags.ex b/lib/philomena/tags.ex index b1ed1a82..d7740fe7 100644 --- a/lib/philomena/tags.ex +++ b/lib/philomena/tags.ex @@ -40,7 +40,7 @@ defmodule Philomena.Tags do # Now get rid of the aliases existent_tags = existent_tags - |> Enum.map(& &1.aliased_tag || &1) + |> Enum.map(&(&1.aliased_tag || &1)) new_tags = nonexistent_tag_names @@ -107,6 +107,7 @@ defmodule Philomena.Tags do """ def update_tag(%Tag{} = tag, attrs) do tag_input = Tag.parse_tag_list(attrs["implied_tag_list"]) + implied_tags = Tag |> where([t], t.name in ^tag_input) @@ -120,7 +121,7 @@ defmodule Philomena.Tags do def update_tag_image(%Tag{} = tag, attrs) do changeset = Uploader.analyze_upload(tag, attrs) - Multi.new + Multi.new() |> Multi.update(:tag, changeset) |> Multi.run(:update_file, fn _repo, %{tag: tag} -> Uploader.persist_upload(tag) @@ -134,7 +135,7 @@ defmodule Philomena.Tags do def remove_tag_image(%Tag{} = tag) do changeset = Tag.remove_image_changeset(tag) - Multi.new + Multi.new() |> Multi.update(:tag, changeset) |> Multi.run(:remove_file, fn _repo, %{tag: tag} -> Uploader.unpersist_old_upload(tag) @@ -177,9 +178,14 @@ defmodule Philomena.Tags do def alias_tag(%Tag{} = tag, attrs) do target_tag = Repo.get_by!(Tag, name: attrs["target_tag"]) - filters_hidden = where(Filter, [f], fragment("? @> ARRAY[?]::integer[]", f.hidden_tag_ids, ^tag.id)) - filters_spoilered = where(Filter, [f], fragment("? @> ARRAY[?]::integer[]", f.spoilered_tag_ids, ^tag.id)) - users_watching = where(User, [u], fragment("? @> ARRAY[?]::integer[]", u.watched_tag_ids, ^tag.id)) + filters_hidden = + where(Filter, [f], fragment("? @> ARRAY[?]::integer[]", f.hidden_tag_ids, ^tag.id)) + + filters_spoilered = + where(Filter, [f], fragment("? @> ARRAY[?]::integer[]", f.spoilered_tag_ids, ^tag.id)) + + users_watching = + where(User, [u], fragment("? @> ARRAY[?]::integer[]", u.watched_tag_ids, ^tag.id)) array_replace(filters_hidden, :hidden_tag_ids, tag.id, target_tag.id) array_replace(filters_spoilered, :spoilered_tag_ids, tag.id, target_tag.id) @@ -188,10 +194,10 @@ defmodule Philomena.Tags do # Manual insert all because ecto won't do it for us Repo.query!( "INSERT INTO image_taggings (image_id, tag_id) " <> - "SELECT i.id, #{target_tag.id} FROM images i " <> - "INNER JOIN image_taggings it on it.image_id = i.id " <> - "WHERE it.tag_id = #{tag.id} " <> - "ON CONFLICT DO NOTHING" + "SELECT i.id, #{target_tag.id} FROM images i " <> + "INNER JOIN image_taggings it on it.image_id = i.id " <> + "WHERE it.tag_id = #{tag.id} " <> + "ON CONFLICT DO NOTHING" ) # Delete taggings on the source tag @@ -211,7 +217,9 @@ defmodule Philomena.Tags do # Update counter Tag |> where(id: ^tag.id) - |> Repo.update_all(set: [images_count: 0, aliased_tag_id: target_tag.id, updated_at: DateTime.utc_now()]) + |> Repo.update_all( + set: [images_count: 0, aliased_tag_id: target_tag.id, updated_at: DateTime.utc_now()] + ) # Finally, reindex reindex_tag_images(target_tag) @@ -274,9 +282,11 @@ defmodule Philomena.Tags do |> Repo.all() |> Enum.map(&%{&1 | image_id: String.to_integer(&1.image_id)}) - {:ok, tag_ids} = - Repo.transaction fn -> - {_count, taggings} = Repo.insert_all(Tagging, taggings, on_conflict: :nothing, returning: [:tag_id]) + {:ok, tag_ids} = + Repo.transaction(fn -> + {_count, taggings} = + Repo.insert_all(Tagging, taggings, on_conflict: :nothing, returning: [:tag_id]) + tag_ids = Enum.map(taggings, & &1.tag_id) Tag @@ -284,7 +294,7 @@ defmodule Philomena.Tags do |> Repo.update_all(inc: [images_count: 1]) tag_ids - end + end) Tag |> where([t], t.id in ^tag_ids) @@ -309,7 +319,7 @@ defmodule Philomena.Tags do end def reindex_tags(tags) do - spawn fn -> + spawn(fn -> ids = tags |> Enum.map(& &1.id) @@ -318,7 +328,7 @@ defmodule Philomena.Tags do |> preload(^indexing_preloads()) |> where([t], t.id in ^ids) |> Elasticsearch.reindex(Tag) - end + end) tags end diff --git a/lib/philomena/tags/query.ex b/lib/philomena/tags/query.ex index 849daa57..56a78544 100644 --- a/lib/philomena/tags/query.ex +++ b/lib/philomena/tags/query.ex @@ -4,7 +4,8 @@ defmodule Philomena.Tags.Query do defp fields do [ int_fields: ~W(id images), - literal_fields: ~W(slug name name_in_namespace namespace implies alias_of implied_by aliases category analyzed_name), + literal_fields: + ~W(slug name name_in_namespace namespace implies alias_of implied_by aliases category analyzed_name), bool_fields: ~W(aliased), ngram_fields: ~W(description short_description), default_field: {"analyzed_name", :ngram}, diff --git a/lib/philomena/tags/tag.ex b/lib/philomena/tags/tag.ex index 564c37ba..5468e6a1 100644 --- a/lib/philomena/tags/tag.ex +++ b/lib/philomena/tags/tag.ex @@ -45,8 +45,16 @@ defmodule Philomena.Tags.Tag do schema "tags" do belongs_to :aliased_tag, Tag, source: :aliased_tag_id has_many :aliases, Tag, foreign_key: :aliased_tag_id - many_to_many :implied_tags, Tag, join_through: "tags_implied_tags", join_keys: [tag_id: :id, implied_tag_id: :id], on_replace: :delete - many_to_many :implied_by_tags, Tag, join_through: "tags_implied_tags", join_keys: [implied_tag_id: :id, tag_id: :id] + + many_to_many :implied_tags, Tag, + join_through: "tags_implied_tags", + join_keys: [tag_id: :id, implied_tag_id: :id], + on_replace: :delete + + many_to_many :implied_by_tags, Tag, + join_through: "tags_implied_tags", + join_keys: [implied_tag_id: :id, tag_id: :id] + has_many :public_links, UserLink, where: [public: true, aasm_state: "verified"] has_many :hidden_links, UserLink, where: [public: false, aasm_state: "verified"] has_many :dnp_entries, DnpEntry, where: [aasm_state: "listed"] @@ -118,23 +126,25 @@ defmodule Philomena.Tags.Tag do |> to_string() |> String.split(",") |> Enum.map(&clean_tag_name/1) - |> Enum.reject(&"" == &1) + |> Enum.reject(&("" == &1)) end def display_order(tags) do tags - |> Enum.sort_by(&{ - &1.category != "error", - &1.category != "rating", - &1.category != "origin", - &1.category != "character", - &1.category != "oc", - &1.category != "species", - &1.category != "content-fanmade", - &1.category != "content-official", - &1.category != "spoiler", - &1.name - }) + |> Enum.sort_by( + &{ + &1.category != "error", + &1.category != "rating", + &1.category != "origin", + &1.category != "character", + &1.category != "oc", + &1.category != "species", + &1.category != "content-fanmade", + &1.category != "content-official", + &1.category != "spoiler", + &1.name + } + ) end def categories do @@ -175,13 +185,16 @@ defmodule Philomena.Tags.Tag do defp join_namespace_parts([_name], original_name), do: original_name + defp join_namespace_parts([namespace, name], _original_name) when namespace in @namespaces, do: namespace <> ":" <> name + defp join_namespace_parts([_namespace, _name], original_name), do: original_name defp ununderscore(<<"artist:", _rest::binary>> = name), do: name + defp ununderscore(name), do: String.replace(name, "_", " ") @@ -222,7 +235,7 @@ defmodule Philomena.Tags.Tag do namespace = changeset |> get_field(:namespace) case @namespace_categories[namespace] do - nil -> changeset + nil -> changeset category -> change(changeset, category: category) end end diff --git a/lib/philomena/textile/renderer.ex b/lib/philomena/textile/renderer.ex index 6644e548..c6fc1686 100644 --- a/lib/philomena/textile/renderer.ex +++ b/lib/philomena/textile/renderer.ex @@ -23,11 +23,12 @@ defmodule Philomena.Textile.Renderer do |> Enum.flat_map(fn tree -> tree |> Enum.flat_map(fn - {:text, text} -> - [text] - _ -> - [] - end) + {:text, text} -> + [text] + + _ -> + [] + end) end) |> find_images @@ -75,15 +76,27 @@ defmodule Philomena.Textile.Renderer do match [image, "p"] -> - Phoenix.View.render(@image_view, "_image_target.html", image: image, size: :medium, conn: conn) + Phoenix.View.render(@image_view, "_image_target.html", + image: image, + size: :medium, + conn: conn + ) |> safe_to_string() [image, "t"] -> - Phoenix.View.render(@image_view, "_image_target.html", image: image, size: :small, conn: conn) + Phoenix.View.render(@image_view, "_image_target.html", + image: image, + size: :small, + conn: conn + ) |> safe_to_string() [image, "s"] -> - Phoenix.View.render(@image_view, "_image_target.html", image: image, size: :thumb_small, conn: conn) + Phoenix.View.render(@image_view, "_image_target.html", + image: image, + size: :thumb_small, + conn: conn + ) |> safe_to_string() [image] -> @@ -103,6 +116,7 @@ defmodule Philomena.Textile.Renderer do end defp load_images([]), do: %{} + defp load_images(ids) do Image |> where([i], i.id in ^ids) diff --git a/lib/philomena/topics.ex b/lib/philomena/topics.ex index fbbb05e2..36490642 100644 --- a/lib/philomena/topics.ex +++ b/lib/philomena/topics.ex @@ -41,11 +41,12 @@ defmodule Philomena.Topics do """ def create_topic(forum, attribution, attrs \\ %{}) do now = DateTime.utc_now() |> DateTime.truncate(:second) + topic = %Topic{} |> Topic.creation_changeset(attrs, forum, attribution) - Multi.new + Multi.new() |> Multi.insert(:topic, topic) |> Multi.run(:update_topic, fn repo, %{topic: topic} -> {count, nil} = @@ -59,7 +60,10 @@ defmodule Philomena.Topics do {count, nil} = Forum |> where(id: ^topic.forum_id) - |> repo.update_all(inc: [post_count: 1, topic_count: 1], set: [last_post_id: hd(topic.posts).id]) + |> repo.update_all( + inc: [post_count: 1, topic_count: 1], + set: [last_post_id: hd(topic.posts).id] + ) {:ok, count} end) @@ -70,7 +74,7 @@ defmodule Philomena.Topics do end def notify_topic(topic) do - spawn fn -> + spawn(fn -> forum = topic |> Repo.preload(:forum) @@ -92,7 +96,7 @@ defmodule Philomena.Topics do action: "posted a new topic in" } ) - end + end) topic end @@ -147,6 +151,7 @@ defmodule Philomena.Topics do alias Philomena.Topics.Subscription def subscribed?(_topic, nil), do: false + def subscribed?(topic, user) do Subscription |> where(topic_id: ^topic.id, user_id: ^user.id) @@ -166,6 +171,7 @@ defmodule Philomena.Topics do """ def create_subscription(_topic, nil), do: {:ok, nil} + def create_subscription(topic, user) do %Subscription{topic_id: topic.id, user_id: user.id} |> Subscription.changeset(%{}) @@ -210,12 +216,12 @@ defmodule Philomena.Topics do Topic.unlock_changeset(topic) |> Repo.update() end - + def move_topic(topic, new_forum_id) do old_forum_id = topic.forum_id topic_changes = Topic.move_changeset(topic, new_forum_id) - Multi.new + Multi.new() |> Multi.update(:topic, topic_changes) |> Multi.run(:update_old_forum, fn repo, %{topic: topic} -> {count, nil} = @@ -247,6 +253,7 @@ defmodule Philomena.Topics do end def clear_notification(_topic, nil), do: nil + def clear_notification(topic, user) do Notifications.delete_unread_notification("Topic", topic.id, user) end diff --git a/lib/philomena/topics/attribution.ex b/lib/philomena/topics/attribution.ex index acb9d7fd..66f2cfde 100644 --- a/lib/philomena/topics/attribution.ex +++ b/lib/philomena/topics/attribution.ex @@ -10,4 +10,4 @@ defimpl Philomena.Attribution, for: Philomena.Topics.Topic do def anonymous?(topic) do !!topic.anonymous end -end \ No newline at end of file +end diff --git a/lib/philomena/uploader.ex b/lib/philomena/uploader.ex index 2f8ce01f..8e73db47 100644 --- a/lib/philomena/uploader.ex +++ b/lib/philomena/uploader.ex @@ -13,11 +13,11 @@ defmodule Philomena.Uploader do callback on the model or changeset passed in with attributes set on the field_name. """ - @spec analyze_upload(any(), String.t(), Plug.Upload.t(), (any(), map() -> Ecto.Changeset.t())) :: Ecto.Changeset.t() + @spec analyze_upload(any(), String.t(), Plug.Upload.t(), (any(), map() -> Ecto.Changeset.t())) :: + Ecto.Changeset.t() def analyze_upload(model_or_changeset, field_name, upload_parameter, changeset_fn) do with {:ok, analysis} <- Analyzers.analyze(upload_parameter), - analysis <- extra_attributes(analysis, upload_parameter) - do + analysis <- extra_attributes(analysis, upload_parameter) do removed = model_or_changeset |> change() @@ -25,16 +25,16 @@ defmodule Philomena.Uploader do attributes = %{ - "name" => analysis.name, - "width" => analysis.width, - "height" => analysis.height, - "size" => analysis.size, - "format" => analysis.extension, - "mime_type" => analysis.mime_type, - "aspect_ratio" => analysis.aspect_ratio, + "name" => analysis.name, + "width" => analysis.width, + "height" => analysis.height, + "size" => analysis.size, + "format" => analysis.extension, + "mime_type" => analysis.mime_type, + "aspect_ratio" => analysis.aspect_ratio, "orig_sha512_hash" => analysis.sha512, - "sha512_hash" => analysis.sha512, - "is_animated" => analysis.animated? + "sha512_hash" => analysis.sha512, + "is_animated" => analysis.animated? } |> prefix_attributes(field_name) |> Map.put(field_name, analysis.new_name) @@ -55,9 +55,9 @@ defmodule Philomena.Uploader do @spec persist_upload(any(), String.t(), String.t()) :: any() def persist_upload(model, file_root, field_name) do source = Map.get(model, field(upload_key(field_name))) - dest = Map.get(model, field(field_name)) + dest = Map.get(model, field(field_name)) target = Path.join(file_root, dest) - dir = Path.dirname(target) + dir = Path.dirname(target) # Create the target directory if it doesn't exist yet, # then write the file. @@ -78,10 +78,10 @@ defmodule Philomena.Uploader do defp extra_attributes(analysis, %Plug.Upload{path: path, filename: filename}) do {width, height} = analysis.dimensions - aspect_ratio = aspect_ratio(width, height) + aspect_ratio = aspect_ratio(width, height) - stat = File.stat!(path) - sha512 = Sha512.file(path) + stat = File.stat!(path) + sha512 = Sha512.file(path) new_name = Filename.build(analysis.extension) analysis @@ -109,4 +109,4 @@ defmodule Philomena.Uploader do defp remove_key(field_name), do: "removed_#{field_name}" defp field(field_name), do: String.to_existing_atom(field_name) -end \ No newline at end of file +end diff --git a/lib/philomena/user_downvote_wipe.ex b/lib/philomena/user_downvote_wipe.ex index 9e39f9bb..c2751376 100644 --- a/lib/philomena/user_downvote_wipe.ex +++ b/lib/philomena/user_downvote_wipe.ex @@ -23,6 +23,7 @@ defmodule Philomena.UserDownvoteWipe do |> where(user_id: ^user.id, up: true) |> Batch.query_batches([id_field: :image_id], fn queryable -> {_, image_ids} = Repo.delete_all(select(queryable, [i_v], i_v.image_id)) + Repo.update_all(where(Image, [i], i.id in ^image_ids), inc: [upvotes_count: -1, score: -1]) reindex(image_ids) @@ -33,7 +34,7 @@ defmodule Philomena.UserDownvoteWipe do |> Batch.query_batches([id_field: :image_id], fn queryable -> {_, image_ids} = Repo.delete_all(select(queryable, [i_f], i_f.image_id)) Repo.update_all(where(Image, [i], i.id in ^image_ids), inc: [faves_count: -1]) - + reindex(image_ids) end) end diff --git a/lib/philomena/user_links.ex b/lib/philomena/user_links.ex index d8e498ed..277ec21d 100644 --- a/lib/philomena/user_links.ex +++ b/lib/philomena/user_links.ex @@ -92,9 +92,13 @@ defmodule Philomena.UserLinks do now = DateTime.utc_now() |> DateTime.truncate(:second) with badge when not is_nil(badge) <- repo.get_by(limit(Badge, 1), title: "Artist"), - nil <- repo.get_by(limit(Award, 1), badge_id: badge.id, user_id: user_link.user_id) - do - %Award{badge_id: badge.id, user_id: user_link.user_id, awarded_by_id: user.id, awarded_on: now} + nil <- repo.get_by(limit(Award, 1), badge_id: badge.id, user_id: user_link.user_id) do + %Award{ + badge_id: badge.id, + user_id: user_link.user_id, + awarded_by_id: user.id, + awarded_on: now + } |> Award.changeset(%{}) |> repo.insert() else diff --git a/lib/philomena/user_statistics.ex b/lib/philomena/user_statistics.ex index 6f32ec19..a6fe48c3 100644 --- a/lib/philomena/user_statistics.ex +++ b/lib/philomena/user_statistics.ex @@ -24,9 +24,16 @@ defmodule Philomena.UserStatistics do def inc_stat(user, action, amount \\ 1) def inc_stat(nil, _action, _amount), do: {:ok, nil} + def inc_stat(%{id: user_id}, action, amount) - when action in [:uploads, :images_favourited, :comments_posted, :votes_cast, :metadata_updates, :forum_posts] - do + when action in [ + :uploads, + :images_favourited, + :comments_posted, + :votes_cast, + :metadata_updates, + :forum_posts + ] do now = DateTime.utc_now() |> DateTime.to_unix(:second) @@ -37,6 +44,7 @@ defmodule Philomena.UserStatistics do run = fn -> Repo.update_all(user, inc: [{action_count, amount}]) + Repo.insert( Map.put(%UserStatistic{day: now, user_id: user_id}, action, amount), on_conflict: [inc: [{action, amount}]], diff --git a/lib/philomena/user_statistics/user_statistic.ex b/lib/philomena/user_statistics/user_statistic.ex index 27af1b68..704c9a4e 100644 --- a/lib/philomena/user_statistics/user_statistic.ex +++ b/lib/philomena/user_statistics/user_statistic.ex @@ -20,8 +20,12 @@ defmodule Philomena.UserStatistics.UserStatistic do def changeset(user_statistic, attrs) do user_statistic |> cast(attrs, [ - :uploads, :votes_cast, :comments_posted, :metadata_updates, - :images_favourited, :forum_posts + :uploads, + :votes_cast, + :comments_posted, + :metadata_updates, + :images_favourited, + :forum_posts ]) end end diff --git a/lib/philomena/user_wipe.ex b/lib/philomena/user_wipe.ex index c227e6bd..a00b519b 100644 --- a/lib/philomena/user_wipe.ex +++ b/lib/philomena/user_wipe.ex @@ -33,7 +33,13 @@ defmodule Philomena.UserWipe do User |> where(id: ^user.id) - |> Repo.update_all(set: [email: "deactivated#{random_hex}@example.com", current_sign_in_ip: @wipe_ip, last_sign_in_ip: @wipe_ip]) + |> Repo.update_all( + set: [ + email: "deactivated#{random_hex}@example.com", + current_sign_in_ip: @wipe_ip, + last_sign_in_ip: @wipe_ip + ] + ) end defp in_batches(queryable, mapper) do diff --git a/lib/philomena/users.ex b/lib/philomena/users.ex index 48add23c..4c3a4622 100644 --- a/lib/philomena/users.ex +++ b/lib/philomena/users.ex @@ -86,7 +86,7 @@ defmodule Philomena.Users do end defp clean_roles(nil), do: [] - defp clean_roles(roles), do: Enum.filter(roles, &"" != &1) + defp clean_roles(roles), do: Enum.filter(roles, &("" != &1)) def update_spoiler_type(%User{} = user, attrs) do user @@ -131,7 +131,7 @@ defmodule Philomena.Users do def update_avatar(%User{} = user, attrs) do changeset = Uploader.analyze_upload(user, attrs) - Multi.new + Multi.new() |> Multi.update(:user, changeset) |> Multi.run(:update_file, fn _repo, %{user: user} -> Uploader.persist_upload(user) @@ -145,7 +145,7 @@ defmodule Philomena.Users do def remove_avatar(%User{} = user) do changeset = User.remove_avatar_changeset(user) - Multi.new + Multi.new() |> Multi.update(:user, changeset) |> Multi.run(:remove_file, fn _repo, %{user: user} -> Uploader.unpersist_old_upload(user) @@ -203,12 +203,13 @@ defmodule Philomena.Users do User |> join(:left, [u], _ in assoc(u, :roles)) |> join(:left, [u, _], _ in assoc(u, :current_filter)) - |> preload([_, r, cf], [current_filter: cf, roles: r]) + |> preload([_, r, cf], current_filter: cf, roles: r) |> Repo.get_by(clauses) |> setup_roles() end defp setup_roles(nil), do: nil + defp setup_roles(user) do role_map = Map.new(user.roles, &{&1.resource_type || &1.name, &1.name}) diff --git a/lib/philomena/users/ability.ex b/lib/philomena/users/ability.ex index 4a50bfba..07a56d26 100644 --- a/lib/philomena/users/ability.ex +++ b/lib/philomena/users/ability.ex @@ -52,7 +52,9 @@ defimpl Canada.Can, for: [Atom, Philomena.Users.User] do # View forums def can?(%User{role: "moderator"}, :show, %Forum{access_level: level}) - when level in ["normal", "assistant", "staff"], do: true + when level in ["normal", "assistant", "staff"], + do: true + def can?(%User{role: "moderator"}, :show, %Topic{hidden_from_users: true}), do: true # View conversations @@ -116,8 +118,11 @@ defimpl Canada.Can, for: [Atom, Philomena.Users.User] do # And some privileged moderators can... # Manage site notices - def can?(%User{role: "moderator", role_map: %{"SiteNotice" => "admin"}}, _action, SiteNotice), do: true - def can?(%User{role: "moderator", role_map: %{"SiteNotice" => "admin"}}, _action, %SiteNotice{}), do: true + def can?(%User{role: "moderator", role_map: %{"SiteNotice" => "admin"}}, _action, SiteNotice), + do: true + + def can?(%User{role: "moderator", role_map: %{"SiteNotice" => "admin"}}, _action, %SiteNotice{}), + do: true # Manage badges def can?(%User{role: "moderator", role_map: %{"Badge" => "admin"}}, _action, Badge), do: true @@ -132,58 +137,127 @@ defimpl Canada.Can, for: [Atom, Philomena.Users.User] do # Manage users def can?(%User{role: "moderator", role_map: %{"User" => "moderator"}}, _action, User), do: true - def can?(%User{role: "moderator", role_map: %{"User" => "moderator"}}, _action, %User{}), do: true + + def can?(%User{role: "moderator", role_map: %{"User" => "moderator"}}, _action, %User{}), + do: true # Manage advertisements def can?(%User{role: "moderator", role_map: %{"Advert" => "admin"}}, _action, Advert), do: true - def can?(%User{role: "moderator", role_map: %{"Advert" => "admin"}}, _action, %Advert{}), do: true + + def can?(%User{role: "moderator", role_map: %{"Advert" => "admin"}}, _action, %Advert{}), + do: true # Manage static pages - def can?(%User{role: "moderator", role_map: %{"StaticPage" => "admin"}}, _action, StaticPage), do: true - def can?(%User{role: "moderator", role_map: %{"StaticPage" => "admin"}}, _action, %StaticPage{}), do: true + def can?(%User{role: "moderator", role_map: %{"StaticPage" => "admin"}}, _action, StaticPage), + do: true + + def can?(%User{role: "moderator", role_map: %{"StaticPage" => "admin"}}, _action, %StaticPage{}), + do: true # # Assistants can... # - # Image assistant actions - def can?(%User{role: "assistant", role_map: %{"Image" => "moderator"}}, :show, %Image{}), do: true - def can?(%User{role: "assistant", role_map: %{"Image" => "moderator"}}, :hide, %Image{}), do: true - def can?(%User{role: "assistant", role_map: %{"Image" => "moderator"}}, :edit, %Image{}), do: true - def can?(%User{role: "assistant", role_map: %{"Image" => "moderator"}}, :edit_description, %Image{}), do: true + def can?(%User{role: "assistant", role_map: %{"Image" => "moderator"}}, :show, %Image{}), + do: true + + def can?(%User{role: "assistant", role_map: %{"Image" => "moderator"}}, :hide, %Image{}), + do: true + + def can?(%User{role: "assistant", role_map: %{"Image" => "moderator"}}, :edit, %Image{}), + do: true + + def can?( + %User{role: "assistant", role_map: %{"Image" => "moderator"}}, + :edit_description, + %Image{} + ), + do: true # Dupe assistant actions - def can?(%User{role: "assistant", role_map: %{"DuplicateReport" => "moderator"}}, :index, DuplicateReport), do: true - def can?(%User{role: "assistant", role_map: %{"DuplicateReport" => "moderator"}}, :edit, %DuplicateReport{}), do: true - def can?(%User{role: "assistant", role_map: %{"DuplicateReport" => "moderator"}}, :show, %Image{}), do: true - def can?(%User{role: "assistant", role_map: %{"DuplicateReport" => "moderator"}}, :edit, %Image{}), do: true - def can?(%User{role: "assistant", role_map: %{"DuplicateReport" => "moderator"}}, :hide, %Comment{}), do: true + def can?( + %User{role: "assistant", role_map: %{"DuplicateReport" => "moderator"}}, + :index, + DuplicateReport + ), + do: true + + def can?( + %User{role: "assistant", role_map: %{"DuplicateReport" => "moderator"}}, + :edit, + %DuplicateReport{} + ), + do: true + + def can?( + %User{role: "assistant", role_map: %{"DuplicateReport" => "moderator"}}, + :show, + %Image{} + ), + do: true + + def can?( + %User{role: "assistant", role_map: %{"DuplicateReport" => "moderator"}}, + :edit, + %Image{} + ), + do: true + + def can?( + %User{role: "assistant", role_map: %{"DuplicateReport" => "moderator"}}, + :hide, + %Comment{} + ), + do: true # Comment assistant actions - def can?(%User{role: "assistant", role_map: %{"Comment" => "moderator"}}, :show, %Comment{}), do: true - def can?(%User{role: "assistant", role_map: %{"Comment" => "moderator"}}, :edit, %Comment{}), do: true - def can?(%User{role: "assistant", role_map: %{"Comment" => "moderator"}}, :hide, %Comment{}), do: true + def can?(%User{role: "assistant", role_map: %{"Comment" => "moderator"}}, :show, %Comment{}), + do: true + + def can?(%User{role: "assistant", role_map: %{"Comment" => "moderator"}}, :edit, %Comment{}), + do: true + + def can?(%User{role: "assistant", role_map: %{"Comment" => "moderator"}}, :hide, %Comment{}), + do: true # Topic assistant actions - def can?(%User{role: "assistant", role_map: %{"Topic" => "moderator"}}, :show, %Topic{}), do: true - def can?(%User{role: "assistant", role_map: %{"Topic" => "moderator"}}, :edit, %Topic{}), do: true - def can?(%User{role: "assistant", role_map: %{"Topic" => "moderator"}}, :hide, %Topic{}), do: true - def can?(%User{role: "assistant", role_map: %{"Topic" => "moderator"}}, :show, %Post{}), do: true - def can?(%User{role: "assistant", role_map: %{"Topic" => "moderator"}}, :edit, %Post{}), do: true - def can?(%User{role: "assistant", role_map: %{"Topic" => "moderator"}}, :hide, %Post{}), do: true + def can?(%User{role: "assistant", role_map: %{"Topic" => "moderator"}}, :show, %Topic{}), + do: true + + def can?(%User{role: "assistant", role_map: %{"Topic" => "moderator"}}, :edit, %Topic{}), + do: true + + def can?(%User{role: "assistant", role_map: %{"Topic" => "moderator"}}, :hide, %Topic{}), + do: true + + def can?(%User{role: "assistant", role_map: %{"Topic" => "moderator"}}, :show, %Post{}), + do: true + + def can?(%User{role: "assistant", role_map: %{"Topic" => "moderator"}}, :edit, %Post{}), + do: true + + def can?(%User{role: "assistant", role_map: %{"Topic" => "moderator"}}, :hide, %Post{}), + do: true # Tag assistant actions def can?(%User{role: "assistant", role_map: %{"Tag" => "moderator"}}, :edit, %Tag{}), do: true - def can?(%User{role: "assistant", role_map: %{"Tag" => "moderator"}}, :batch_update, Tag), do: true + + def can?(%User{role: "assistant", role_map: %{"Tag" => "moderator"}}, :batch_update, Tag), + do: true # User link assistant actions - def can?(%User{role: "assistant", role_map: %{"UserLink" => "moderator"}}, :show, %UserLink{}), do: true - def can?(%User{role: "assistant", role_map: %{"UserLink" => "moderator"}}, :edit, %UserLink{}), do: true + def can?(%User{role: "assistant", role_map: %{"UserLink" => "moderator"}}, :show, %UserLink{}), + do: true + + def can?(%User{role: "assistant", role_map: %{"UserLink" => "moderator"}}, :edit, %UserLink{}), + do: true # View forums def can?(%User{role: "assistant"}, :show, %Forum{access_level: level}) - when level in ["normal", "assistant"], do: true + when level in ["normal", "assistant"], + do: true + def can?(%User{role: "assistant"}, :show, %Topic{hidden_from_users: true}), do: true # @@ -205,17 +279,22 @@ defimpl Canada.Can, for: [Atom, Philomena.Users.User] do def can?(_user, :show, %Filter{system: true}), do: true def can?(_user, :show, %Filter{public: true}), do: true def can?(%User{}, action, Filter) when action in [:index, :new, :create], do: true - def can?(%User{id: id}, action, %Filter{user_id: id}) when action in [:show, :edit, :update], do: true + + def can?(%User{id: id}, action, %Filter{user_id: id}) when action in [:show, :edit, :update], + do: true # Edit filters they own - def can?(%User{id: id}, action, %Filter{user_id: id}) when action in [:edit, :update, :delete], do: true + def can?(%User{id: id}, action, %Filter{user_id: id}) when action in [:edit, :update, :delete], + do: true # View user links they've created def can?(%User{id: id}, :create_links, %User{id: id}), do: true def can?(%User{id: id}, :show, %UserLink{user_id: id}), do: true # Edit their commissions - def can?(%User{id: id}, action, %Commission{user_id: id}) when action in [:edit, :update, :delete], do: true + def can?(%User{id: id}, action, %Commission{user_id: id}) + when action in [:edit, :update, :delete], + do: true # View non-deleted images def can?(_user, action, Image) @@ -229,10 +308,12 @@ defimpl Canada.Can, for: [Atom, Philomena.Users.User] do def can?(_user, :show, %Tag{}), do: true # Comment on images where that is allowed - def can?(_user, :create_comment, %Image{hidden_from_users: false, commenting_allowed: true}), do: true + def can?(_user, :create_comment, %Image{hidden_from_users: false, commenting_allowed: true}), + do: true # Edit comments on images - def can?(%User{id: id}, action, %Comment{hidden_from_users: false, user_id: id} = comment) when action in [:edit, :update] do + def can?(%User{id: id}, action, %Comment{hidden_from_users: false, user_id: id} = comment) + when action in [:edit, :update] do # comment must have been made no later than 15 minutes ago time_ago = NaiveDateTime.utc_now() |> NaiveDateTime.add(-15 * 60) @@ -240,8 +321,15 @@ defimpl Canada.Can, for: [Atom, Philomena.Users.User] do end # Edit metadata on images where that is allowed - def can?(_user, :edit_metadata, %Image{hidden_from_users: false, tag_editing_allowed: true}), do: true - def can?(%User{id: id}, :edit_description, %Image{user_id: id, hidden_from_users: false, description_editing_allowed: true}), do: true + def can?(_user, :edit_metadata, %Image{hidden_from_users: false, tag_editing_allowed: true}), + do: true + + def can?(%User{id: id}, :edit_description, %Image{ + user_id: id, + hidden_from_users: false, + description_editing_allowed: true + }), + do: true # Vote on images they can see def can?(user, :vote, image), do: can?(user, :show, image) @@ -254,10 +342,13 @@ defimpl Canada.Can, for: [Atom, Philomena.Users.User] do def can?(_user, :show, %Forum{access_level: "normal"}), do: true def can?(_user, :show, %Topic{hidden_from_users: false}), do: true def can?(_user, :show, %Post{hidden_from_users: false}), do: true - + # Create and edit posts def can?(_user, :create_post, %Topic{locked_at: nil, hidden_from_users: false}), do: true - def can?(%User{id: id}, action, %Post{hidden_from_users: false, user_id: id}) when action in [:edit, :update], do: true + + def can?(%User{id: id}, action, %Post{hidden_from_users: false, user_id: id}) + when action in [:edit, :update], + do: true # View profile pages def can?(_user, :show, %User{}), do: true @@ -274,7 +365,10 @@ defimpl Canada.Can, for: [Atom, Philomena.Users.User] do # Create and edit galleries def can?(_user, :show, %Gallery{}), do: true def can?(%User{}, action, Gallery) when action in [:new, :create], do: true - def can?(%User{id: id}, action, %Gallery{creator_id: id}) when action in [:edit, :update, :delete], do: true + + def can?(%User{id: id}, action, %Gallery{creator_id: id}) + when action in [:edit, :update, :delete], + do: true # Show static pages def can?(_user, :show, %StaticPage{}), do: true diff --git a/lib/philomena/users/uploader.ex b/lib/philomena/users/uploader.ex index 14cb03b4..9d8cb1cb 100644 --- a/lib/philomena/users/uploader.ex +++ b/lib/philomena/users/uploader.ex @@ -21,4 +21,4 @@ defmodule Philomena.Users.Uploader do defp avatar_file_root do Application.get_env(:philomena, :avatar_file_root) end -end \ No newline at end of file +end diff --git a/lib/philomena/users/user.ex b/lib/philomena/users/user.ex index eb714c65..dd928417 100644 --- a/lib/philomena/users/user.ex +++ b/lib/philomena/users/user.ex @@ -183,7 +183,10 @@ defmodule Philomena.Users.User do changeset |> put_change(:current_filter_id, filter.id) - |> put_change(:recent_filter_ids, Enum.take(Enum.uniq([filter.id | user.recent_filter_ids]), 10)) + |> put_change( + :recent_filter_ids, + Enum.take(Enum.uniq([filter.id | user.recent_filter_ids]), 10) + ) end def spoiler_type_changeset(user, attrs) do @@ -196,16 +199,32 @@ defmodule Philomena.Users.User do def settings_changeset(user, attrs) do user |> cast(attrs, [ - :watched_tag_list, :images_per_page, :fancy_tag_field_on_upload, - :fancy_tag_field_on_edit, :anonymous_by_default, :scale_large_images, - :comments_per_page, :theme, :watched_images_query_str, - :no_spoilered_in_watched, :watched_images_exclude_str, - :use_centered_layout, :hide_vote_counts, :comments_newest_first + :watched_tag_list, + :images_per_page, + :fancy_tag_field_on_upload, + :fancy_tag_field_on_edit, + :anonymous_by_default, + :scale_large_images, + :comments_per_page, + :theme, + :watched_images_query_str, + :no_spoilered_in_watched, + :watched_images_exclude_str, + :use_centered_layout, + :hide_vote_counts, + :comments_newest_first ]) |> validate_required([ - :images_per_page, :fancy_tag_field_on_upload, :fancy_tag_field_on_edit, - :anonymous_by_default, :scale_large_images, :comments_per_page, :theme, - :no_spoilered_in_watched, :use_centered_layout, :hide_vote_counts + :images_per_page, + :fancy_tag_field_on_upload, + :fancy_tag_field_on_edit, + :anonymous_by_default, + :scale_large_images, + :comments_per_page, + :theme, + :no_spoilered_in_watched, + :use_centered_layout, + :hide_vote_counts ]) |> TagList.propagate_tag_list(:watched_tag_list, :watched_tag_ids) |> validate_inclusion(:theme, ~W(default dark red)) @@ -220,7 +239,10 @@ defmodule Philomena.Users.User do |> cast(attrs, [:description, :personal_title]) |> validate_length(:description, max: 10_000, count: :bytes) |> validate_length(:personal_title, max: 24, count: :bytes) - |> validate_format(:personal_title, ~r/\A((?!site|admin|moderator|assistant|developer|\p{C}).)*\z/iu) + |> validate_format( + :personal_title, + ~r/\A((?!site|admin|moderator|assistant|developer|\p{C}).)*\z/iu + ) end def scratchpad_changeset(user, attrs) do @@ -231,11 +253,19 @@ defmodule Philomena.Users.User do def avatar_changeset(user, attrs) do user |> cast(attrs, [ - :avatar, :avatar_width, :avatar_height, :avatar_size, :uploaded_avatar, + :avatar, + :avatar_width, + :avatar_height, + :avatar_size, + :uploaded_avatar, :removed_avatar ]) |> validate_required([ - :avatar, :avatar_width, :avatar_height, :avatar_size, :uploaded_avatar + :avatar, + :avatar_width, + :avatar_height, + :avatar_size, + :uploaded_avatar ]) |> validate_number(:avatar_size, greater_than: 0, less_than_or_equal_to: 300_000) |> validate_number(:avatar_width, greater_than: 0, less_than_or_equal_to: 1000) @@ -321,7 +351,7 @@ defmodule Philomena.Users.User do end def random_backup_codes do - (1..10) + 1..10 |> Enum.map(fn _i -> :crypto.strong_rand_bytes(6) |> Base.encode16(case: :lower) end) @@ -329,14 +359,16 @@ defmodule Philomena.Users.User do def totp_qrcode(user) do secret = totp_secret(user) + provisioning_uri = %URI{ scheme: "otpauth", host: "totp", path: "/Derpibooru:" <> user.email, - query: URI.encode_query(%{ - secret: secret, - issuer: "Derpibooru" - }) + query: + URI.encode_query(%{ + secret: secret, + issuer: "Derpibooru" + }) } png = @@ -354,7 +386,6 @@ defmodule Philomena.Users.User do ) end - defp enable_totp_changeset(user, backup_codes) do hashed_codes = backup_codes @@ -409,7 +440,8 @@ defmodule Philomena.Users.User do defp totp_valid?(user, token) do case Integer.parse(token) do {int_token, _rest} -> - int_token != user.consumed_timestep and :pot.valid_totp(token, totp_secret(user), window: 1) + int_token != user.consumed_timestep and + :pot.valid_totp(token, totp_secret(user), window: 1) _error -> false diff --git a/lib/philomena/versions.ex b/lib/philomena/versions.ex index ca1fa6a9..f40bcd2f 100644 --- a/lib/philomena/versions.ex +++ b/lib/philomena/versions.ex @@ -29,15 +29,14 @@ defmodule Philomena.Versions do body = yaml["body"] || "" edit_reason = yaml["edit_reason"] - v = - %{ - version | - parent: parent, + v = %{ + version + | parent: parent, user: users[version.whodunnit], body: body, edit_reason: edit_reason, difference: difference(body, previous_body) - } + } {v, body} end) @@ -61,7 +60,12 @@ defmodule Philomena.Versions do """ def create_version(item_type, item_id, whodunnit, attrs \\ %{}) do - %Version{item_type: item_type, item_id: item_id, event: "update", whodunnit: whodunnit(whodunnit)} + %Version{ + item_type: item_type, + item_id: item_id, + event: "update", + whodunnit: whodunnit(whodunnit) + } |> Version.changeset(attrs, item_id) |> Repo.insert() end diff --git a/lib/philomena/versions/attribution.ex b/lib/philomena/versions/attribution.ex index b286fa77..55a05be7 100644 --- a/lib/philomena/versions/attribution.ex +++ b/lib/philomena/versions/attribution.ex @@ -13,4 +13,4 @@ defimpl Philomena.Attribution, for: Philomena.Versions.Version do defp same_user?(%{id: id}, %{user_id: id}), do: true defp same_user?(_user, _parent), do: false -end \ No newline at end of file +end diff --git a/lib/philomena/versions/version.ex b/lib/philomena/versions/version.ex index 42495220..d8e769d2 100644 --- a/lib/philomena/versions/version.ex +++ b/lib/philomena/versions/version.ex @@ -31,11 +31,12 @@ defmodule Philomena.Versions.Version do body = get_field(changeset, :body) edit_reason = get_field(changeset, :edit_reason) - object = Jason.encode!(%{ - id: item_id, - body: body, - edit_reason: edit_reason - }) + object = + Jason.encode!(%{ + id: item_id, + body: body, + edit_reason: edit_reason + }) change(changeset, object: object) end diff --git a/lib/philomena_web/comment_json.ex b/lib/philomena_web/comment_json.ex index e5508aeb..443070c7 100644 --- a/lib/philomena_web/comment_json.ex +++ b/lib/philomena_web/comment_json.ex @@ -20,7 +20,11 @@ defmodule PhilomenaWeb.CommentJson do id: comment.id, image_id: comment.image_id, user_id: if(not comment.anonymous, do: comment.user_id), - author: if(comment.anonymous or is_nil(comment.user), do: UserAttributionView.anonymous_name(comment), else: comment.user.name), + author: + if(comment.anonymous or is_nil(comment.user), + do: UserAttributionView.anonymous_name(comment), + else: comment.user.name + ), body: nil } end @@ -30,7 +34,11 @@ defmodule PhilomenaWeb.CommentJson do id: comment.id, image_id: comment.image_id, user_id: if(not comment.anonymous, do: comment.user_id), - author: if(comment.anonymous or is_nil(comment.user), do: UserAttributionView.anonymous_name(comment), else: comment.user.name), + author: + if(comment.anonymous or is_nil(comment.user), + do: UserAttributionView.anonymous_name(comment), + else: comment.user.name + ), body: comment.body } end diff --git a/lib/philomena_web/controllers/activity_controller.ex b/lib/philomena_web/controllers/activity_controller.ex index c58d41c7..be591013 100644 --- a/lib/philomena_web/controllers/activity_controller.ex +++ b/lib/philomena_web/controllers/activity_controller.ex @@ -3,7 +3,16 @@ defmodule PhilomenaWeb.ActivityController do alias PhilomenaWeb.ImageLoader alias Philomena.Elasticsearch - alias Philomena.{Images.Image, ImageFeatures.ImageFeature, Comments.Comment, Channels.Channel, Topics.Topic, Forums.Forum} + + alias Philomena.{ + Images.Image, + ImageFeatures.ImageFeature, + Comments.Comment, + Channels.Channel, + Topics.Topic, + Forums.Forum + } + alias Philomena.Interactions alias Philomena.Repo import Ecto.Query @@ -47,16 +56,17 @@ defmodule PhilomenaWeb.ActivityController do Comment |> preload([:user, image: [:tags]]) ) - watched = if !!user do - {:ok, {watched_images, _tags}} = - ImageLoader.search_string( - conn, - "my:watched", - pagination: %{conn.assigns.image_pagination | page_number: 1} - ) + watched = + if !!user do + {:ok, {watched_images, _tags}} = + ImageLoader.search_string( + conn, + "my:watched", + pagination: %{conn.assigns.image_pagination | page_number: 1} + ) - if Enum.any?(watched_images), do: watched_images - end + if Enum.any?(watched_images), do: watched_images + end featured_image = Image @@ -68,7 +78,7 @@ defmodule PhilomenaWeb.ActivityController do streams = Channel - |> where([c], c.nsfw == false) + |> where([c], c.nsfw == false) |> where([c], not is_nil(c.last_fetched_at)) |> order_by(desc: :is_live, asc: :title) |> limit(6) diff --git a/lib/philomena_web/controllers/admin/advert_controller.ex b/lib/philomena_web/controllers/admin/advert_controller.ex index 6890dddc..bb119f42 100644 --- a/lib/philomena_web/controllers/admin/advert_controller.ex +++ b/lib/philomena_web/controllers/admin/advert_controller.ex @@ -15,7 +15,11 @@ defmodule PhilomenaWeb.Admin.AdvertController do |> order_by(desc: :finish_date) |> Repo.paginate(conn.assigns.scrivener) - render(conn, "index.html", title: "Admin - Adverts", layout_class: "layout--wide", adverts: adverts) + render(conn, "index.html", + title: "Admin - Adverts", + layout_class: "layout--wide", + adverts: adverts + ) end def new(conn, _params) do @@ -62,7 +66,7 @@ defmodule PhilomenaWeb.Admin.AdvertController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, Advert) do - true -> conn + true -> conn false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/badge/user_controller.ex b/lib/philomena_web/controllers/admin/badge/user_controller.ex index 11cdd9ad..e4f9a841 100644 --- a/lib/philomena_web/controllers/admin/badge/user_controller.ex +++ b/lib/philomena_web/controllers/admin/badge/user_controller.ex @@ -24,7 +24,7 @@ defmodule PhilomenaWeb.Admin.Badge.UserController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, Badge) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/badge_controller.ex b/lib/philomena_web/controllers/admin/badge_controller.ex index 88270f64..95aa4438 100644 --- a/lib/philomena_web/controllers/admin/badge_controller.ex +++ b/lib/philomena_web/controllers/admin/badge_controller.ex @@ -54,7 +54,7 @@ defmodule PhilomenaWeb.Admin.BadgeController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, Badge) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/batch/tag_controller.ex b/lib/philomena_web/controllers/admin/batch/tag_controller.ex index 16d02aac..4e8563a9 100644 --- a/lib/philomena_web/controllers/admin/batch/tag_controller.ex +++ b/lib/philomena_web/controllers/admin/batch/tag_controller.ex @@ -14,6 +14,7 @@ defmodule PhilomenaWeb.Admin.Batch.TagController do tags = Tag.parse_tag_list(tags) added_tag_names = Enum.reject(tags, &String.starts_with?(&1, "-")) + removed_tag_names = tags |> Enum.filter(&String.starts_with?(&1, "-")) @@ -24,7 +25,7 @@ defmodule PhilomenaWeb.Admin.Batch.TagController do |> where([t], t.name in ^added_tag_names) |> preload([:implied_tags, aliased_tag: :implied_tags]) |> Repo.all() - |> Enum.map(& &1.aliased_tag || &1) + |> Enum.map(&(&1.aliased_tag || &1)) |> Enum.flat_map(&[&1 | &1.implied_tags]) removed_tags = @@ -33,6 +34,7 @@ defmodule PhilomenaWeb.Admin.Batch.TagController do |> Repo.all() attributes = conn.assigns.attributes + attributes = %{ ip: attributes[:ip], fingerprint: attributes[:fingerprint], @@ -57,7 +59,7 @@ defmodule PhilomenaWeb.Admin.Batch.TagController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :batch_update, Tag) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/dnp_entry/transition_controller.ex b/lib/philomena_web/controllers/admin/dnp_entry/transition_controller.ex index 16e65621..369e0469 100644 --- a/lib/philomena_web/controllers/admin/dnp_entry/transition_controller.ex +++ b/lib/philomena_web/controllers/admin/dnp_entry/transition_controller.ex @@ -8,7 +8,11 @@ defmodule PhilomenaWeb.Admin.DnpEntry.TransitionController do plug :load_resource, model: DnpEntry, only: [:create], id_name: "dnp_entry_id", persisted: true def create(conn, %{"state" => new_state}) do - case DnpEntries.transition_dnp_entry(conn.assigns.dnp_entry, conn.assigns.current_user, new_state) do + case DnpEntries.transition_dnp_entry( + conn.assigns.dnp_entry, + conn.assigns.current_user, + new_state + ) do {:ok, dnp_entry} -> conn |> put_flash(:info, "Successfully updated DNP entry.") @@ -23,7 +27,7 @@ defmodule PhilomenaWeb.Admin.DnpEntry.TransitionController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, DnpEntry) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/dnp_entry_controller.ex b/lib/philomena_web/controllers/admin/dnp_entry_controller.ex index ad0976e0..21a796c7 100644 --- a/lib/philomena_web/controllers/admin/dnp_entry_controller.ex +++ b/lib/philomena_web/controllers/admin/dnp_entry_controller.ex @@ -21,7 +21,11 @@ defmodule PhilomenaWeb.Admin.DnpEntryController do DnpEntry |> join(:inner, [d], _ in assoc(d, :tag)) |> join(:inner, [d, _t], _ in assoc(d, :requesting_user)) - |> where([d, t, u], ilike(u.name, ^q) or ilike(t.name, ^q) or ilike(d.reason, ^q) or ilike(d.conditions, ^q) or ilike(d.instructions, ^q)) + |> where( + [d, t, u], + ilike(u.name, ^q) or ilike(t.name, ^q) or ilike(d.reason, ^q) or ilike(d.conditions, ^q) or + ilike(d.instructions, ^q) + ) |> load_entries(conn) end @@ -43,15 +47,18 @@ defmodule PhilomenaWeb.Admin.DnpEntryController do |> Enum.map(&%{body: &1.conditions}) |> Renderer.render_collection(conn) - dnp_entries = - %{dnp_entries | entries: Enum.zip(bodies, dnp_entries.entries)} + dnp_entries = %{dnp_entries | entries: Enum.zip(bodies, dnp_entries.entries)} - render(conn, "index.html", layout_class: "layout--wide", title: "Admin - DNP Entries", dnp_entries: dnp_entries) + render(conn, "index.html", + layout_class: "layout--wide", + title: "Admin - DNP Entries", + dnp_entries: dnp_entries + ) end defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, DnpEntry) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/donation/user_controller.ex b/lib/philomena_web/controllers/admin/donation/user_controller.ex index 1b81df27..f74da9bd 100644 --- a/lib/philomena_web/controllers/admin/donation/user_controller.ex +++ b/lib/philomena_web/controllers/admin/donation/user_controller.ex @@ -11,12 +11,17 @@ defmodule PhilomenaWeb.Admin.Donation.UserController do def show(conn, _params) do user = conn.assigns.user changeset = Donations.change_donation(%Donation{}) - render(conn, "index.html", title: "Donations for User `#{user.name}'", donations: user.donations, changeset: changeset) + + render(conn, "index.html", + title: "Donations for User `#{user.name}'", + donations: user.donations, + changeset: changeset + ) end defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, Donation) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/donation_controller.ex b/lib/philomena_web/controllers/admin/donation_controller.ex index e73d0def..91de59cf 100644 --- a/lib/philomena_web/controllers/admin/donation_controller.ex +++ b/lib/philomena_web/controllers/admin/donation_controller.ex @@ -34,7 +34,7 @@ defmodule PhilomenaWeb.Admin.DonationController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, Donation) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/fingerprint_ban_controller.ex b/lib/philomena_web/controllers/admin/fingerprint_ban_controller.ex index 0a7d5cd8..f251af46 100644 --- a/lib/philomena_web/controllers/admin/fingerprint_ban_controller.ex +++ b/lib/philomena_web/controllers/admin/fingerprint_ban_controller.ex @@ -11,11 +11,12 @@ defmodule PhilomenaWeb.Admin.FingerprintBanController do def index(conn, %{"q" => q}) when is_binary(q) do FingerprintBan - |> where([fb], - ilike(fb.fingerprint, ^"%#{q}%") - or fb.generated_ban_id == ^q - or fragment("to_tsvector(?) @@ plainto_tsquery(?)", fb.reason, ^q) - or fragment("to_tsvector(?) @@ plainto_tsquery(?)", fb.note, ^q) + |> where( + [fb], + ilike(fb.fingerprint, ^"%#{q}%") or + fb.generated_ban_id == ^q or + fragment("to_tsvector(?) @@ plainto_tsquery(?)", fb.reason, ^q) or + fragment("to_tsvector(?) @@ plainto_tsquery(?)", fb.note, ^q) ) |> load_bans(conn) end @@ -84,12 +85,16 @@ defmodule PhilomenaWeb.Admin.FingerprintBanController do |> preload(:banning_user) |> Repo.paginate(conn.assigns.scrivener) - render(conn, "index.html", layout_class: "layout--wide", title: "Admin - Fingerprint Bans", fingerprint_bans: fingerprint_bans) + render(conn, "index.html", + layout_class: "layout--wide", + title: "Admin - Fingerprint Bans", + fingerprint_bans: fingerprint_bans + ) end defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, FingerprintBan) do - true -> conn + true -> conn false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/forum_controller.ex b/lib/philomena_web/controllers/admin/forum_controller.ex index 54d58948..7d9e0190 100644 --- a/lib/philomena_web/controllers/admin/forum_controller.ex +++ b/lib/philomena_web/controllers/admin/forum_controller.ex @@ -47,7 +47,7 @@ defmodule PhilomenaWeb.Admin.ForumController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :edit, Forum) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/mod_note_controller.ex b/lib/philomena_web/controllers/admin/mod_note_controller.ex index 630cd445..6cd9e62d 100644 --- a/lib/philomena_web/controllers/admin/mod_note_controller.ex +++ b/lib/philomena_web/controllers/admin/mod_note_controller.ex @@ -80,7 +80,7 @@ defmodule PhilomenaWeb.Admin.ModNoteController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, ModNote) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/report/close_controller.ex b/lib/philomena_web/controllers/admin/report/close_controller.ex index 1558431c..2ce98b1d 100644 --- a/lib/philomena_web/controllers/admin/report/close_controller.ex +++ b/lib/philomena_web/controllers/admin/report/close_controller.ex @@ -15,4 +15,4 @@ defmodule PhilomenaWeb.Admin.Report.CloseController do |> put_flash(:info, "Successfully closed report") |> redirect(to: Routes.admin_report_path(conn, :index)) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/admin/report_controller.ex b/lib/philomena_web/controllers/admin/report_controller.ex index 2f569a4d..ede6fac8 100644 --- a/lib/philomena_web/controllers/admin/report_controller.ex +++ b/lib/philomena_web/controllers/admin/report_controller.ex @@ -11,7 +11,12 @@ defmodule PhilomenaWeb.Admin.ReportController do import Ecto.Query plug :verify_authorized - plug :load_and_authorize_resource, model: Report, only: [:show], preload: [:admin, user: [:linked_tags, awards: :badge]] + + plug :load_and_authorize_resource, + model: Report, + only: [:show], + preload: [:admin, user: [:linked_tags, awards: :badge]] + plug :set_mod_notes when action in [:show] def index(conn, %{"rq" => query_string}) do @@ -19,26 +24,30 @@ defmodule PhilomenaWeb.Admin.ReportController do reports = load_reports(conn, query) - render(conn, "index.html", title: "Admin - Reports", layout_class: "layout--wide", reports: reports, my_reports: []) + render(conn, "index.html", + title: "Admin - Reports", + layout_class: "layout--wide", + reports: reports, + my_reports: [] + ) end def index(conn, _params) do user = conn.assigns.current_user - query = - %{ - bool: %{ - should: [ - %{term: %{open: false}}, - %{ - bool: %{ - must: %{term: %{open: true}}, - must_not: %{term: %{admin_id: user.id}} - } + query = %{ + bool: %{ + should: [ + %{term: %{open: false}}, + %{ + bool: %{ + must: %{term: %{open: true}}, + must_not: %{term: %{admin_id: user.id}} } - ] - } + } + ] } + } reports = load_reports(conn, query) @@ -50,11 +59,20 @@ defmodule PhilomenaWeb.Admin.ReportController do |> Repo.all() |> Polymorphic.load_polymorphic(reportable: [reportable_id: :reportable_type]) - render(conn, "index.html", title: "Admin - Reports", layout_class: "layout--wide", reports: reports, my_reports: my_reports) + render(conn, "index.html", + title: "Admin - Reports", + layout_class: "layout--wide", + reports: reports, + my_reports: my_reports + ) end def show(conn, _params) do - [report] = Polymorphic.load_polymorphic([conn.assigns.report], reportable: [reportable_id: :reportable_type]) + [report] = + Polymorphic.load_polymorphic([conn.assigns.report], + reportable: [reportable_id: :reportable_type] + ) + body = Renderer.render_one(%{body: report.reason}, conn) render(conn, "show.html", title: "Showing Report", report: report, body: body) @@ -72,8 +90,7 @@ defmodule PhilomenaWeb.Admin.ReportController do Report |> preload([:admin, user: :linked_tags]) ) - entries = - Polymorphic.load_polymorphic(reports, reportable: [reportable_id: :reportable_type]) + entries = Polymorphic.load_polymorphic(reports, reportable: [reportable_id: :reportable_type]) %{reports | entries: entries} end @@ -88,7 +105,7 @@ defmodule PhilomenaWeb.Admin.ReportController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, Report) do - true -> conn + true -> conn false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/site_notice_controller.ex b/lib/philomena_web/controllers/admin/site_notice_controller.ex index a6eef65f..11462540 100644 --- a/lib/philomena_web/controllers/admin/site_notice_controller.ex +++ b/lib/philomena_web/controllers/admin/site_notice_controller.ex @@ -62,7 +62,7 @@ defmodule PhilomenaWeb.Admin.SiteNoticeController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, SiteNotice) do - true -> conn + true -> conn false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/subnet_ban_controller.ex b/lib/philomena_web/controllers/admin/subnet_ban_controller.ex index bf8706d4..cd92a5b7 100644 --- a/lib/philomena_web/controllers/admin/subnet_ban_controller.ex +++ b/lib/philomena_web/controllers/admin/subnet_ban_controller.ex @@ -11,10 +11,11 @@ defmodule PhilomenaWeb.Admin.SubnetBanController do def index(conn, %{"q" => q}) when is_binary(q) do SubnetBan - |> where([sb], - sb.generated_ban_id == ^q - or fragment("to_tsvector(?) @@ plainto_tsquery(?)", sb.reason, ^q) - or fragment("to_tsvector(?) @@ plainto_tsquery(?)", sb.note, ^q) + |> where( + [sb], + sb.generated_ban_id == ^q or + fragment("to_tsvector(?) @@ plainto_tsquery(?)", sb.reason, ^q) or + fragment("to_tsvector(?) @@ plainto_tsquery(?)", sb.note, ^q) ) |> load_bans(conn) end @@ -86,12 +87,16 @@ defmodule PhilomenaWeb.Admin.SubnetBanController do |> preload(:banning_user) |> Repo.paginate(conn.assigns.scrivener) - render(conn, "index.html", title: "Admin - Subnet Bans", layout_class: "layout--wide", subnet_bans: subnet_bans) + render(conn, "index.html", + title: "Admin - Subnet Bans", + layout_class: "layout--wide", + subnet_bans: subnet_bans + ) end defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, SubnetBan) do - true -> conn + true -> conn false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/user/activation_controller.ex b/lib/philomena_web/controllers/admin/user/activation_controller.ex index c641729b..e5f78aad 100644 --- a/lib/philomena_web/controllers/admin/user/activation_controller.ex +++ b/lib/philomena_web/controllers/admin/user/activation_controller.ex @@ -25,7 +25,7 @@ defmodule PhilomenaWeb.Admin.User.ActivationController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, User) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/user/api_key_controller.ex b/lib/philomena_web/controllers/admin/user/api_key_controller.ex index f38b1f77..e2987ff9 100644 --- a/lib/philomena_web/controllers/admin/user/api_key_controller.ex +++ b/lib/philomena_web/controllers/admin/user/api_key_controller.ex @@ -17,7 +17,7 @@ defmodule PhilomenaWeb.Admin.User.ApiKeyController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, User) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/user/avatar_controller.ex b/lib/philomena_web/controllers/admin/user/avatar_controller.ex index 421b97d2..c04fdbcd 100644 --- a/lib/philomena_web/controllers/admin/user/avatar_controller.ex +++ b/lib/philomena_web/controllers/admin/user/avatar_controller.ex @@ -17,7 +17,7 @@ defmodule PhilomenaWeb.Admin.User.AvatarController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, User) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/user/downvote_controller.ex b/lib/philomena_web/controllers/admin/user/downvote_controller.ex index 06804e4f..5a31782d 100644 --- a/lib/philomena_web/controllers/admin/user/downvote_controller.ex +++ b/lib/philomena_web/controllers/admin/user/downvote_controller.ex @@ -8,9 +8,9 @@ defmodule PhilomenaWeb.Admin.User.DownvoteController do plug :load_resource, model: User, id_name: "user_id", id_field: "slug", persisted: true def delete(conn, _params) do - spawn fn -> + spawn(fn -> UserDownvoteWipe.perform(conn.assigns.user) - end + end) conn |> put_flash(:info, "Downvote wipe started.") @@ -19,7 +19,7 @@ defmodule PhilomenaWeb.Admin.User.DownvoteController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, User) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/user/vote_controller.ex b/lib/philomena_web/controllers/admin/user/vote_controller.ex index b5c95085..8e888235 100644 --- a/lib/philomena_web/controllers/admin/user/vote_controller.ex +++ b/lib/philomena_web/controllers/admin/user/vote_controller.ex @@ -8,9 +8,9 @@ defmodule PhilomenaWeb.Admin.User.VoteController do plug :load_resource, model: User, id_name: "user_id", id_field: "slug", persisted: true def delete(conn, _params) do - spawn fn -> + spawn(fn -> UserDownvoteWipe.perform(conn.assigns.user, true) - end + end) conn |> put_flash(:info, "Vote and fave wipe started.") @@ -19,7 +19,7 @@ defmodule PhilomenaWeb.Admin.User.VoteController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, User) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/user/wipe_controller.ex b/lib/philomena_web/controllers/admin/user/wipe_controller.ex index ed4732b8..7376464f 100644 --- a/lib/philomena_web/controllers/admin/user/wipe_controller.ex +++ b/lib/philomena_web/controllers/admin/user/wipe_controller.ex @@ -8,18 +8,21 @@ defmodule PhilomenaWeb.Admin.User.WipeController do plug :load_resource, model: User, id_name: "user_id", id_field: "slug", persisted: true def create(conn, _params) do - spawn fn -> + spawn(fn -> UserWipe.perform(conn.assigns.user) - end + end) conn - |> put_flash(:info, "PII wipe started, please verify and then deactivate the account as necessary.") + |> put_flash( + :info, + "PII wipe started, please verify and then deactivate the account as necessary." + ) |> redirect(to: Routes.profile_path(conn, :show, conn.assigns.user)) end defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, User) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/user_ban_controller.ex b/lib/philomena_web/controllers/admin/user_ban_controller.ex index 7a9ed264..dfbdd713 100644 --- a/lib/philomena_web/controllers/admin/user_ban_controller.ex +++ b/lib/philomena_web/controllers/admin/user_ban_controller.ex @@ -14,11 +14,12 @@ defmodule PhilomenaWeb.Admin.UserBanController do UserBan |> join(:inner, [ub], _ in assoc(ub, :user)) - |> where([ub, u], - ilike(u.name, ^like_q) - or ub.generated_ban_id == ^q - or fragment("to_tsvector(?) @@ plainto_tsquery(?)", ub.reason, ^q) - or fragment("to_tsvector(?) @@ plainto_tsquery(?)", ub.note, ^q) + |> where( + [ub, u], + ilike(u.name, ^like_q) or + ub.generated_ban_id == ^q or + fragment("to_tsvector(?) @@ plainto_tsquery(?)", ub.reason, ^q) or + fragment("to_tsvector(?) @@ plainto_tsquery(?)", ub.note, ^q) ) |> load_bans(conn) end @@ -87,12 +88,16 @@ defmodule PhilomenaWeb.Admin.UserBanController do |> preload([:user, :banning_user]) |> Repo.paginate(conn.assigns.scrivener) - render(conn, "index.html", title: "Admin - User Bans", layout_class: "layout--wide", user_bans: user_bans) + render(conn, "index.html", + title: "Admin - User Bans", + layout_class: "layout--wide", + user_bans: user_bans + ) end defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, UserBan) do - true -> conn + true -> conn false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/user_controller.ex b/lib/philomena_web/controllers/admin/user_controller.ex index d59f4128..8fa7e7f4 100644 --- a/lib/philomena_web/controllers/admin/user_controller.ex +++ b/lib/philomena_web/controllers/admin/user_controller.ex @@ -8,7 +8,13 @@ defmodule PhilomenaWeb.Admin.UserController do import Ecto.Query plug :verify_authorized - plug :load_and_authorize_resource, model: User, only: [:edit, :update], id_field: "slug", preload: [:roles] + + plug :load_and_authorize_resource, + model: User, + only: [:edit, :update], + id_field: "slug", + preload: [:roles] + plug :load_roles when action in [:edit] def index(conn, %{"q" => q}) do @@ -39,7 +45,11 @@ defmodule PhilomenaWeb.Admin.UserController do |> order_by(desc: :id) |> Repo.paginate(conn.assigns.scrivener) - render(conn, "index.html", title: "Admin - Users", layout_class: "layout--medium", users: users) + render(conn, "index.html", + title: "Admin - Users", + layout_class: "layout--medium", + users: users + ) end def edit(conn, _params) do @@ -61,7 +71,7 @@ defmodule PhilomenaWeb.Admin.UserController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, User) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/admin/user_link/contact_controller.ex b/lib/philomena_web/controllers/admin/user_link/contact_controller.ex index c39e2de8..20ce0ceb 100644 --- a/lib/philomena_web/controllers/admin/user_link/contact_controller.ex +++ b/lib/philomena_web/controllers/admin/user_link/contact_controller.ex @@ -5,13 +5,21 @@ defmodule PhilomenaWeb.Admin.UserLink.ContactController do alias Philomena.UserLinks plug PhilomenaWeb.CanaryMapPlug, create: :edit - plug :load_and_authorize_resource, model: UserLink, id_name: "user_link_id", persisted: true, preload: [:user] + + plug :load_and_authorize_resource, + model: UserLink, + id_name: "user_link_id", + persisted: true, + preload: [:user] def create(conn, _params) do - {:ok, user_link} = UserLinks.contact_user_link(conn.assigns.user_link, conn.assigns.current_user) + {:ok, user_link} = + UserLinks.contact_user_link(conn.assigns.user_link, conn.assigns.current_user) conn |> put_flash(:info, "User link successfully marked as contacted.") - |> redirect(to: Routes.profile_user_link_path(conn, :show, conn.assigns.user_link.user, user_link)) + |> redirect( + to: Routes.profile_user_link_path(conn, :show, conn.assigns.user_link.user, user_link) + ) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/admin/user_link/reject_controller.ex b/lib/philomena_web/controllers/admin/user_link/reject_controller.ex index 03612f03..8e9bf6d9 100644 --- a/lib/philomena_web/controllers/admin/user_link/reject_controller.ex +++ b/lib/philomena_web/controllers/admin/user_link/reject_controller.ex @@ -5,13 +5,20 @@ defmodule PhilomenaWeb.Admin.UserLink.RejectController do alias Philomena.UserLinks plug PhilomenaWeb.CanaryMapPlug, create: :edit - plug :load_and_authorize_resource, model: UserLink, id_name: "user_link_id", persisted: true, preload: [:user] + + plug :load_and_authorize_resource, + model: UserLink, + id_name: "user_link_id", + persisted: true, + preload: [:user] def create(conn, _params) do {:ok, user_link} = UserLinks.reject_user_link(conn.assigns.user_link) conn |> put_flash(:info, "User link successfully marked as rejected.") - |> redirect(to: Routes.profile_user_link_path(conn, :show, conn.assigns.user_link.user, user_link)) + |> redirect( + to: Routes.profile_user_link_path(conn, :show, conn.assigns.user_link.user, user_link) + ) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/admin/user_link/verification_controller.ex b/lib/philomena_web/controllers/admin/user_link/verification_controller.ex index 3609b32e..3c914a52 100644 --- a/lib/philomena_web/controllers/admin/user_link/verification_controller.ex +++ b/lib/philomena_web/controllers/admin/user_link/verification_controller.ex @@ -5,13 +5,21 @@ defmodule PhilomenaWeb.Admin.UserLink.VerificationController do alias Philomena.UserLinks plug PhilomenaWeb.CanaryMapPlug, create: :edit - plug :load_and_authorize_resource, model: UserLink, id_name: "user_link_id", persisted: true, preload: [:user] + + plug :load_and_authorize_resource, + model: UserLink, + id_name: "user_link_id", + persisted: true, + preload: [:user] def create(conn, _params) do - {:ok, %{user_link: user_link}} = UserLinks.verify_user_link(conn.assigns.user_link, conn.assigns.current_user) + {:ok, %{user_link: user_link}} = + UserLinks.verify_user_link(conn.assigns.user_link, conn.assigns.current_user) conn |> put_flash(:info, "User link successfully verified.") - |> redirect(to: Routes.profile_user_link_path(conn, :show, conn.assigns.user_link.user, user_link)) + |> redirect( + to: Routes.profile_user_link_path(conn, :show, conn.assigns.user_link.user, user_link) + ) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/admin/user_link_controller.ex b/lib/philomena_web/controllers/admin/user_link_controller.ex index c3770538..11c5e717 100644 --- a/lib/philomena_web/controllers/admin/user_link_controller.ex +++ b/lib/philomena_web/controllers/admin/user_link_controller.ex @@ -30,7 +30,12 @@ defmodule PhilomenaWeb.Admin.UserLinkController do links = queryable |> order_by(desc: :created_at) - |> preload([:tag, :verified_by_user, :contacted_by_user, user: [:linked_tags, awards: :badge]]) + |> preload([ + :tag, + :verified_by_user, + :contacted_by_user, + user: [:linked_tags, awards: :badge] + ]) |> Repo.paginate(conn.assigns.scrivener) render(conn, "index.html", title: "Admin - User Links", user_links: links) @@ -38,7 +43,7 @@ defmodule PhilomenaWeb.Admin.UserLinkController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :index, UserLink) do - true -> conn + true -> conn false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/advert_controller.ex b/lib/philomena_web/controllers/advert_controller.ex index dfd5f0d0..f0845322 100644 --- a/lib/philomena_web/controllers/advert_controller.ex +++ b/lib/philomena_web/controllers/advert_controller.ex @@ -14,4 +14,4 @@ defmodule PhilomenaWeb.AdvertController do conn |> redirect(external: advert.link) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/api/json/comment_controller.ex b/lib/philomena_web/controllers/api/json/comment_controller.ex index e87527ff..4c788975 100644 --- a/lib/philomena_web/controllers/api/json/comment_controller.ex +++ b/lib/philomena_web/controllers/api/json/comment_controller.ex @@ -7,7 +7,7 @@ defmodule PhilomenaWeb.Api.Json.CommentController do import Ecto.Query def show(conn, %{"id" => id}) do - comment = + comment = Comment |> where(id: ^id) |> preload([:image, :user]) @@ -26,7 +26,6 @@ defmodule PhilomenaWeb.Api.Json.CommentController do true -> json(conn, %{comment: CommentJson.as_json(comment)}) - end end end diff --git a/lib/philomena_web/controllers/api/json/forum/topic/post_controller.ex b/lib/philomena_web/controllers/api/json/forum/topic/post_controller.ex index c1a1d8ff..2e1002d4 100644 --- a/lib/philomena_web/controllers/api/json/forum/topic/post_controller.ex +++ b/lib/philomena_web/controllers/api/json/forum/topic/post_controller.ex @@ -7,14 +7,14 @@ defmodule PhilomenaWeb.Api.Json.Forum.Topic.PostController do import Ecto.Query def show(conn, %{"forum_id" => forum_id, "topic_id" => topic_id, "id" => post_id}) do - post = + post = Post |> join(:inner, [p], _ in assoc(p, :topic)) |> join(:inner, [_p, t], _ in assoc(t, :forum)) |> where(id: ^post_id) |> where(destroyed_content: false) |> where([_p, t], t.hidden_from_users == false and t.slug == ^topic_id) - |> where([_p, _t, f], f.access_level == "normal" and f.short_name == ^forum_id) + |> where([_p, _t, f], f.access_level == "normal" and f.short_name == ^forum_id) |> preload([:user, :topic]) |> Repo.one() @@ -31,7 +31,8 @@ defmodule PhilomenaWeb.Api.Json.Forum.Topic.PostController do def index(conn, %{"forum_id" => forum_id, "topic_id" => topic_id}) do page = conn.assigns.pagination.page_number - posts = + + posts = Post |> join(:inner, [p], _ in assoc(p, :topic)) |> join(:inner, [_p, t], _ in assoc(t, :forum)) @@ -43,13 +44,17 @@ defmodule PhilomenaWeb.Api.Json.Forum.Topic.PostController do |> preload([:user, :topic]) |> preload([_p, t, _f], topic: t) |> Repo.all() - + case posts do [] -> json(conn, %{posts: Enum.map(posts, &PostJson.as_json/1), page: page}) _ -> - json(conn, %{posts: Enum.map(posts, &PostJson.as_json/1), page: page, total: hd(posts).topic.post_count}) + json(conn, %{ + posts: Enum.map(posts, &PostJson.as_json/1), + page: page, + total: hd(posts).topic.post_count + }) end end end diff --git a/lib/philomena_web/controllers/api/json/forum/topic_controller.ex b/lib/philomena_web/controllers/api/json/forum/topic_controller.ex index a7cca2f7..96da55aa 100644 --- a/lib/philomena_web/controllers/api/json/forum/topic_controller.ex +++ b/lib/philomena_web/controllers/api/json/forum/topic_controller.ex @@ -7,7 +7,7 @@ defmodule PhilomenaWeb.Api.Json.Forum.TopicController do import Ecto.Query def show(conn, %{"forum_id" => forum_id, "id" => id}) do - topic = + topic = Topic |> join(:inner, [t], _ in assoc(t, :forum)) |> where(slug: ^id) diff --git a/lib/philomena_web/controllers/api/json/forums_controller.ex b/lib/philomena_web/controllers/api/json/forums_controller.ex index d3a4e9b3..a54b28f3 100644 --- a/lib/philomena_web/controllers/api/json/forums_controller.ex +++ b/lib/philomena_web/controllers/api/json/forums_controller.ex @@ -7,7 +7,7 @@ defmodule PhilomenaWeb.Api.Json.ForumController do import Ecto.Query def show(conn, %{"id" => id}) do - forum = + forum = Forum |> where(short_name: ^id) |> where(access_level: "normal") diff --git a/lib/philomena_web/controllers/api/json/oembed_controller.ex b/lib/philomena_web/controllers/api/json/oembed_controller.ex index 452e99eb..cfda244a 100644 --- a/lib/philomena_web/controllers/api/json/oembed_controller.ex +++ b/lib/philomena_web/controllers/api/json/oembed_controller.ex @@ -13,6 +13,7 @@ defmodule PhilomenaWeb.Api.Json.OembedController do try_oembed(conn, parsed) end + def index(conn, _params), do: oembed_error(conn) defp try_oembed(conn, %{path: path}) do @@ -21,8 +22,8 @@ defmodule PhilomenaWeb.Api.Json.OembedController do image_id = cond do - cdn -> hd(cdn) - img -> hd(img) + cdn -> hd(cdn) + img -> hd(img) true -> nil end @@ -31,6 +32,7 @@ defmodule PhilomenaWeb.Api.Json.OembedController do end defp load_image(nil), do: nil + defp load_image(id) do Image |> where(id: ^id, hidden_from_users: false) @@ -66,7 +68,7 @@ defmodule PhilomenaWeb.Api.Json.OembedController do defp artist_tags(tags) do tags - |> Enum.filter(& &1.namespace == "artist") + |> Enum.filter(&(&1.namespace == "artist")) |> Enum.map_join(", ", & &1.name_in_namespace) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/api/json/post_controller.ex b/lib/philomena_web/controllers/api/json/post_controller.ex index f2d779bd..3f4c3331 100644 --- a/lib/philomena_web/controllers/api/json/post_controller.ex +++ b/lib/philomena_web/controllers/api/json/post_controller.ex @@ -7,14 +7,14 @@ defmodule PhilomenaWeb.Api.Json.PostController do import Ecto.Query def show(conn, %{"id" => post_id}) do - post = + post = Post |> join(:inner, [p], _ in assoc(p, :topic)) |> join(:inner, [_p, t], _ in assoc(t, :forum)) |> where(id: ^post_id) |> where(destroyed_content: false) |> where([_p, t], t.hidden_from_users == false) - |> where([_p, _t, f], f.access_level == "normal") + |> where([_p, _t, f], f.access_level == "normal") |> preload([:user, :topic]) |> Repo.one() diff --git a/lib/philomena_web/controllers/api/json/search/image_controller.ex b/lib/philomena_web/controllers/api/json/search/image_controller.ex index 0fafc7b4..67d55581 100644 --- a/lib/philomena_web/controllers/api/json/search/image_controller.ex +++ b/lib/philomena_web/controllers/api/json/search/image_controller.ex @@ -13,10 +13,13 @@ defmodule PhilomenaWeb.Api.Json.Search.ImageController do user = conn.assigns.current_user sort = ImageSorter.parse_sort(params) - case ImageLoader.search_string(conn, params["q"], sorts: sort.sorts, queries: sort.queries, queryable: queryable) do + case ImageLoader.search_string(conn, params["q"], + sorts: sort.sorts, + queries: sort.queries, + queryable: queryable + ) do {:ok, {images, _tags}} -> - interactions = - Interactions.user_interactions(images, user) + interactions = Interactions.user_interactions(images, user) conn |> json(%{ diff --git a/lib/philomena_web/controllers/api/json/search/post_controller.ex b/lib/philomena_web/controllers/api/json/search/post_controller.ex index 48e47f6a..1eed888a 100644 --- a/lib/philomena_web/controllers/api/json/search/post_controller.ex +++ b/lib/philomena_web/controllers/api/json/search/post_controller.ex @@ -22,7 +22,7 @@ defmodule PhilomenaWeb.Api.Json.Search.PostController do query, %{term: %{deleted: false}}, %{term: %{access_level: "normal"}} - ], + ] } }, sort: %{created_at: :desc} diff --git a/lib/philomena_web/controllers/api/json/search/reverse_controller.ex b/lib/philomena_web/controllers/api/json/search/reverse_controller.ex index e0b8ae88..f86f48cd 100644 --- a/lib/philomena_web/controllers/api/json/search/reverse_controller.ex +++ b/lib/philomena_web/controllers/api/json/search/reverse_controller.ex @@ -5,7 +5,7 @@ defmodule PhilomenaWeb.Api.Json.Search.ReverseController do alias PhilomenaWeb.ImageJson plug :set_scraper_cache - plug PhilomenaWeb.ScraperPlug, [params_key: "image", params_name: "image"] + plug PhilomenaWeb.ScraperPlug, params_key: "image", params_name: "image" def create(conn, %{"image" => image_params}) do images = @@ -29,10 +29,11 @@ defmodule PhilomenaWeb.Api.Json.Search.ReverseController do end defp normalize_dist(%{"distance" => distance}) do - "0" <> distance + ("0" <> distance) |> Float.parse() |> elem(0) |> Float.to_string() end + defp normalize_dist(_dist), do: "0.25" end diff --git a/lib/philomena_web/controllers/api/json/tag_controller.ex b/lib/philomena_web/controllers/api/json/tag_controller.ex index 884c773d..7c44391f 100644 --- a/lib/philomena_web/controllers/api/json/tag_controller.ex +++ b/lib/philomena_web/controllers/api/json/tag_controller.ex @@ -9,7 +9,7 @@ defmodule PhilomenaWeb.Api.Json.TagController do plug PhilomenaWeb.RecodeParameterPlug, [name: "id"] when action in [:show] def show(conn, %{"id" => slug}) do - tag = + tag = Tag |> where(slug: ^slug) |> preload([:aliased_tag, :aliases, :implied_tags, :implied_by_tags, :dnp_entries]) diff --git a/lib/philomena_web/controllers/avatar_controller.ex b/lib/philomena_web/controllers/avatar_controller.ex index d6106b6c..109fd337 100644 --- a/lib/philomena_web/controllers/avatar_controller.ex +++ b/lib/philomena_web/controllers/avatar_controller.ex @@ -4,7 +4,9 @@ defmodule PhilomenaWeb.AvatarController do alias Philomena.Users plug PhilomenaWeb.FilterBannedUsersPlug - plug PhilomenaWeb.ScraperPlug, [params_name: "user", params_key: "avatar"] when action in [:update] + + plug PhilomenaWeb.ScraperPlug, + [params_name: "user", params_key: "avatar"] when action in [:update] def edit(conn, _params) do changeset = Users.change_user(conn.assigns.current_user) diff --git a/lib/philomena_web/controllers/captcha_controller.ex b/lib/philomena_web/controllers/captcha_controller.ex index 705936db..95cdceb2 100644 --- a/lib/philomena_web/controllers/captcha_controller.ex +++ b/lib/philomena_web/controllers/captcha_controller.ex @@ -8,4 +8,4 @@ defmodule PhilomenaWeb.CaptchaController do render(conn, "create.html", captcha: captcha, layout: false) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/channel/read_controller.ex b/lib/philomena_web/controllers/channel/read_controller.ex index e1b4e656..415c6b57 100644 --- a/lib/philomena_web/controllers/channel/read_controller.ex +++ b/lib/philomena_web/controllers/channel/read_controller.ex @@ -15,4 +15,4 @@ defmodule PhilomenaWeb.Channel.ReadController do send_resp(conn, :ok, "") end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/channel/subscription_controller.ex b/lib/philomena_web/controllers/channel/subscription_controller.ex index d0628e70..0aaaa9ea 100644 --- a/lib/philomena_web/controllers/channel/subscription_controller.ex +++ b/lib/philomena_web/controllers/channel/subscription_controller.ex @@ -32,4 +32,4 @@ defmodule PhilomenaWeb.Channel.SubscriptionController do render(conn, "_error.html", layout: false) end end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/channel_controller.ex b/lib/philomena_web/controllers/channel_controller.ex index 048e93bc..89ec850b 100644 --- a/lib/philomena_web/controllers/channel_controller.ex +++ b/lib/philomena_web/controllers/channel_controller.ex @@ -10,6 +10,7 @@ defmodule PhilomenaWeb.ChannelController do def index(conn, _params) do show_nsfw? = conn.cookies["chan_nsfw"] == "true" + channels = Channel |> maybe_show_nsfw(show_nsfw?) @@ -20,7 +21,12 @@ defmodule PhilomenaWeb.ChannelController do subscriptions = Channels.subscriptions(channels, conn.assigns.current_user) - render(conn, "index.html", title: "Livestreams", layout_class: "layout--wide", channels: channels, subscriptions: subscriptions) + render(conn, "index.html", + title: "Livestreams", + layout_class: "layout--wide", + channels: channels, + subscriptions: subscriptions + ) end def show(conn, _params) do @@ -71,10 +77,13 @@ defmodule PhilomenaWeb.ChannelController do defp url(%{type: "LivestreamChannel", short_name: short_name}), do: "http://www.livestream.com/#{short_name}" + defp url(%{type: "PicartoChannel", short_name: short_name}), do: "https://picarto.tv/#{short_name}" + defp url(%{type: "PiczelChannel", short_name: short_name}), do: "https://piczel.tv/watch/#{short_name}" + defp url(%{type: "TwitchChannel", short_name: short_name}), do: "https://www.twitch.tv/#{short_name}" end diff --git a/lib/philomena_web/controllers/comment_controller.ex b/lib/philomena_web/controllers/comment_controller.ex index 4bb6cfb2..4e3d7fac 100644 --- a/lib/philomena_web/controllers/comment_controller.ex +++ b/lib/philomena_web/controllers/comment_controller.ex @@ -36,19 +36,19 @@ defmodule PhilomenaWeb.CommentController do Comment |> preload([:deleted_by, image: [:tags], user: [awards: :badge]]) ) - rendered = - Renderer.render_collection(comments.entries, conn) + rendered = Renderer.render_collection(comments.entries, conn) - comments = - %{comments | entries: Enum.zip(rendered, comments.entries)} + comments = %{comments | entries: Enum.zip(rendered, comments.entries)} render(conn, "index.html", title: "Comments", comments: comments) end + defp render_index({:error, msg}, conn, _user) do render(conn, "index.html", title: "Comments", error: msg, comments: []) end defp filters(%{role: role}) when role in ["moderator", "admin"], do: [] + defp filters(_user), do: [%{term: %{hidden_from_users: false}}] end diff --git a/lib/philomena_web/controllers/commission_controller.ex b/lib/philomena_web/controllers/commission_controller.ex index 7444ca47..0268de91 100644 --- a/lib/philomena_web/controllers/commission_controller.ex +++ b/lib/philomena_web/controllers/commission_controller.ex @@ -12,7 +12,11 @@ defmodule PhilomenaWeb.CommissionController do commission_search(params["commission"]) |> Repo.paginate(conn.assigns.scrivener) - render(conn, "index.html", title: "Commissions", commissions: commissions, layout_class: "layout--wide") + render(conn, "index.html", + title: "Commissions", + commissions: commissions, + layout_class: "layout--wide" + ) end defp commission_search(attrs) when is_map(attrs) do @@ -45,7 +49,11 @@ defmodule PhilomenaWeb.CommissionController do query = if keywords do query - |> where([c, _ci], ilike(c.information, ^like_sanitize(keywords)) or ilike(c.will_create, ^like_sanitize(keywords))) + |> where( + [c, _ci], + ilike(c.information, ^like_sanitize(keywords)) or + ilike(c.will_create, ^like_sanitize(keywords)) + ) else query end @@ -57,7 +65,8 @@ defmodule PhilomenaWeb.CommissionController do from c in Commission, where: c.open == true, where: c.commission_items_count > 0, - inner_join: ci in Item, on: ci.commission_id == c.id, + inner_join: ci in Item, + on: ci.commission_id == c.id, group_by: c.id, order_by: [asc: fragment("random()")], preload: [user: [awards: :badge], items: [example_image: :tags]] @@ -65,17 +74,20 @@ defmodule PhilomenaWeb.CommissionController do defp presence(nil), do: nil + defp presence([]), do: nil + defp presence(string) when is_binary(string), do: if(String.trim(string) == "", do: nil, else: string) + defp presence(object), do: object defp to_f(input) do case Float.parse(to_string(input)) do {float, _rest} -> float - _error -> 0.0 + _error -> 0.0 end end @@ -90,7 +102,7 @@ defmodule PhilomenaWeb.CommissionController do nil -> conn - user -> + user -> user = Repo.preload(user, :commission) config = Pow.Plug.fetch_config(conn) Pow.Plug.assign_current_user(conn, user, config) diff --git a/lib/philomena_web/controllers/conversation/hide_controller.ex b/lib/philomena_web/controllers/conversation/hide_controller.ex index 3abae311..44bd8bad 100644 --- a/lib/philomena_web/controllers/conversation/hide_controller.ex +++ b/lib/philomena_web/controllers/conversation/hide_controller.ex @@ -5,7 +5,12 @@ defmodule PhilomenaWeb.Conversation.HideController do alias Philomena.Conversations plug PhilomenaWeb.CanaryMapPlug, create: :show, delete: :show - plug :load_and_authorize_resource, model: Conversation, id_field: "slug", id_name: "conversation_id", persisted: true + + plug :load_and_authorize_resource, + model: Conversation, + id_field: "slug", + id_name: "conversation_id", + persisted: true def create(conn, _params) do conversation = conn.assigns.conversation @@ -28,4 +33,4 @@ defmodule PhilomenaWeb.Conversation.HideController do |> put_flash(:info, "Conversation restored.") |> redirect(to: Routes.conversation_path(conn, :show, conversation)) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/conversation/message_controller.ex b/lib/philomena_web/controllers/conversation/message_controller.ex index fc3c9c1b..6327877a 100644 --- a/lib/philomena_web/controllers/conversation/message_controller.ex +++ b/lib/philomena_web/controllers/conversation/message_controller.ex @@ -8,7 +8,12 @@ defmodule PhilomenaWeb.Conversation.MessageController do plug PhilomenaWeb.FilterBannedUsersPlug plug PhilomenaWeb.CanaryMapPlug, create: :show - plug :load_and_authorize_resource, model: Conversation, id_name: "conversation_id", id_field: "slug", persisted: true + + plug :load_and_authorize_resource, + model: Conversation, + id_name: "conversation_id", + id_field: "slug", + persisted: true def create(conn, %{"message" => message_params}) do conversation = conn.assigns.conversation @@ -35,4 +40,4 @@ defmodule PhilomenaWeb.Conversation.MessageController do |> redirect(external: conn.assigns.referrer) end end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/conversation/read_controller.ex b/lib/philomena_web/controllers/conversation/read_controller.ex index d5b5166e..93a5601e 100644 --- a/lib/philomena_web/controllers/conversation/read_controller.ex +++ b/lib/philomena_web/controllers/conversation/read_controller.ex @@ -5,7 +5,12 @@ defmodule PhilomenaWeb.Conversation.ReadController do alias Philomena.Conversations plug PhilomenaWeb.CanaryMapPlug, create: :show, delete: :show - plug :load_and_authorize_resource, model: Conversation, id_field: "slug", id_name: "conversation_id", persisted: true + + plug :load_and_authorize_resource, + model: Conversation, + id_field: "slug", + id_name: "conversation_id", + persisted: true def create(conn, _params) do conversation = conn.assigns.conversation @@ -28,4 +33,4 @@ defmodule PhilomenaWeb.Conversation.ReadController do |> put_flash(:info, "Conversation marked as unread.") |> redirect(to: Routes.conversation_path(conn, :index)) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/conversation/report_controller.ex b/lib/philomena_web/controllers/conversation/report_controller.ex index f6b12113..18c4a466 100644 --- a/lib/philomena_web/controllers/conversation/report_controller.ex +++ b/lib/philomena_web/controllers/conversation/report_controller.ex @@ -11,18 +11,30 @@ defmodule PhilomenaWeb.Conversation.ReportController do plug PhilomenaWeb.UserAttributionPlug plug PhilomenaWeb.CaptchaPlug when action in [:create] plug PhilomenaWeb.CanaryMapPlug, new: :show, create: :show - plug :load_and_authorize_resource, model: Conversation, id_name: "conversation_id", id_field: "slug", persisted: true, preload: [:from, :to] + + plug :load_and_authorize_resource, + model: Conversation, + id_name: "conversation_id", + id_field: "slug", + persisted: true, + preload: [:from, :to] def new(conn, _params) do conversation = conn.assigns.conversation action = Routes.conversation_report_path(conn, :create, conversation) + changeset = %Report{reportable_type: "Conversation", reportable_id: conversation.id} |> Reports.change_report() conn |> put_view(ReportView) - |> render("new.html", title: "Reporting Conversation", reportable: conversation, changeset: changeset, action: action) + |> render("new.html", + title: "Reporting Conversation", + reportable: conversation, + changeset: changeset, + action: action + ) end def create(conn, params) do diff --git a/lib/philomena_web/controllers/conversation_controller.ex b/lib/philomena_web/controllers/conversation_controller.ex index d92c5d6e..817c4275 100644 --- a/lib/philomena_web/controllers/conversation_controller.ex +++ b/lib/philomena_web/controllers/conversation_controller.ex @@ -8,13 +8,22 @@ defmodule PhilomenaWeb.ConversationController do import Ecto.Query plug PhilomenaWeb.FilterBannedUsersPlug when action in [:new, :create] - plug :load_and_authorize_resource, model: Conversation, id_field: "slug", only: :show, preload: [:to, :from] + + plug :load_and_authorize_resource, + model: Conversation, + id_field: "slug", + only: :show, + preload: [:to, :from] def index(conn, %{"with" => partner}) do user = conn.assigns.current_user Conversation - |> where([c], (c.from_id == ^user.id and c.to_id == ^partner and not c.from_hidden) or (c.to_id == ^user.id and c.from_id == ^partner and not c.to_hidden)) + |> where( + [c], + (c.from_id == ^user.id and c.to_id == ^partner and not c.from_hidden) or + (c.to_id == ^user.id and c.from_id == ^partner and not c.to_hidden) + ) |> load_conversations(conn) end @@ -22,14 +31,21 @@ defmodule PhilomenaWeb.ConversationController do user = conn.assigns.current_user Conversation - |> where([c], (c.from_id == ^user.id and not c.from_hidden) or (c.to_id == ^user.id and not c.to_hidden)) + |> where( + [c], + (c.from_id == ^user.id and not c.from_hidden) or (c.to_id == ^user.id and not c.to_hidden) + ) |> load_conversations(conn) end defp load_conversations(queryable, conn) do conversations = queryable - |> join(:inner_lateral, [c], _ in fragment("SELECT COUNT(*) FROM messages m WHERE m.conversation_id = ?", c.id)) + |> join( + :inner_lateral, + [c], + _ in fragment("SELECT COUNT(*) FROM messages m WHERE m.conversation_id = ?", c.id) + ) |> order_by(desc: :last_message_at) |> preload([:to, :from]) |> select([c, cnt], {c, cnt.count}) @@ -53,8 +69,7 @@ defmodule PhilomenaWeb.ConversationController do messages.entries |> Renderer.render_collection(conn) - messages = - %{messages | entries: Enum.zip(messages.entries, rendered)} + messages = %{messages | entries: Enum.zip(messages.entries, rendered)} changeset = %Message{} @@ -66,7 +81,12 @@ defmodule PhilomenaWeb.ConversationController do # Update the conversation ticker in the header conn = NotificationCountPlug.call(conn) - render(conn, "show.html", title: "Showing Conversation", conversation: conversation, messages: messages, changeset: changeset) + render(conn, "show.html", + title: "Showing Conversation", + conversation: conversation, + messages: messages, + changeset: changeset + ) end def new(conn, params) do diff --git a/lib/philomena_web/controllers/dnp_entry_controller.ex b/lib/philomena_web/controllers/dnp_entry_controller.ex index 3e1564ff..a531e57c 100644 --- a/lib/philomena_web/controllers/dnp_entry_controller.ex +++ b/lib/philomena_web/controllers/dnp_entry_controller.ex @@ -11,7 +11,12 @@ defmodule PhilomenaWeb.DnpEntryController do import Ecto.Query plug PhilomenaWeb.FilterBannedUsersPlug when action in [:new, :create] - plug :load_and_authorize_resource, model: DnpEntry, only: [:show, :edit, :update], preload: [:tag] + + plug :load_and_authorize_resource, + model: DnpEntry, + only: [:show, :edit, :update], + preload: [:tag] + plug :set_mod_notes when action in [:show] def index(%{assigns: %{current_user: user}} = conn, %{"mine" => _mine}) when not is_nil(user) do @@ -40,10 +45,15 @@ defmodule PhilomenaWeb.DnpEntryController do |> Enum.map(&%{body: &1.conditions || "-"}) |> Renderer.render_collection(conn) - dnp_entries = - %{dnp_entries | entries: Enum.zip(bodies, dnp_entries.entries)} + dnp_entries = %{dnp_entries | entries: Enum.zip(bodies, dnp_entries.entries)} - render(conn, "index.html", title: "Do-Not-Post List", layout_class: "layout--medium", dnp_entries: dnp_entries, status_column: status, linked_tags: linked_tags) + render(conn, "index.html", + title: "Do-Not-Post List", + layout_class: "layout--medium", + dnp_entries: dnp_entries, + status_column: status, + linked_tags: linked_tags + ) end def show(conn, _params) do @@ -59,16 +69,31 @@ defmodule PhilomenaWeb.DnpEntryController do conn ) - render(conn, "show.html", title: "Showing DNP Listing", dnp_entry: dnp_entry, conditions: conditions, reason: reason, instructions: instructions) + render(conn, "show.html", + title: "Showing DNP Listing", + dnp_entry: dnp_entry, + conditions: conditions, + reason: reason, + instructions: instructions + ) end def new(conn, _params) do changeset = DnpEntries.change_dnp_entry(%DnpEntry{}) - render(conn, "new.html", title: "New DNP Listing", changeset: changeset, selectable_tags: selectable_tags(conn)) + + render(conn, "new.html", + title: "New DNP Listing", + changeset: changeset, + selectable_tags: selectable_tags(conn) + ) end def create(conn, %{"dnp_entry" => dnp_entry_params}) do - case DnpEntries.create_dnp_entry(conn.assigns.current_user, selectable_tags(conn), dnp_entry_params) do + case DnpEntries.create_dnp_entry( + conn.assigns.current_user, + selectable_tags(conn), + dnp_entry_params + ) do {:ok, dnp_entry} -> conn |> put_flash(:info, "Successfully submitted DNP request.") @@ -81,11 +106,20 @@ defmodule PhilomenaWeb.DnpEntryController do def edit(conn, _params) do changeset = DnpEntries.change_dnp_entry(conn.assigns.dnp_entry) - render(conn, "edit.html", title: "Editing DNP Listing", changeset: changeset, selectable_tags: selectable_tags(conn)) + + render(conn, "edit.html", + title: "Editing DNP Listing", + changeset: changeset, + selectable_tags: selectable_tags(conn) + ) end def update(conn, %{"dnp_entry" => dnp_entry_params}) do - case DnpEntries.update_dnp_entry(conn.assigns.dnp_entry, selectable_tags(conn), dnp_entry_params) do + case DnpEntries.update_dnp_entry( + conn.assigns.dnp_entry, + selectable_tags(conn), + dnp_entry_params + ) do {:ok, dnp_entry} -> conn |> put_flash(:info, "Successfully updated DNP request.") @@ -97,7 +131,8 @@ defmodule PhilomenaWeb.DnpEntryController do end defp selectable_tags(conn) do - case not is_nil(conn.params["tag_id"]) and Canada.Can.can?(conn.assigns.current_user, :index, DnpEntry) do + case not is_nil(conn.params["tag_id"]) and + Canada.Can.can?(conn.assigns.current_user, :index, DnpEntry) do true -> [Repo.get!(Tag, conn.params["tag_id"])] false -> linked_tags(conn) end @@ -108,6 +143,7 @@ defmodule PhilomenaWeb.DnpEntryController do |> Repo.preload(:linked_tags) |> Map.get(:linked_tags) end + defp linked_tags(_), do: [] defp set_mod_notes(conn, _opts) do diff --git a/lib/philomena_web/controllers/duplicate_report/accept_controller.ex b/lib/philomena_web/controllers/duplicate_report/accept_controller.ex index f134421d..0cfacb87 100644 --- a/lib/philomena_web/controllers/duplicate_report/accept_controller.ex +++ b/lib/philomena_web/controllers/duplicate_report/accept_controller.ex @@ -6,10 +6,20 @@ defmodule PhilomenaWeb.DuplicateReport.AcceptController do alias Philomena.Images plug PhilomenaWeb.CanaryMapPlug, create: :edit, delete: :edit - plug :load_and_authorize_resource, model: DuplicateReport, id_name: "duplicate_report_id", persisted: true, preload: [:image, :duplicate_of_image] + + plug :load_and_authorize_resource, + model: DuplicateReport, + id_name: "duplicate_report_id", + persisted: true, + preload: [:image, :duplicate_of_image] def create(conn, _params) do - {:ok, _report} = DuplicateReports.accept_duplicate_report(conn.assigns.duplicate_report, conn.assigns.current_user) + {:ok, _report} = + DuplicateReports.accept_duplicate_report( + conn.assigns.duplicate_report, + conn.assigns.current_user + ) + Images.reindex_image(conn.assigns.duplicate_report.image) Images.reindex_image(conn.assigns.duplicate_report.duplicate_of_image) @@ -17,4 +27,4 @@ defmodule PhilomenaWeb.DuplicateReport.AcceptController do |> put_flash(:info, "Successfully accepted report.") |> redirect(external: conn.assigns.referrer) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/duplicate_report/accept_reverse_controller.ex b/lib/philomena_web/controllers/duplicate_report/accept_reverse_controller.ex index d9386ba6..800378b8 100644 --- a/lib/philomena_web/controllers/duplicate_report/accept_reverse_controller.ex +++ b/lib/philomena_web/controllers/duplicate_report/accept_reverse_controller.ex @@ -6,10 +6,20 @@ defmodule PhilomenaWeb.DuplicateReport.AcceptReverseController do alias Philomena.Images plug PhilomenaWeb.CanaryMapPlug, create: :edit, delete: :edit - plug :load_and_authorize_resource, model: DuplicateReport, id_name: "duplicate_report_id", persisted: true, preload: [:image, :duplicate_of_image] + + plug :load_and_authorize_resource, + model: DuplicateReport, + id_name: "duplicate_report_id", + persisted: true, + preload: [:image, :duplicate_of_image] def create(conn, _params) do - {:ok, _report} = DuplicateReports.accept_reverse_duplicate_report(conn.assigns.duplicate_report, conn.assigns.current_user) + {:ok, _report} = + DuplicateReports.accept_reverse_duplicate_report( + conn.assigns.duplicate_report, + conn.assigns.current_user + ) + Images.reindex_image(conn.assigns.duplicate_report.image) Images.reindex_image(conn.assigns.duplicate_report.duplicate_of_image) @@ -17,4 +27,4 @@ defmodule PhilomenaWeb.DuplicateReport.AcceptReverseController do |> put_flash(:info, "Successfully accepted report in reverse.") |> redirect(external: conn.assigns.referrer) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/duplicate_report/claim_controller.ex b/lib/philomena_web/controllers/duplicate_report/claim_controller.ex index 5fe66286..539282c8 100644 --- a/lib/philomena_web/controllers/duplicate_report/claim_controller.ex +++ b/lib/philomena_web/controllers/duplicate_report/claim_controller.ex @@ -5,10 +5,18 @@ defmodule PhilomenaWeb.DuplicateReport.ClaimController do alias Philomena.DuplicateReports plug PhilomenaWeb.CanaryMapPlug, create: :edit, delete: :edit - plug :load_and_authorize_resource, model: DuplicateReport, id_name: "duplicate_report_id", persisted: true + + plug :load_and_authorize_resource, + model: DuplicateReport, + id_name: "duplicate_report_id", + persisted: true def create(conn, _params) do - {:ok, _report} = DuplicateReports.claim_duplicate_report(conn.assigns.duplicate_report, conn.assigns.current_user) + {:ok, _report} = + DuplicateReports.claim_duplicate_report( + conn.assigns.duplicate_report, + conn.assigns.current_user + ) conn |> put_flash(:info, "Successfully claimed report.") @@ -22,4 +30,4 @@ defmodule PhilomenaWeb.DuplicateReport.ClaimController do |> put_flash(:info, "Successfully released report.") |> redirect(external: conn.assigns.referrer) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/duplicate_report/reject_controller.ex b/lib/philomena_web/controllers/duplicate_report/reject_controller.ex index 5d16822c..280099ef 100644 --- a/lib/philomena_web/controllers/duplicate_report/reject_controller.ex +++ b/lib/philomena_web/controllers/duplicate_report/reject_controller.ex @@ -6,10 +6,20 @@ defmodule PhilomenaWeb.DuplicateReport.RejectController do alias Philomena.Images plug PhilomenaWeb.CanaryMapPlug, create: :edit, delete: :edit - plug :load_and_authorize_resource, model: DuplicateReport, id_name: "duplicate_report_id", persisted: true, preload: [:image, :duplicate_of_image] + + plug :load_and_authorize_resource, + model: DuplicateReport, + id_name: "duplicate_report_id", + persisted: true, + preload: [:image, :duplicate_of_image] def create(conn, _params) do - {:ok, _report} = DuplicateReports.reject_duplicate_report(conn.assigns.duplicate_report, conn.assigns.current_user) + {:ok, _report} = + DuplicateReports.reject_duplicate_report( + conn.assigns.duplicate_report, + conn.assigns.current_user + ) + {:ok, _image} = Images.unhide_image(conn.assigns.duplicate_report.image) Images.reindex_image(conn.assigns.duplicate_report.image) Images.reindex_image(conn.assigns.duplicate_report.duplicate_of_image) @@ -18,4 +28,4 @@ defmodule PhilomenaWeb.DuplicateReport.RejectController do |> put_flash(:info, "Successfully rejected report.") |> redirect(external: conn.assigns.referrer) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/duplicate_report_controller.ex b/lib/philomena_web/controllers/duplicate_report_controller.ex index 0879b5d4..73a3e115 100644 --- a/lib/philomena_web/controllers/duplicate_report_controller.ex +++ b/lib/philomena_web/controllers/duplicate_report_controller.ex @@ -11,7 +11,11 @@ defmodule PhilomenaWeb.DuplicateReportController do plug PhilomenaWeb.FilterBannedUsersPlug when action in [:create] plug PhilomenaWeb.UserAttributionPlug when action in [:create] - plug :load_resource, model: DuplicateReport, only: [:show], preload: [:image, :duplicate_of_image] + + plug :load_resource, + model: DuplicateReport, + only: [:show], + preload: [:image, :duplicate_of_image] def index(conn, params) do states = @@ -26,7 +30,11 @@ defmodule PhilomenaWeb.DuplicateReportController do |> order_by(desc: :created_at) |> Repo.paginate(conn.assigns.pagination) - render(conn, "index.html", title: "Duplicate Reports", duplicate_reports: duplicate_reports, layout_class: "layout--wide") + render(conn, "index.html", + title: "Duplicate Reports", + duplicate_reports: duplicate_reports, + layout_class: "layout--wide" + ) end def create(conn, %{"duplicate_report" => duplicate_report_params}) do @@ -34,7 +42,12 @@ defmodule PhilomenaWeb.DuplicateReportController do source = Repo.get!(Image, duplicate_report_params["image_id"]) target = Repo.get!(Image, duplicate_report_params["duplicate_of_image_id"]) - case DuplicateReports.create_duplicate_report(source, target, attributes, duplicate_report_params) do + case DuplicateReports.create_duplicate_report( + source, + target, + attributes, + duplicate_report_params + ) do {:ok, duplicate_report} -> conn |> put_flash(:info, "Duplicate report created successfully.") @@ -50,7 +63,11 @@ defmodule PhilomenaWeb.DuplicateReportController do def show(conn, _params) do dr = conn.assigns.duplicate_report - render(conn, "show.html", title: "Showing Duplicate Report", duplicate_report: dr, layout_class: "layout--wide") + render(conn, "show.html", + title: "Showing Duplicate Report", + duplicate_report: dr, + layout_class: "layout--wide" + ) end defp wrap(list) when is_list(list), do: list diff --git a/lib/philomena_web/controllers/filter/hide_controller.ex b/lib/philomena_web/controllers/filter/hide_controller.ex index 85463428..fcf0f387 100644 --- a/lib/philomena_web/controllers/filter/hide_controller.ex +++ b/lib/philomena_web/controllers/filter/hide_controller.ex @@ -49,4 +49,4 @@ defmodule PhilomenaWeb.Filter.HideController do |> text("") end end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/filter/spoiler_controller.ex b/lib/philomena_web/controllers/filter/spoiler_controller.ex index e239338c..4f568fa6 100644 --- a/lib/philomena_web/controllers/filter/spoiler_controller.ex +++ b/lib/philomena_web/controllers/filter/spoiler_controller.ex @@ -49,4 +49,4 @@ defmodule PhilomenaWeb.Filter.SpoilerController do |> text("") end end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/filter/spoiler_type_controller.ex b/lib/philomena_web/controllers/filter/spoiler_type_controller.ex index b3d0f9e5..f0527068 100644 --- a/lib/philomena_web/controllers/filter/spoiler_type_controller.ex +++ b/lib/philomena_web/controllers/filter/spoiler_type_controller.ex @@ -18,4 +18,4 @@ defmodule PhilomenaWeb.Filter.SpoilerTypeController do |> redirect(external: conn.assigns.referrer) end end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/filter_controller.ex b/lib/philomena_web/controllers/filter_controller.ex index e27d658f..217a70f4 100644 --- a/lib/philomena_web/controllers/filter_controller.ex +++ b/lib/philomena_web/controllers/filter_controller.ex @@ -28,13 +28,17 @@ defmodule PhilomenaWeb.FilterController do |> preload(:user) |> Repo.all() - render(conn, "index.html", title: "Filters", my_filters: my_filters, system_filters: system_filters) + render(conn, "index.html", + title: "Filters", + my_filters: my_filters, + system_filters: system_filters + ) end def show(conn, _params) do filter = conn.assigns.filter - spoilered_tags = + spoilered_tags = Tag |> where([t], t.id in ^filter.spoilered_tag_ids) |> order_by(asc: :name) @@ -46,7 +50,12 @@ defmodule PhilomenaWeb.FilterController do |> order_by(asc: :name) |> Repo.all() - render(conn, "show.html", title: "Showing Filter", filter: filter, spoilered_tags: spoilered_tags, hidden_tags: hidden_tags) + render(conn, "show.html", + title: "Showing Filter", + filter: filter, + spoilered_tags: spoilered_tags, + hidden_tags: hidden_tags + ) end def new(conn, _params) do @@ -68,7 +77,7 @@ defmodule PhilomenaWeb.FilterController do def edit(conn, _params) do filter = - conn.assigns.filter + conn.assigns.filter |> TagList.assign_tag_list(:spoilered_tag_ids, :spoilered_tag_list) |> TagList.assign_tag_list(:hidden_tag_ids, :hidden_tag_list) diff --git a/lib/philomena_web/controllers/fingerprint_profile/source_change_controller.ex b/lib/philomena_web/controllers/fingerprint_profile/source_change_controller.ex index b3ccf771..cfeaece2 100644 --- a/lib/philomena_web/controllers/fingerprint_profile/source_change_controller.ex +++ b/lib/philomena_web/controllers/fingerprint_profile/source_change_controller.ex @@ -15,12 +15,16 @@ defmodule PhilomenaWeb.FingerprintProfile.SourceChangeController do |> preload([:user, image: [:user, :tags]]) |> Repo.paginate(conn.assigns.scrivener) - render(conn, "index.html", title: "Source Changes for Fingerprint `#{fingerprint}'", fingerprint: fingerprint, source_changes: source_changes) + render(conn, "index.html", + title: "Source Changes for Fingerprint `#{fingerprint}'", + fingerprint: fingerprint, + source_changes: source_changes + ) end defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :show, :ip_address) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/fingerprint_profile/tag_change_controller.ex b/lib/philomena_web/controllers/fingerprint_profile/tag_change_controller.ex index 38f36fd6..af698483 100644 --- a/lib/philomena_web/controllers/fingerprint_profile/tag_change_controller.ex +++ b/lib/philomena_web/controllers/fingerprint_profile/tag_change_controller.ex @@ -16,19 +16,25 @@ defmodule PhilomenaWeb.FingerprintProfile.TagChangeController do |> order_by(desc: :created_at) |> Repo.paginate(conn.assigns.scrivener) - render(conn, "index.html", title: "Tag Changes for Fingerprint `#{fingerprint}'", fingerprint: fingerprint, tag_changes: tag_changes) + render(conn, "index.html", + title: "Tag Changes for Fingerprint `#{fingerprint}'", + fingerprint: fingerprint, + tag_changes: tag_changes + ) end defp added_filter(query, %{"added" => "1"}), do: where(query, added: true) + defp added_filter(query, %{"added" => "0"}), do: where(query, added: false) + defp added_filter(query, _params), do: query defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :show, :ip_address) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/fingerprint_profile_controller.ex b/lib/philomena_web/controllers/fingerprint_profile_controller.ex index ee5010fd..d73da309 100644 --- a/lib/philomena_web/controllers/fingerprint_profile_controller.ex +++ b/lib/philomena_web/controllers/fingerprint_profile_controller.ex @@ -21,13 +21,18 @@ defmodule PhilomenaWeb.FingerprintProfileController do |> where(fingerprint: ^fingerprint) |> Repo.all() - render(conn, "show.html", title: "#{fingerprint}'s fingerprint profile", fingerprint: fingerprint, user_fps: user_fps, fingerprint_bans: fp_bans) + render(conn, "show.html", + title: "#{fingerprint}'s fingerprint profile", + fingerprint: fingerprint, + user_fps: user_fps, + fingerprint_bans: fp_bans + ) end defp authorize_ip(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :show, :ip_address) do false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) - true -> conn + true -> conn end end end diff --git a/lib/philomena_web/controllers/forum/read_controller.ex b/lib/philomena_web/controllers/forum/read_controller.ex index bdcb129d..2a10242e 100644 --- a/lib/philomena_web/controllers/forum/read_controller.ex +++ b/lib/philomena_web/controllers/forum/read_controller.ex @@ -5,7 +5,11 @@ defmodule PhilomenaWeb.Forum.ReadController do alias Philomena.Forums.Forum alias Philomena.Forums - plug :load_and_authorize_resource, model: Forum, id_name: "forum_id", id_field: "short_name", persisted: true + plug :load_and_authorize_resource, + model: Forum, + id_name: "forum_id", + id_field: "short_name", + persisted: true def create(conn, _params) do forum = conn.assigns.forum @@ -15,4 +19,4 @@ defmodule PhilomenaWeb.Forum.ReadController do send_resp(conn, :ok, "") end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/forum/subscription_controller.ex b/lib/philomena_web/controllers/forum/subscription_controller.ex index 221feb7a..fca9405d 100644 --- a/lib/philomena_web/controllers/forum/subscription_controller.ex +++ b/lib/philomena_web/controllers/forum/subscription_controller.ex @@ -5,7 +5,12 @@ defmodule PhilomenaWeb.Forum.SubscriptionController do alias Philomena.Forums plug PhilomenaWeb.CanaryMapPlug, create: :show, delete: :show - plug :load_and_authorize_resource, model: Forum, id_name: "forum_id", id_field: "short_name", persisted: true + + plug :load_and_authorize_resource, + model: Forum, + id_name: "forum_id", + id_field: "short_name", + persisted: true def create(conn, _params) do forum = conn.assigns.forum @@ -32,4 +37,4 @@ defmodule PhilomenaWeb.Forum.SubscriptionController do render(conn, "_error.html", layout: false) end end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/forum_controller.ex b/lib/philomena_web/controllers/forum_controller.ex index 89ace9dc..54e30e15 100644 --- a/lib/philomena_web/controllers/forum_controller.ex +++ b/lib/philomena_web/controllers/forum_controller.ex @@ -9,10 +9,11 @@ defmodule PhilomenaWeb.ForumController do def index(conn, _params) do user = conn.assigns.current_user + forums = Forum |> order_by(asc: :name) - |> preload([last_post: [:user, topic: :forum]]) + |> preload(last_post: [:user, topic: :forum]) |> Repo.all() |> Enum.filter(&Canada.Can.can?(user, :show, &1)) @@ -35,6 +36,11 @@ defmodule PhilomenaWeb.ForumController do watching = Forums.subscribed?(forum, user) - render(conn, "show.html", title: forum.name, forum: conn.assigns.forum, watching: watching, topics: topics) + render(conn, "show.html", + title: forum.name, + forum: conn.assigns.forum, + watching: watching, + topics: topics + ) end end diff --git a/lib/philomena_web/controllers/gallery/image_controller.ex b/lib/philomena_web/controllers/gallery/image_controller.ex index 40de0a83..2bf3c3af 100644 --- a/lib/philomena_web/controllers/gallery/image_controller.ex +++ b/lib/philomena_web/controllers/gallery/image_controller.ex @@ -34,4 +34,4 @@ defmodule PhilomenaWeb.Gallery.ImageController do json(conn, %{}) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/gallery/order_controller.ex b/lib/philomena_web/controllers/gallery/order_controller.ex index 47a0d1c0..4892d5d4 100644 --- a/lib/philomena_web/controllers/gallery/order_controller.ex +++ b/lib/philomena_web/controllers/gallery/order_controller.ex @@ -14,4 +14,4 @@ defmodule PhilomenaWeb.Gallery.OrderController do json(conn, %{}) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/gallery/read_controller.ex b/lib/philomena_web/controllers/gallery/read_controller.ex index b4bdca8e..eee4e3d0 100644 --- a/lib/philomena_web/controllers/gallery/read_controller.ex +++ b/lib/philomena_web/controllers/gallery/read_controller.ex @@ -15,4 +15,4 @@ defmodule PhilomenaWeb.Gallery.ReadController do send_resp(conn, :ok, "") end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/gallery/report_controller.ex b/lib/philomena_web/controllers/gallery/report_controller.ex index d2d812f2..d530b591 100644 --- a/lib/philomena_web/controllers/gallery/report_controller.ex +++ b/lib/philomena_web/controllers/gallery/report_controller.ex @@ -11,18 +11,29 @@ defmodule PhilomenaWeb.Gallery.ReportController do plug PhilomenaWeb.UserAttributionPlug plug PhilomenaWeb.CaptchaPlug when action in [:create] plug PhilomenaWeb.CanaryMapPlug, new: :show, create: :show - plug :load_and_authorize_resource, model: Gallery, id_name: "gallery_id", persisted: true, preload: [:creator] + + plug :load_and_authorize_resource, + model: Gallery, + id_name: "gallery_id", + persisted: true, + preload: [:creator] def new(conn, _params) do gallery = conn.assigns.gallery action = Routes.gallery_report_path(conn, :create, gallery) + changeset = %Report{reportable_type: "Gallery", reportable_id: gallery.id} |> Reports.change_report() conn |> put_view(ReportView) - |> render("new.html", title: "Reporting Gallery", reportable: gallery, changeset: changeset, action: action) + |> render("new.html", + title: "Reporting Gallery", + reportable: gallery, + changeset: changeset, + action: action + ) end def create(conn, params) do diff --git a/lib/philomena_web/controllers/gallery/subscription_controller.ex b/lib/philomena_web/controllers/gallery/subscription_controller.ex index f4e4e06d..21e80aa1 100644 --- a/lib/philomena_web/controllers/gallery/subscription_controller.ex +++ b/lib/philomena_web/controllers/gallery/subscription_controller.ex @@ -32,4 +32,4 @@ defmodule PhilomenaWeb.Gallery.SubscriptionController do render(conn, "_error.html", layout: false) end end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/gallery_controller.ex b/lib/philomena_web/controllers/gallery_controller.ex index c79242a1..6d919b6a 100644 --- a/lib/philomena_web/controllers/gallery_controller.ex +++ b/lib/philomena_web/controllers/gallery_controller.ex @@ -11,7 +11,11 @@ defmodule PhilomenaWeb.GalleryController do import Ecto.Query plug PhilomenaWeb.FilterBannedUsersPlug when action in [:new, :create, :edit, :update, :delete] - plug :load_and_authorize_resource, model: Gallery, except: [:index], preload: [:creator, thumbnail: :tags] + + plug :load_and_authorize_resource, + model: Gallery, + except: [:index], + preload: [:creator, thumbnail: :tags] def index(conn, params) do galleries = @@ -23,23 +27,36 @@ defmodule PhilomenaWeb.GalleryController do must: parse_search(params) } }, - sort: parse_sort(params), + sort: parse_sort(params) }, conn.assigns.pagination, Gallery |> preload([:creator, thumbnail: :tags]) ) - render(conn, "index.html", title: "Galleries", galleries: galleries, layout_class: "layout--wide") + render(conn, "index.html", + title: "Galleries", + galleries: galleries, + layout_class: "layout--wide" + ) end def show(conn, _params) do gallery = conn.assigns.gallery user = conn.assigns.current_user query = "gallery_id:#{gallery.id}" - params = Map.merge(conn.params, %{"q" => query, "sf" => "gallery_id:#{gallery.id}", "sd" => position_order(gallery)}) + + params = + Map.merge(conn.params, %{ + "q" => query, + "sf" => "gallery_id:#{gallery.id}", + "sd" => position_order(gallery) + }) + sort = ImageSorter.parse_sort(params) - {:ok, {images, _tags}} = ImageLoader.search_string(conn, query, queries: sort.queries, sorts: sort.sorts) + {:ok, {images, _tags}} = + ImageLoader.search_string(conn, query, queries: sort.queries, sorts: sort.sorts) + interactions = Interactions.user_interactions(images, user) watching = Galleries.subscribed?(gallery, user) @@ -50,8 +67,15 @@ defmodule PhilomenaWeb.GalleryController do conn |> NotificationCountPlug.call([]) |> Map.put(:params, params) - |> assign(:clientside_data, [gallery_images: gallery_images]) - |> render("show.html", title: "Showing Gallery", layout_class: "layout--wide", watching: watching, gallery: gallery, images: images, interactions: interactions) + |> assign(:clientside_data, gallery_images: gallery_images) + |> render("show.html", + title: "Showing Gallery", + layout_class: "layout--wide", + watching: watching, + gallery: gallery, + images: images, + interactions: interactions + ) end def new(conn, _params) do @@ -61,7 +85,7 @@ defmodule PhilomenaWeb.GalleryController do def create(conn, %{"gallery" => gallery_params}) do user = conn.assigns.current_user - + case Galleries.create_gallery(user, gallery_params) do {:ok, gallery} -> Galleries.reindex_gallery(gallery) @@ -113,21 +137,26 @@ defmodule PhilomenaWeb.GalleryController do defp parse_search(%{"gallery" => gallery_params}) do parse_title(gallery_params) ++ - parse_creator(gallery_params) ++ - parse_included_image(gallery_params) ++ - parse_description(gallery_params) + parse_creator(gallery_params) ++ + parse_included_image(gallery_params) ++ + parse_description(gallery_params) end + defp parse_search(_params), do: [%{match_all: %{}}] defp parse_title(%{"title" => title}) when is_binary(title) and title not in [nil, ""], do: [%{wildcard: %{title: "*" <> String.downcase(title) <> "*"}}] + defp parse_title(_params), do: [] - defp parse_creator(%{"creator" => creator}) when is_binary(creator) and creator not in [nil, ""], - do: [%{term: %{creator: String.downcase(creator)}}] + defp parse_creator(%{"creator" => creator}) + when is_binary(creator) and creator not in [nil, ""], + do: [%{term: %{creator: String.downcase(creator)}}] + defp parse_creator(_params), do: [] - defp parse_included_image(%{"include_image" => image_id}) when is_binary(image_id) and image_id not in [nil, ""] do + defp parse_included_image(%{"include_image" => image_id}) + when is_binary(image_id) and image_id not in [nil, ""] do with {image_id, _rest} <- Integer.parse(image_id) do [%{term: %{image_ids: image_id}}] else @@ -135,18 +164,21 @@ defmodule PhilomenaWeb.GalleryController do [] end end + defp parse_included_image(_params), do: [] - defp parse_description(%{"description" => description}) when is_binary(description) and description not in [nil, ""], - do: [%{match_phrase: %{description: description}}] + defp parse_description(%{"description" => description}) + when is_binary(description) and description not in [nil, ""], + do: [%{match_phrase: %{description: description}}] + defp parse_description(_params), do: [] defp parse_sort(%{"gallery" => %{"sf" => sf, "sd" => sd}}) - when sf in ["created_at", "updated_at", "image_count", "_score"] - and sd in ["desc", "asc"] - do + when sf in ["created_at", "updated_at", "image_count", "_score"] and + sd in ["desc", "asc"] do %{sf => sd} end + defp parse_sort(_params) do %{created_at: :desc} end diff --git a/lib/philomena_web/controllers/image/comment/delete_controller.ex b/lib/philomena_web/controllers/image/comment/delete_controller.ex index c79eb9eb..5cbf285d 100644 --- a/lib/philomena_web/controllers/image/comment/delete_controller.ex +++ b/lib/philomena_web/controllers/image/comment/delete_controller.ex @@ -16,12 +16,16 @@ defmodule PhilomenaWeb.Image.Comment.DeleteController do conn |> put_flash(:info, "Comment successfully destroyed!") - |> redirect(to: Routes.image_path(conn, :show, comment.image_id) <> "#comment_#{comment.id}") + |> redirect( + to: Routes.image_path(conn, :show, comment.image_id) <> "#comment_#{comment.id}" + ) {:error, _changeset} -> conn |> put_flash(:error, "Unable to destroy comment!") - |> redirect(to: Routes.image_path(conn, :show, comment.image_id) <> "#comment_#{comment.id}") + |> redirect( + to: Routes.image_path(conn, :show, comment.image_id) <> "#comment_#{comment.id}" + ) end end end diff --git a/lib/philomena_web/controllers/image/comment/hide_controller.ex b/lib/philomena_web/controllers/image/comment/hide_controller.ex index 20d83650..5f2aba09 100644 --- a/lib/philomena_web/controllers/image/comment/hide_controller.ex +++ b/lib/philomena_web/controllers/image/comment/hide_controller.ex @@ -19,12 +19,16 @@ defmodule PhilomenaWeb.Image.Comment.HideController do conn |> put_flash(:info, "Comment successfully hidden!") - |> redirect(to: Routes.image_path(conn, :show, comment.image_id) <> "#comment_#{comment.id}") + |> redirect( + to: Routes.image_path(conn, :show, comment.image_id) <> "#comment_#{comment.id}" + ) _error -> conn |> put_flash(:error, "Unable to hide comment!") - |> redirect(to: Routes.image_path(conn, :show, comment.image_id) <> "#comment_#{comment.id}") + |> redirect( + to: Routes.image_path(conn, :show, comment.image_id) <> "#comment_#{comment.id}" + ) end end @@ -37,12 +41,16 @@ defmodule PhilomenaWeb.Image.Comment.HideController do conn |> put_flash(:info, "Comment successfully unhidden!") - |> redirect(to: Routes.image_path(conn, :show, comment.image_id) <> "#comment_#{comment.id}") + |> redirect( + to: Routes.image_path(conn, :show, comment.image_id) <> "#comment_#{comment.id}" + ) {:error, _changeset} -> conn |> put_flash(:error, "Unable to unhide comment!") - |> redirect(to: Routes.image_path(conn, :show, comment.image_id) <> "#comment_#{comment.id}") + |> redirect( + to: Routes.image_path(conn, :show, comment.image_id) <> "#comment_#{comment.id}" + ) end end end diff --git a/lib/philomena_web/controllers/image/comment/history_controller.ex b/lib/philomena_web/controllers/image/comment/history_controller.ex index be1afe2d..d7ad3792 100644 --- a/lib/philomena_web/controllers/image/comment/history_controller.ex +++ b/lib/philomena_web/controllers/image/comment/history_controller.ex @@ -24,6 +24,9 @@ defmodule PhilomenaWeb.Image.Comment.HistoryController do |> Repo.all() |> Versions.load_data_and_associations(comment) - render(conn, "index.html", title: "Comment History for comment #{comment.id} on image #{image.id}", versions: versions) + render(conn, "index.html", + title: "Comment History for comment #{comment.id} on image #{image.id}", + versions: versions + ) end end diff --git a/lib/philomena_web/controllers/image/comment/report_controller.ex b/lib/philomena_web/controllers/image/comment/report_controller.ex index ee5e8927..6eb25d2b 100644 --- a/lib/philomena_web/controllers/image/comment/report_controller.ex +++ b/lib/philomena_web/controllers/image/comment/report_controller.ex @@ -12,20 +12,31 @@ defmodule PhilomenaWeb.Image.Comment.ReportController do plug PhilomenaWeb.CaptchaPlug when action in [:create] plug PhilomenaWeb.CanaryMapPlug, new: :show, create: :show - plug :load_and_authorize_resource, model: Image, id_name: "image_id", persisted: true, preload: [:tags] + + plug :load_and_authorize_resource, + model: Image, + id_name: "image_id", + persisted: true, + preload: [:tags] plug PhilomenaWeb.LoadCommentPlug def new(conn, _params) do comment = conn.assigns.comment action = Routes.image_comment_report_path(conn, :create, comment.image, comment) + changeset = %Report{reportable_type: "Comment", reportable_id: comment.id} |> Reports.change_report() conn |> put_view(ReportView) - |> render("new.html", title: "Reporting Comment", reportable: comment, changeset: changeset, action: action) + |> render("new.html", + title: "Reporting Comment", + reportable: comment, + changeset: changeset, + action: action + ) end def create(conn, params) do diff --git a/lib/philomena_web/controllers/image/comment_controller.ex b/lib/philomena_web/controllers/image/comment_controller.ex index e1000269..d67503cf 100644 --- a/lib/philomena_web/controllers/image/comment_controller.ex +++ b/lib/philomena_web/controllers/image/comment_controller.ex @@ -10,7 +10,11 @@ defmodule PhilomenaWeb.Image.CommentController do plug PhilomenaWeb.FilterBannedUsersPlug when action in [:create, :edit, :update] plug PhilomenaWeb.UserAttributionPlug when action in [:create] - plug PhilomenaWeb.CanaryMapPlug, create: :create_comment, edit: :create_comment, update: :create_comment + plug PhilomenaWeb.CanaryMapPlug, + create: :create_comment, + edit: :create_comment, + update: :create_comment + plug :load_resource, model: Image, id_name: "image_id", persisted: true plug :verify_authorized when action in [:show] @@ -18,7 +22,11 @@ defmodule PhilomenaWeb.Image.CommentController do plug PhilomenaWeb.LoadCommentPlug, [param: "id", show_hidden: true] when action in [:show] plug PhilomenaWeb.LoadCommentPlug, [param: "id"] when action in [:edit, :update] plug PhilomenaWeb.CanaryMapPlug, create: :create, edit: :edit, update: :edit - plug :authorize_resource, model: Comment, only: [:edit, :update], preload: [:image, user: [awards: :badge]] + + plug :authorize_resource, + model: Comment, + only: [:edit, :update], + preload: [:image, user: [awards: :badge]] def index(conn, %{"comment_id" => comment_id}) do page = CommentLoader.find_page(conn, conn.assigns.image, comment_id) @@ -31,15 +39,20 @@ defmodule PhilomenaWeb.Image.CommentController do rendered = Renderer.render_collection(comments.entries, conn) - comments = - %{comments | entries: Enum.zip(comments.entries, rendered)} + comments = %{comments | entries: Enum.zip(comments.entries, rendered)} render(conn, "index.html", layout: false, image: conn.assigns.image, comments: comments) end def show(conn, _params) do rendered = Renderer.render_one(conn.assigns.comment, conn) - render(conn, "show.html", layout: false, image: conn.assigns.image, comment: conn.assigns.comment, body: rendered) + + render(conn, "show.html", + layout: false, + image: conn.assigns.image, + comment: conn.assigns.comment, + body: rendered + ) end def create(conn, %{"comment" => comment_params}) do @@ -67,7 +80,11 @@ defmodule PhilomenaWeb.Image.CommentController do conn.assigns.comment |> Comments.change_comment() - render(conn, "edit.html", title: "Editing Comment", comment: conn.assigns.comment, changeset: changeset) + render(conn, "edit.html", + title: "Editing Comment", + comment: conn.assigns.comment, + changeset: changeset + ) end def update(conn, %{"comment" => comment_params}) do @@ -77,7 +94,9 @@ defmodule PhilomenaWeb.Image.CommentController do conn |> put_flash(:info, "Comment updated successfully.") - |> redirect(to: Routes.image_path(conn, :show, conn.assigns.image) <> "#comment_#{comment.id}") + |> redirect( + to: Routes.image_path(conn, :show, conn.assigns.image) <> "#comment_#{comment.id}" + ) {:error, :comment, changeset, _changes} -> render(conn, "edit.html", comment: conn.assigns.comment, changeset: changeset) @@ -86,16 +105,17 @@ defmodule PhilomenaWeb.Image.CommentController do defp verify_authorized(conn, _params) do image = conn.assigns.image + image = case is_nil(image.duplicate_id) do - true -> image + true -> image _false -> Images.get_image!(image.duplicate_id) end conn = assign(conn, :image, image) case Canada.Can.can?(conn.assigns.current_user, :show, image) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/image/description_controller.ex b/lib/philomena_web/controllers/image/description_controller.ex index 16ab545e..da52c1de 100644 --- a/lib/philomena_web/controllers/image/description_controller.ex +++ b/lib/philomena_web/controllers/image/description_controller.ex @@ -27,4 +27,4 @@ defmodule PhilomenaWeb.Image.DescriptionController do |> render("_form.html", layout: false, image: image, changeset: changeset) end end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/image/fave_controller.ex b/lib/philomena_web/controllers/image/fave_controller.ex index af707f73..3f6212cc 100644 --- a/lib/philomena_web/controllers/image/fave_controller.ex +++ b/lib/philomena_web/controllers/image/fave_controller.ex @@ -58,4 +58,4 @@ defmodule PhilomenaWeb.Image.FaveController do |> json(%{}) end end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/image/favorite_controller.ex b/lib/philomena_web/controllers/image/favorite_controller.ex index 6ce481b6..b0f67d1e 100644 --- a/lib/philomena_web/controllers/image/favorite_controller.ex +++ b/lib/philomena_web/controllers/image/favorite_controller.ex @@ -4,7 +4,12 @@ defmodule PhilomenaWeb.Image.FavoriteController do alias Philomena.Images.Image alias Philomena.Repo - plug :load_and_authorize_resource, model: Image, id_name: "image_id", persisted: true, preload: [faves: :user] + plug :load_and_authorize_resource, + model: Image, + id_name: "image_id", + persisted: true, + preload: [faves: :user] + plug :load_votes_if_authorized def index(conn, _params) do diff --git a/lib/philomena_web/controllers/image/file_controller.ex b/lib/philomena_web/controllers/image/file_controller.ex index 762b0120..f2f115d8 100644 --- a/lib/philomena_web/controllers/image/file_controller.ex +++ b/lib/philomena_web/controllers/image/file_controller.ex @@ -11,9 +11,10 @@ defmodule PhilomenaWeb.Image.FileController do def update(conn, %{"image" => image_params}) do case Images.update_file(conn.assigns.image, image_params) do {:ok, %{image: image}} -> - spawn fn -> + spawn(fn -> Images.repair_image(image) - end + end) + Images.reindex_image(image) conn diff --git a/lib/philomena_web/controllers/image/hide_controller.ex b/lib/philomena_web/controllers/image/hide_controller.ex index 642723e9..875ee129 100644 --- a/lib/philomena_web/controllers/image/hide_controller.ex +++ b/lib/philomena_web/controllers/image/hide_controller.ex @@ -56,4 +56,4 @@ defmodule PhilomenaWeb.Image.HideController do |> json(%{}) end end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/image/navigate_controller.ex b/lib/philomena_web/controllers/image/navigate_controller.ex index d47dd89f..1e41466f 100644 --- a/lib/philomena_web/controllers/image/navigate_controller.ex +++ b/lib/philomena_web/controllers/image/navigate_controller.ex @@ -51,9 +51,10 @@ defmodule PhilomenaWeb.Image.NavigateController do end defp match_all_if_blank(nil), do: "*" + defp match_all_if_blank(input) do case String.trim(input) == "" do - true -> "*" + true -> "*" false -> input end end diff --git a/lib/philomena_web/controllers/image/random_controller.ex b/lib/philomena_web/controllers/image/random_controller.ex index c0b2582b..31a062a2 100644 --- a/lib/philomena_web/controllers/image/random_controller.ex +++ b/lib/philomena_web/controllers/image/random_controller.ex @@ -26,6 +26,7 @@ defmodule PhilomenaWeb.Image.RandomController do query end + defp query(_user, _), do: %{match_all: %{}} defp random_image_id(query, filter) do diff --git a/lib/philomena_web/controllers/image/read_controller.ex b/lib/philomena_web/controllers/image/read_controller.ex index 40f39478..965b7fdc 100644 --- a/lib/philomena_web/controllers/image/read_controller.ex +++ b/lib/philomena_web/controllers/image/read_controller.ex @@ -15,4 +15,4 @@ defmodule PhilomenaWeb.Image.ReadController do send_resp(conn, :ok, "") end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/image/related_controller.ex b/lib/philomena_web/controllers/image/related_controller.ex index 21b42237..b7a9ba60 100644 --- a/lib/philomena_web/controllers/image/related_controller.ex +++ b/lib/philomena_web/controllers/image/related_controller.ex @@ -6,7 +6,12 @@ defmodule PhilomenaWeb.Image.RelatedController do alias Philomena.Images.Image plug PhilomenaWeb.CanaryMapPlug, index: :show - plug :load_and_authorize_resource, model: Image, id_name: "image_id", persisted: true, preload: [:tags, :faves] + + plug :load_and_authorize_resource, + model: Image, + id_name: "image_id", + persisted: true, + preload: [:tags, :faves] def index(conn, _params) do image = conn.assigns.image @@ -14,7 +19,7 @@ defmodule PhilomenaWeb.Image.RelatedController do tags_to_match = image.tags - |> Enum.reject(& &1.category == "rating") + |> Enum.reject(&(&1.category == "rating")) |> Enum.sort_by(& &1.images_count) |> Enum.take(10) |> Enum.map(& &1.id) @@ -34,17 +39,16 @@ defmodule PhilomenaWeb.Image.RelatedController do |> Enum.take(11) |> Enum.map(&%{term: %{favourited_by_user_ids: &1.user_id}}) - 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}} - } + 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}} } + } {images, _tags} = ImageLoader.query( @@ -56,6 +60,11 @@ defmodule PhilomenaWeb.Image.RelatedController do interactions = Interactions.user_interactions(images, user) - render(conn, "index.html", title: "##{image.id} - Related Images", layout_class: "wide", images: images, interactions: interactions) + render(conn, "index.html", + title: "##{image.id} - Related Images", + layout_class: "wide", + images: images, + interactions: interactions + ) end end diff --git a/lib/philomena_web/controllers/image/repair_controller.ex b/lib/philomena_web/controllers/image/repair_controller.ex index 2cd80bb6..3dc43888 100644 --- a/lib/philomena_web/controllers/image/repair_controller.ex +++ b/lib/philomena_web/controllers/image/repair_controller.ex @@ -9,9 +9,9 @@ defmodule PhilomenaWeb.Image.RepairController do plug :verify_not_deleted def create(conn, _params) do - spawn fn -> + spawn(fn -> Images.repair_image(conn.assigns.image) - end + end) conn |> put_flash(:info, "Repair job started.") diff --git a/lib/philomena_web/controllers/image/report_controller.ex b/lib/philomena_web/controllers/image/report_controller.ex index e6b99342..36d45578 100644 --- a/lib/philomena_web/controllers/image/report_controller.ex +++ b/lib/philomena_web/controllers/image/report_controller.ex @@ -11,18 +11,29 @@ defmodule PhilomenaWeb.Image.ReportController do plug PhilomenaWeb.UserAttributionPlug plug PhilomenaWeb.CaptchaPlug when action in [:create] plug PhilomenaWeb.CanaryMapPlug, new: :show, create: :show - plug :load_and_authorize_resource, model: Image, id_name: "image_id", persisted: true, preload: [:tags] + + plug :load_and_authorize_resource, + model: Image, + id_name: "image_id", + persisted: true, + preload: [:tags] def new(conn, _params) do image = conn.assigns.image action = Routes.image_report_path(conn, :create, image) + changeset = %Report{reportable_type: "Image", reportable_id: image.id} |> Reports.change_report() conn |> put_view(ReportView) - |> render("new.html", title: "Reporting Image", reportable: image, changeset: changeset, action: action) + |> render("new.html", + title: "Reporting Image", + reportable: image, + changeset: changeset, + action: action + ) end def create(conn, params) do diff --git a/lib/philomena_web/controllers/image/reporting_controller.ex b/lib/philomena_web/controllers/image/reporting_controller.ex index f968c361..a0c6ba54 100644 --- a/lib/philomena_web/controllers/image/reporting_controller.ex +++ b/lib/philomena_web/controllers/image/reporting_controller.ex @@ -7,7 +7,11 @@ defmodule PhilomenaWeb.Image.ReportingController do alias Philomena.Repo import Ecto.Query - plug :load_and_authorize_resource, model: Image, id_name: "image_id", persisted: true, preload: [:tags] + plug :load_and_authorize_resource, + model: Image, + id_name: "image_id", + persisted: true, + preload: [:tags] def show(conn, _params) do image = conn.assigns.image @@ -22,6 +26,11 @@ defmodule PhilomenaWeb.Image.ReportingController do %DuplicateReport{} |> DuplicateReports.change_duplicate_report() - render(conn, "show.html", layout: false, image: image, dupe_reports: dupe_reports, changeset: changeset) + render(conn, "show.html", + layout: false, + image: image, + dupe_reports: dupe_reports, + changeset: changeset + ) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/image/scrape_controller.ex b/lib/philomena_web/controllers/image/scrape_controller.ex index 7c5dfff1..a46c8733 100644 --- a/lib/philomena_web/controllers/image/scrape_controller.ex +++ b/lib/philomena_web/controllers/image/scrape_controller.ex @@ -14,4 +14,4 @@ defmodule PhilomenaWeb.Image.ScrapeController do conn |> json(result) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/image/source_change_controller.ex b/lib/philomena_web/controllers/image/source_change_controller.ex index 744a0764..bfa16d7d 100644 --- a/lib/philomena_web/controllers/image/source_change_controller.ex +++ b/lib/philomena_web/controllers/image/source_change_controller.ex @@ -18,7 +18,11 @@ defmodule PhilomenaWeb.Image.SourceChangeController do |> preload([:user, image: [:user, :tags]]) |> order_by(desc: :created_at) |> Repo.paginate(conn.assigns.scrivener) - - render(conn, "index.html", title: "Source Changes on Image #{image.id}", image: image, source_changes: source_changes) + + render(conn, "index.html", + title: "Source Changes on Image #{image.id}", + image: image, + source_changes: source_changes + ) end end diff --git a/lib/philomena_web/controllers/image/source_controller.ex b/lib/philomena_web/controllers/image/source_controller.ex index 560b06e4..37216a24 100644 --- a/lib/philomena_web/controllers/image/source_controller.ex +++ b/lib/philomena_web/controllers/image/source_controller.ex @@ -21,8 +21,7 @@ defmodule PhilomenaWeb.Image.SourceController do case Images.update_source(image, attributes, image_params) do {:ok, %{image: image}} -> - changeset = - Images.change_image(image) + changeset = Images.change_image(image) source_change_count = SourceChange @@ -35,12 +34,22 @@ defmodule PhilomenaWeb.Image.SourceController do conn |> put_view(PhilomenaWeb.ImageView) - |> render("_source.html", layout: false, source_change_count: source_change_count, image: image, changeset: changeset) + |> render("_source.html", + layout: false, + source_change_count: source_change_count, + image: image, + changeset: changeset + ) {:error, :image, changeset, _} -> conn |> put_view(PhilomenaWeb.ImageView) - |> render("_source.html", layout: false, source_change_count: 0, image: image, changeset: changeset) + |> render("_source.html", + layout: false, + source_change_count: 0, + image: image, + changeset: changeset + ) end end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/image/subscription_controller.ex b/lib/philomena_web/controllers/image/subscription_controller.ex index d7f077b8..aaf98f66 100644 --- a/lib/philomena_web/controllers/image/subscription_controller.ex +++ b/lib/philomena_web/controllers/image/subscription_controller.ex @@ -32,4 +32,4 @@ defmodule PhilomenaWeb.Image.SubscriptionController do render(conn, "_error.html", layout: false) end end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/image/tag_change_controller.ex b/lib/philomena_web/controllers/image/tag_change_controller.ex index ee6c6847..f0f10142 100644 --- a/lib/philomena_web/controllers/image/tag_change_controller.ex +++ b/lib/philomena_web/controllers/image/tag_change_controller.ex @@ -19,14 +19,20 @@ defmodule PhilomenaWeb.Image.TagChangeController do |> preload([:tag, :user, image: [:user, :tags]]) |> order_by(desc: :created_at) |> Repo.paginate(conn.assigns.scrivener) - - render(conn, "index.html", title: "Tag Changes on Image #{image.id}", image: image, tag_changes: tag_changes) + + render(conn, "index.html", + title: "Tag Changes on Image #{image.id}", + image: image, + tag_changes: tag_changes + ) end defp added_filter(query, %{"added" => "1"}), do: where(query, added: true) + defp added_filter(query, %{"added" => "0"}), do: where(query, added: false) + defp added_filter(query, _params), do: query end diff --git a/lib/philomena_web/controllers/image/tag_controller.ex b/lib/philomena_web/controllers/image/tag_controller.ex index 052d2416..386ce463 100644 --- a/lib/philomena_web/controllers/image/tag_controller.ex +++ b/lib/philomena_web/controllers/image/tag_controller.ex @@ -39,17 +39,26 @@ defmodule PhilomenaWeb.Image.TagController do image |> Repo.preload(:tags, force: true) - changeset = - Images.change_image(image) + changeset = Images.change_image(image) conn |> put_view(PhilomenaWeb.ImageView) - |> render("_tags.html", layout: false, tag_change_count: tag_change_count, image: image, changeset: changeset) + |> render("_tags.html", + layout: false, + tag_change_count: tag_change_count, + image: image, + changeset: changeset + ) {:error, :image, changeset, _} -> conn |> put_view(PhilomenaWeb.ImageView) - |> render("_tags.html", layout: false, tag_change_count: 0, image: image, changeset: changeset) + |> render("_tags.html", + layout: false, + tag_change_count: 0, + image: image, + changeset: changeset + ) end end end diff --git a/lib/philomena_web/controllers/image/uploader_controller.ex b/lib/philomena_web/controllers/image/uploader_controller.ex index 20215fd5..3d9c8f39 100644 --- a/lib/philomena_web/controllers/image/uploader_controller.ex +++ b/lib/philomena_web/controllers/image/uploader_controller.ex @@ -23,7 +23,7 @@ defmodule PhilomenaWeb.Image.UploaderController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :show, :ip_address) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/image/vote_controller.ex b/lib/philomena_web/controllers/image/vote_controller.ex index 6e465fd0..e13b9673 100644 --- a/lib/philomena_web/controllers/image/vote_controller.ex +++ b/lib/philomena_web/controllers/image/vote_controller.ex @@ -56,4 +56,4 @@ defmodule PhilomenaWeb.Image.VoteController do |> json(%{}) end end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/image_controller.ex b/lib/philomena_web/controllers/image_controller.ex index 74eb8282..a02a223f 100644 --- a/lib/philomena_web/controllers/image_controller.ex +++ b/lib/philomena_web/controllers/image_controller.ex @@ -4,7 +4,16 @@ defmodule PhilomenaWeb.ImageController do alias PhilomenaWeb.ImageLoader alias PhilomenaWeb.CommentLoader alias PhilomenaWeb.NotificationCountPlug - alias Philomena.{Images, Images.Image, Comments.Comment, Galleries.Gallery, Galleries.Interaction, Textile.Renderer} + + alias Philomena.{ + Images, + Images.Image, + Comments.Comment, + Galleries.Gallery, + Galleries.Interaction, + Textile.Renderer + } + # alias Philomena.Servers.ImageProcessor alias Philomena.UserStatistics alias Philomena.Interactions @@ -18,16 +27,23 @@ defmodule PhilomenaWeb.ImageController do plug PhilomenaWeb.FilterBannedUsersPlug when action in [:new, :create] plug PhilomenaWeb.UserAttributionPlug when action in [:create] plug PhilomenaWeb.CaptchaPlug when action in [:create] - plug PhilomenaWeb.ScraperPlug, [params_name: "image", params_key: "image"] when action in [:create] + + plug PhilomenaWeb.ScraperPlug, + [params_name: "image", params_key: "image"] when action in [:create] + plug PhilomenaWeb.AdvertPlug when action in [:show] def index(conn, _params) do {:ok, {images, _tags}} = ImageLoader.search_string(conn, "created_at.lte:3 minutes ago") - interactions = - Interactions.user_interactions(images, conn.assigns.current_user) + interactions = Interactions.user_interactions(images, conn.assigns.current_user) - render(conn, "index.html", title: "Images", layout_class: "layout--wide", images: images, interactions: interactions) + render(conn, "index.html", + title: "Images", + layout_class: "layout--wide", + images: images, + interactions: interactions + ) end def show(conn, %{"id" => _id}) do @@ -43,15 +59,13 @@ defmodule PhilomenaWeb.ImageController do rendered = Renderer.render_collection(comments.entries, conn) - comments = - %{comments | entries: Enum.zip(comments.entries, rendered)} + comments = %{comments | entries: Enum.zip(comments.entries, rendered)} description = %{body: image.description} |> Renderer.render_one(conn) - interactions = - Interactions.user_interactions([image], conn.assigns.current_user) + interactions = Interactions.user_interactions([image], conn.assigns.current_user) comment_changeset = %Comment{} @@ -61,8 +75,7 @@ defmodule PhilomenaWeb.ImageController do image |> Images.change_image() - watching = - Images.subscribed?(image, conn.assigns.current_user) + watching = Images.subscribed?(image, conn.assigns.current_user) {user_galleries, image_galleries} = image_and_user_galleries(image, conn.assigns.current_user) @@ -100,9 +113,10 @@ defmodule PhilomenaWeb.ImageController do case Images.create_image(attributes, image_params) do {:ok, %{image: image}} -> - spawn fn -> + spawn(fn -> Images.repair_image(image) - end + end) + # ImageProcessor.cast(image.id) Images.reindex_image(image) Tags.reindex_tags(image.added_tags) @@ -119,11 +133,14 @@ defmodule PhilomenaWeb.ImageController do end defp image_and_user_galleries(_image, nil), do: {[], []} + defp image_and_user_galleries(image, user) do image_galleries = Gallery |> where(creator_id: ^user.id) - |> join(:inner, [g], gi in Interaction, on: g.id == gi.gallery_id and gi.image_id == ^image.id) + |> join(:inner, [g], gi in Interaction, + on: g.id == gi.gallery_id and gi.image_id == ^image.id + ) |> order_by(desc: :created_at) |> Repo.all() @@ -145,8 +162,16 @@ defmodule PhilomenaWeb.ImageController do {image, tag_changes, source_changes} = Image |> where(id: ^id) - |> join(:inner_lateral, [i], _ in fragment("SELECT COUNT(*) FROM tag_changes t WHERE t.image_id = ?", i.id)) - |> join(:inner_lateral, [i, _], _ in fragment("SELECT COUNT(*) FROM source_changes s WHERE s.image_id = ?", i.id)) + |> join( + :inner_lateral, + [i], + _ in fragment("SELECT COUNT(*) FROM tag_changes t WHERE t.image_id = ?", i.id) + ) + |> join( + :inner_lateral, + [i, _], + _ in fragment("SELECT COUNT(*) FROM source_changes s WHERE s.image_id = ?", i.id) + ) |> preload([:tags, :deleter, user: [awards: :badge]]) |> select([i, t, s], {i, t.count, s.count}) |> Repo.one() @@ -162,9 +187,13 @@ defmodule PhilomenaWeb.ImageController do is_nil(image) -> PhilomenaWeb.NotFoundPlug.call(conn) - not is_nil(image.duplicate_id) and not Canada.Can.can?(conn.assigns.current_user, :show, image) -> + not is_nil(image.duplicate_id) and + not Canada.Can.can?(conn.assigns.current_user, :show, image) -> conn - |> put_flash(:info, "The image you were looking for has been marked a duplicate of the image below") + |> put_flash( + :info, + "The image you were looking for has been marked a duplicate of the image below" + ) |> redirect(to: Routes.image_path(conn, :show, image.duplicate_id)) |> Plug.Conn.halt() diff --git a/lib/philomena_web/controllers/ip_profile/source_change_controller.ex b/lib/philomena_web/controllers/ip_profile/source_change_controller.ex index bfbcb90b..c470d1b1 100644 --- a/lib/philomena_web/controllers/ip_profile/source_change_controller.ex +++ b/lib/philomena_web/controllers/ip_profile/source_change_controller.ex @@ -17,12 +17,16 @@ defmodule PhilomenaWeb.IpProfile.SourceChangeController do |> preload([:user, image: [:user, :tags]]) |> Repo.paginate(conn.assigns.scrivener) - render(conn, "index.html", title: "Source Changes for IP `#{ip}'", ip: ip, source_changes: source_changes) + render(conn, "index.html", + title: "Source Changes for IP `#{ip}'", + ip: ip, + source_changes: source_changes + ) end defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :show, :ip_address) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/ip_profile/tag_change_controller.ex b/lib/philomena_web/controllers/ip_profile/tag_change_controller.ex index 7dd912c6..3899cf24 100644 --- a/lib/philomena_web/controllers/ip_profile/tag_change_controller.ex +++ b/lib/philomena_web/controllers/ip_profile/tag_change_controller.ex @@ -18,19 +18,25 @@ defmodule PhilomenaWeb.IpProfile.TagChangeController do |> order_by(desc: :created_at) |> Repo.paginate(conn.assigns.scrivener) - render(conn, "index.html", title: "Tag Changes for IP `#{ip}'", ip: ip, tag_changes: tag_changes) + render(conn, "index.html", + title: "Tag Changes for IP `#{ip}'", + ip: ip, + tag_changes: tag_changes + ) end defp added_filter(query, %{"added" => "1"}), do: where(query, added: true) + defp added_filter(query, %{"added" => "0"}), do: where(query, added: false) + defp added_filter(query, _params), do: query defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :show, :ip_address) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/ip_profile_controller.ex b/lib/philomena_web/controllers/ip_profile_controller.ex index e93e7d48..4d9ded0c 100644 --- a/lib/philomena_web/controllers/ip_profile_controller.ex +++ b/lib/philomena_web/controllers/ip_profile_controller.ex @@ -23,13 +23,18 @@ defmodule PhilomenaWeb.IpProfileController do |> where([s], fragment("? >>= ?", s.specification, ^ip)) |> Repo.all() - render(conn, "show.html", title: "#{ip}'s IP profile", ip: ip, user_ips: user_ips, subnet_bans: subnet_bans) + render(conn, "show.html", + title: "#{ip}'s IP profile", + ip: ip, + user_ips: user_ips, + subnet_bans: subnet_bans + ) end defp authorize_ip(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :show, :ip_address) do false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) - true -> conn + true -> conn end end end diff --git a/lib/philomena_web/controllers/notification/unread_controller.ex b/lib/philomena_web/controllers/notification/unread_controller.ex index ef091dd5..8da063d7 100644 --- a/lib/philomena_web/controllers/notification/unread_controller.ex +++ b/lib/philomena_web/controllers/notification/unread_controller.ex @@ -7,4 +7,4 @@ defmodule PhilomenaWeb.Notification.UnreadController do conversations: conn.assigns.conversation_count }) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/notification_controller.ex b/lib/philomena_web/controllers/notification_controller.ex index 3eaf4e26..170d504b 100644 --- a/lib/philomena_web/controllers/notification_controller.ex +++ b/lib/philomena_web/controllers/notification_controller.ex @@ -11,7 +11,8 @@ defmodule PhilomenaWeb.NotificationController do notifications = from n in Notification, - join: un in UnreadNotification, on: un.notification_id == n.id, + join: un in UnreadNotification, + on: un.notification_id == n.id, where: un.user_id == ^user.id notifications = @@ -26,8 +27,7 @@ defmodule PhilomenaWeb.NotificationController do actor_child: [actor_child_id: :actor_child_type] ) - notifications = - %{notifications | entries: entries} + notifications = %{notifications | entries: entries} render(conn, "index.html", title: "Notification Area", notifications: notifications) end diff --git a/lib/philomena_web/controllers/page/history_controller.ex b/lib/philomena_web/controllers/page/history_controller.ex index c0e25665..df6cd447 100644 --- a/lib/philomena_web/controllers/page/history_controller.ex +++ b/lib/philomena_web/controllers/page/history_controller.ex @@ -19,7 +19,11 @@ defmodule PhilomenaWeb.Page.HistoryController do |> Repo.all() |> generate_differences(page.body) - render(conn, "index.html", title: "Revision History for Page `#{page.title}'", layout_class: "layout--wide", versions: versions) + render(conn, "index.html", + title: "Revision History for Page `#{page.title}'", + layout_class: "layout--wide", + versions: versions + ) end defp generate_differences(pages, current_body) do diff --git a/lib/philomena_web/controllers/page_controller.ex b/lib/philomena_web/controllers/page_controller.ex index 27dacf69..8fa86eb7 100644 --- a/lib/philomena_web/controllers/page_controller.ex +++ b/lib/philomena_web/controllers/page_controller.ex @@ -37,7 +37,11 @@ defmodule PhilomenaWeb.PageController do end def update(conn, %{"static_page" => static_page_params}) do - case StaticPages.update_static_page(conn.assigns.static_page, conn.assigns.current_user, static_page_params) do + case StaticPages.update_static_page( + conn.assigns.static_page, + conn.assigns.current_user, + static_page_params + ) do {:ok, %{static_page: static_page}} -> conn |> put_flash(:info, "Static page successfully updated.") diff --git a/lib/philomena_web/controllers/post/preview_controller.ex b/lib/philomena_web/controllers/post/preview_controller.ex index 307ff1e7..98d68968 100644 --- a/lib/philomena_web/controllers/post/preview_controller.ex +++ b/lib/philomena_web/controllers/post/preview_controller.ex @@ -17,7 +17,8 @@ defmodule PhilomenaWeb.Post.PreviewController do end defp preload_awards(nil), do: nil + defp preload_awards(user) do Repo.preload(user, awards: :badge) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/post_controller.ex b/lib/philomena_web/controllers/post_controller.ex index cb7bc2f7..b613317d 100644 --- a/lib/philomena_web/controllers/post_controller.ex +++ b/lib/philomena_web/controllers/post_controller.ex @@ -33,25 +33,26 @@ defmodule PhilomenaWeb.PostController do Post |> preload([:deleted_by, topic: :forum, user: [awards: :badge]]) ) - rendered = - Renderer.render_collection(posts.entries, conn) + rendered = Renderer.render_collection(posts.entries, conn) - posts = - %{posts | entries: Enum.zip(rendered, posts.entries)} + posts = %{posts | entries: Enum.zip(rendered, posts.entries)} render(conn, "index.html", title: "Posts", posts: posts) end + defp render_index({:error, msg}, conn, _user) do render(conn, "index.html", title: "Posts", error: msg, posts: []) end defp filters(%{role: role}) when role in ["moderator", "admin"], do: [] + defp filters(%{role: "assistant"}) do [ %{terms: %{access_level: ["normal", "assistant"]}}, %{term: %{deleted: false}} ] end + defp filters(_user) do [ %{term: %{access_level: "normal"}}, diff --git a/lib/philomena_web/controllers/profile/alias_controller.ex b/lib/philomena_web/controllers/profile/alias_controller.ex index 372754ed..18cd7f4f 100644 --- a/lib/philomena_web/controllers/profile/alias_controller.ex +++ b/lib/philomena_web/controllers/profile/alias_controller.ex @@ -8,7 +8,12 @@ defmodule PhilomenaWeb.Profile.AliasController do import Ecto.Query plug PhilomenaWeb.CanaryMapPlug, index: :show_details - plug :load_and_authorize_resource, model: User, id_field: "slug", id_name: "profile_id", persisted: true + + plug :load_and_authorize_resource, + model: User, + id_field: "slug", + id_name: "profile_id", + persisted: true def index(conn, _params) do user = conn.assigns.user @@ -37,14 +42,11 @@ defmodule PhilomenaWeb.Profile.AliasController do |> Repo.all() |> Map.new(&{&1.id, &1}) - both_matches = - Map.take(ip_matches, Map.keys(fp_matches)) + both_matches = Map.take(ip_matches, Map.keys(fp_matches)) - ip_matches = - Map.drop(ip_matches, Map.keys(both_matches)) + ip_matches = Map.drop(ip_matches, Map.keys(both_matches)) - fp_matches = - Map.drop(fp_matches, Map.keys(both_matches)) + fp_matches = Map.drop(fp_matches, Map.keys(both_matches)) both_matches = Map.values(both_matches) ip_matches = Map.values(ip_matches) diff --git a/lib/philomena_web/controllers/profile/award_controller.ex b/lib/philomena_web/controllers/profile/award_controller.ex index bbdff47e..07df9819 100644 --- a/lib/philomena_web/controllers/profile/award_controller.ex +++ b/lib/philomena_web/controllers/profile/award_controller.ex @@ -57,7 +57,7 @@ defmodule PhilomenaWeb.Profile.AwardController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :create, Award) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/profile/commission/item_controller.ex b/lib/philomena_web/controllers/profile/commission/item_controller.ex index fff25fbf..d7705638 100644 --- a/lib/philomena_web/controllers/profile/commission/item_controller.ex +++ b/lib/philomena_web/controllers/profile/commission/item_controller.ex @@ -7,7 +7,17 @@ defmodule PhilomenaWeb.Profile.Commission.ItemController do alias Philomena.Repo plug PhilomenaWeb.FilterBannedUsersPlug - plug :load_resource, model: User, id_name: "profile_id", id_field: "slug", preload: [:verified_links, commission: [sheet_image: :tags, user: [awards: :badge], items: [example_image: :tags]]], persisted: true + + plug :load_resource, + model: User, + id_name: "profile_id", + id_field: "slug", + preload: [ + :verified_links, + commission: [sheet_image: :tags, user: [awards: :badge], items: [example_image: :tags]] + ], + persisted: true + plug :ensure_commission plug :ensure_correct_user @@ -16,7 +26,13 @@ defmodule PhilomenaWeb.Profile.Commission.ItemController do commission = user.commission changeset = Commissions.change_item(%Item{}) - render(conn, "new.html", title: "New Commission Item", user: user, commission: commission, changeset: changeset) + + render(conn, "new.html", + title: "New Commission Item", + user: user, + commission: commission, + changeset: changeset + ) end def create(conn, %{"item" => item_params}) do @@ -40,7 +56,14 @@ defmodule PhilomenaWeb.Profile.Commission.ItemController do item = Repo.get_by!(Item, commission_id: commission.id, id: id) changeset = Commissions.change_item(item) - render(conn, "edit.html", title: "Editing Commission Item", user: user, commission: commission, item: item, changeset: changeset) + + render(conn, "edit.html", + title: "Editing Commission Item", + user: user, + commission: commission, + item: item, + changeset: changeset + ) end def update(conn, %{"id" => id, "item" => item_params}) do @@ -55,7 +78,12 @@ defmodule PhilomenaWeb.Profile.Commission.ItemController do |> redirect(to: Routes.profile_commission_path(conn, :show, conn.assigns.user)) {:error, changeset} -> - render(conn, "edit.html", user: user, commission: commission, item: item, changeset: changeset) + render(conn, "edit.html", + user: user, + commission: commission, + item: item, + changeset: changeset + ) end end @@ -73,7 +101,7 @@ defmodule PhilomenaWeb.Profile.Commission.ItemController do defp ensure_commission(conn, _opts) do case is_nil(conn.assigns.user.commission) do - true -> PhilomenaWeb.NotFoundPlug.call(conn) + true -> PhilomenaWeb.NotFoundPlug.call(conn) false -> conn end end @@ -83,7 +111,7 @@ defmodule PhilomenaWeb.Profile.Commission.ItemController do case conn.assigns.current_user do %{id: ^user_id} -> conn - _other -> PhilomenaWeb.NotAuthorizedPlug.call(conn) + _other -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end end diff --git a/lib/philomena_web/controllers/profile/commission/report_controller.ex b/lib/philomena_web/controllers/profile/commission/report_controller.ex index 6b530977..3b41e621 100644 --- a/lib/philomena_web/controllers/profile/commission/report_controller.ex +++ b/lib/philomena_web/controllers/profile/commission/report_controller.ex @@ -11,20 +11,36 @@ defmodule PhilomenaWeb.Profile.Commission.ReportController do plug PhilomenaWeb.UserAttributionPlug plug PhilomenaWeb.CaptchaPlug when action in [:create] plug PhilomenaWeb.CanaryMapPlug, new: :show, create: :show - plug :load_resource, model: User, id_name: "profile_id", id_field: "slug", preload: [:verified_links, commission: [sheet_image: :tags, user: [awards: :badge], items: [example_image: :tags]]], persisted: true + + plug :load_resource, + model: User, + id_name: "profile_id", + id_field: "slug", + preload: [ + :verified_links, + commission: [sheet_image: :tags, user: [awards: :badge], items: [example_image: :tags]] + ], + persisted: true + plug :ensure_commission def new(conn, _params) do user = conn.assigns.user commission = conn.assigns.user.commission action = Routes.profile_commission_report_path(conn, :create, user) + changeset = %Report{reportable_type: "Commission", reportable_id: commission.id} |> Reports.change_report() conn |> put_view(ReportView) - |> render("new.html", title: "Reporting Commission", reportable: commission, changeset: changeset, action: action) + |> render("new.html", + title: "Reporting Commission", + reportable: commission, + changeset: changeset, + action: action + ) end def create(conn, params) do @@ -37,7 +53,7 @@ defmodule PhilomenaWeb.Profile.Commission.ReportController do defp ensure_commission(conn, _opts) do case is_nil(conn.assigns.user.commission) do - true -> PhilomenaWeb.NotFoundPlug.call(conn) + true -> PhilomenaWeb.NotFoundPlug.call(conn) false -> conn end end diff --git a/lib/philomena_web/controllers/profile/commission_controller.ex b/lib/philomena_web/controllers/profile/commission_controller.ex index ede16ef6..9effeb31 100644 --- a/lib/philomena_web/controllers/profile/commission_controller.ex +++ b/lib/philomena_web/controllers/profile/commission_controller.ex @@ -7,7 +7,17 @@ defmodule PhilomenaWeb.Profile.CommissionController do alias Philomena.Users.User plug PhilomenaWeb.FilterBannedUsersPlug when action in [:new, :create, :edit, :update, :delete] - plug :load_resource, model: User, id_name: "profile_id", id_field: "slug", preload: [:verified_links, commission: [sheet_image: :tags, user: [awards: :badge], items: [example_image: :tags]]], persisted: true + + plug :load_resource, + model: User, + id_name: "profile_id", + id_field: "slug", + preload: [ + :verified_links, + commission: [sheet_image: :tags, user: [awards: :badge], items: [example_image: :tags]] + ], + persisted: true + plug :ensure_commission when action in [:show, :edit, :update, :delete] plug :ensure_no_commission when action in [:new, :create] plug :ensure_correct_user when action in [:new, :create, :edit, :update, :delete] @@ -18,11 +28,11 @@ defmodule PhilomenaWeb.Profile.CommissionController do items = commission.items - |> Enum.sort(&Decimal.cmp(&1.base_price, &2.base_price) != :gt) + |> Enum.sort(&(Decimal.cmp(&1.base_price, &2.base_price) != :gt)) item_descriptions = items - |> Enum.map(&%{body: &1.description }) + |> Enum.map(&%{body: &1.description}) |> Renderer.render_collection(conn) item_add_ons = @@ -41,17 +51,22 @@ defmodule PhilomenaWeb.Profile.CommissionController do conn ) - rendered = - %{ - information: information, - contact: contact, - will_create: will_create, - will_not_create: will_not_create - } + rendered = %{ + information: information, + contact: contact, + will_create: will_create, + will_not_create: will_not_create + } items = Enum.zip([item_descriptions, item_add_ons, items]) - render(conn, "show.html", title: "Showing Commission", rendered: rendered, commission: commission, items: items, layout_class: "layout--wide") + render(conn, "show.html", + title: "Showing Commission", + rendered: rendered, + commission: commission, + items: items, + layout_class: "layout--wide" + ) end def new(conn, _params) do @@ -104,7 +119,7 @@ defmodule PhilomenaWeb.Profile.CommissionController do defp ensure_commission(conn, _opts) do case is_nil(conn.assigns.user.commission) do - true -> PhilomenaWeb.NotFoundPlug.call(conn) + true -> PhilomenaWeb.NotFoundPlug.call(conn) false -> conn end end @@ -112,22 +127,24 @@ defmodule PhilomenaWeb.Profile.CommissionController do defp ensure_no_commission(conn, _opts) do case is_nil(conn.assigns.user.commission) do false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) - true -> conn + true -> conn end end - + defp ensure_correct_user(conn, _opts) do user_id = conn.assigns.user.id case conn.assigns.current_user do %{id: ^user_id} -> conn - _other -> PhilomenaWeb.NotAuthorizedPlug.call(conn) + _other -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end defp ensure_links_verified(conn, _opts) do case Enum.any?(conn.assigns.user.verified_links) do - true -> conn + true -> + conn + false -> conn |> put_flash(:error, "You must have a verified user link to create a commission listing.") diff --git a/lib/philomena_web/controllers/profile/description_controller.ex b/lib/philomena_web/controllers/profile/description_controller.ex index 816968ff..1b2660e9 100644 --- a/lib/philomena_web/controllers/profile/description_controller.ex +++ b/lib/philomena_web/controllers/profile/description_controller.ex @@ -10,7 +10,12 @@ defmodule PhilomenaWeb.Profile.DescriptionController do def edit(conn, _params) do changeset = Users.change_user(conn.assigns.user) - render(conn, "edit.html", title: "Editing Profile Description", changeset: changeset, user: conn.assigns.user) + + render(conn, "edit.html", + title: "Editing Profile Description", + changeset: changeset, + user: conn.assigns.user + ) end def update(conn, %{"user" => user_params}) do diff --git a/lib/philomena_web/controllers/profile/detail_controller.ex b/lib/philomena_web/controllers/profile/detail_controller.ex index 383368d0..40989f9f 100644 --- a/lib/philomena_web/controllers/profile/detail_controller.ex +++ b/lib/philomena_web/controllers/profile/detail_controller.ex @@ -10,7 +10,12 @@ defmodule PhilomenaWeb.Profile.DetailController do import Ecto.Query plug PhilomenaWeb.CanaryMapPlug, index: :show_details - plug :load_and_authorize_resource, model: User, id_field: "slug", id_name: "profile_id", persisted: true + + plug :load_and_authorize_resource, + model: User, + id_field: "slug", + id_name: "profile_id", + persisted: true def index(conn, _params) do user = conn.assigns.user @@ -34,6 +39,10 @@ defmodule PhilomenaWeb.Profile.DetailController do |> order_by(desc: :id) |> Repo.all() - render(conn, "index.html", title: "Profile Details for User `#{user.name}'", mod_notes: mod_notes, name_changes: name_changes) + render(conn, "index.html", + title: "Profile Details for User `#{user.name}'", + mod_notes: mod_notes, + name_changes: name_changes + ) end end diff --git a/lib/philomena_web/controllers/profile/fp_history_controller.ex b/lib/philomena_web/controllers/profile/fp_history_controller.ex index cabb6492..c59f4f1c 100644 --- a/lib/philomena_web/controllers/profile/fp_history_controller.ex +++ b/lib/philomena_web/controllers/profile/fp_history_controller.ex @@ -7,7 +7,12 @@ defmodule PhilomenaWeb.Profile.FpHistoryController do import Ecto.Query plug PhilomenaWeb.CanaryMapPlug, index: :show_details - plug :load_and_authorize_resource, model: User, id_field: "slug", id_name: "profile_id", persisted: true + + plug :load_and_authorize_resource, + model: User, + id_field: "slug", + id_name: "profile_id", + persisted: true def index(conn, _params) do user = conn.assigns.user @@ -32,6 +37,10 @@ defmodule PhilomenaWeb.Profile.FpHistoryController do |> Repo.all() |> Enum.group_by(& &1.fingerprint) - render(conn, "index.html", title: "FP History for `#{user.name}'", user_fps: user_fps, other_users: other_users) + render(conn, "index.html", + title: "FP History for `#{user.name}'", + user_fps: user_fps, + other_users: other_users + ) end end diff --git a/lib/philomena_web/controllers/profile/ip_history_controller.ex b/lib/philomena_web/controllers/profile/ip_history_controller.ex index 45facf9e..053e2b9a 100644 --- a/lib/philomena_web/controllers/profile/ip_history_controller.ex +++ b/lib/philomena_web/controllers/profile/ip_history_controller.ex @@ -7,7 +7,12 @@ defmodule PhilomenaWeb.Profile.IpHistoryController do import Ecto.Query plug PhilomenaWeb.CanaryMapPlug, index: :show_details - plug :load_and_authorize_resource, model: User, id_field: "slug", id_name: "profile_id", persisted: true + + plug :load_and_authorize_resource, + model: User, + id_field: "slug", + id_name: "profile_id", + persisted: true def index(conn, _params) do user = conn.assigns.user @@ -32,6 +37,10 @@ defmodule PhilomenaWeb.Profile.IpHistoryController do |> Repo.all() |> Enum.group_by(& &1.ip) - render(conn, "index.html", title: "IP History for `#{user.name}'", user_ips: user_ips, other_users: other_users) + render(conn, "index.html", + title: "IP History for `#{user.name}'", + user_ips: user_ips, + other_users: other_users + ) end end diff --git a/lib/philomena_web/controllers/profile/report_controller.ex b/lib/philomena_web/controllers/profile/report_controller.ex index c909c2e2..d594930b 100644 --- a/lib/philomena_web/controllers/profile/report_controller.ex +++ b/lib/philomena_web/controllers/profile/report_controller.ex @@ -11,18 +11,29 @@ defmodule PhilomenaWeb.Profile.ReportController do plug PhilomenaWeb.UserAttributionPlug plug PhilomenaWeb.CaptchaPlug when action in [:create] plug PhilomenaWeb.CanaryMapPlug, new: :show, create: :show - plug :load_and_authorize_resource, model: User, id_name: "profile_id", id_field: "slug", persisted: true + + plug :load_and_authorize_resource, + model: User, + id_name: "profile_id", + id_field: "slug", + persisted: true def new(conn, _params) do user = conn.assigns.user action = Routes.profile_report_path(conn, :create, user) + changeset = %Report{reportable_type: "User", reportable_id: user.id} |> Reports.change_report() conn |> put_view(ReportView) - |> render("new.html", title: "Reporting User", reportable: user, changeset: changeset, action: action) + |> render("new.html", + title: "Reporting User", + reportable: user, + changeset: changeset, + action: action + ) end def create(conn, params) do diff --git a/lib/philomena_web/controllers/profile/scratchpad_controller.ex b/lib/philomena_web/controllers/profile/scratchpad_controller.ex index df728548..117fb3b6 100644 --- a/lib/philomena_web/controllers/profile/scratchpad_controller.ex +++ b/lib/philomena_web/controllers/profile/scratchpad_controller.ex @@ -10,7 +10,12 @@ defmodule PhilomenaWeb.Profile.ScratchpadController do def edit(conn, _params) do changeset = Users.change_user(conn.assigns.user) - render(conn, "edit.html", title: "Editing Moderation Scratchpad", changeset: changeset, user: conn.assigns.user) + + render(conn, "edit.html", + title: "Editing Moderation Scratchpad", + changeset: changeset, + user: conn.assigns.user + ) end def update(conn, %{"user" => user_params}) do diff --git a/lib/philomena_web/controllers/profile/source_change_controller.ex b/lib/philomena_web/controllers/profile/source_change_controller.ex index 1346cb64..521b8616 100644 --- a/lib/philomena_web/controllers/profile/source_change_controller.ex +++ b/lib/philomena_web/controllers/profile/source_change_controller.ex @@ -8,7 +8,12 @@ defmodule PhilomenaWeb.Profile.SourceChangeController do import Ecto.Query plug PhilomenaWeb.CanaryMapPlug, index: :show - plug :load_and_authorize_resource, model: User, id_name: "profile_id", id_field: "slug", persisted: true + + plug :load_and_authorize_resource, + model: User, + id_name: "profile_id", + id_field: "slug", + persisted: true def index(conn, _params) do user = conn.assigns.user @@ -16,11 +21,18 @@ defmodule PhilomenaWeb.Profile.SourceChangeController do source_changes = SourceChange |> join(:inner, [sc], i in Image, on: sc.image_id == i.id) - |> where([sc, i], sc.user_id == ^user.id and not (i.user_id == ^user.id and i.anonymous == true)) + |> where( + [sc, i], + sc.user_id == ^user.id and not (i.user_id == ^user.id and i.anonymous == true) + ) |> preload([:user, image: [:user, :tags]]) |> order_by(desc: :created_at) |> Repo.paginate(conn.assigns.scrivener) - - render(conn, "index.html", title: "Source Changes for User `#{user.name}'", user: user, source_changes: source_changes) + + render(conn, "index.html", + title: "Source Changes for User `#{user.name}'", + user: user, + source_changes: source_changes + ) end end diff --git a/lib/philomena_web/controllers/profile/tag_change_controller.ex b/lib/philomena_web/controllers/profile/tag_change_controller.ex index 1cafc69e..1254dadd 100644 --- a/lib/philomena_web/controllers/profile/tag_change_controller.ex +++ b/lib/philomena_web/controllers/profile/tag_change_controller.ex @@ -16,19 +16,28 @@ defmodule PhilomenaWeb.Profile.TagChangeController do tag_changes = TagChange |> join(:inner, [tc], i in Image, on: tc.image_id == i.id) - |> where([tc, i], tc.user_id == ^user.id and not (i.user_id == ^user.id and i.anonymous == true)) + |> where( + [tc, i], + tc.user_id == ^user.id and not (i.user_id == ^user.id and i.anonymous == true) + ) |> added_filter(params) |> preload([:tag, :user, image: [:user, :tags]]) |> order_by(desc: :created_at) |> Repo.paginate(conn.assigns.scrivener) - render(conn, "index.html", title: "Tag Changes for User `#{user.name}'", user: user, tag_changes: tag_changes) + render(conn, "index.html", + title: "Tag Changes for User `#{user.name}'", + user: user, + tag_changes: tag_changes + ) end defp added_filter(query, %{"added" => "1"}), do: where(query, added: true) + defp added_filter(query, %{"added" => "0"}), do: where(query, added: false) + defp added_filter(query, _params), do: query end diff --git a/lib/philomena_web/controllers/profile/user_link_controller.ex b/lib/philomena_web/controllers/profile/user_link_controller.ex index 7db1bd6f..577b4cd1 100644 --- a/lib/philomena_web/controllers/profile/user_link_controller.ex +++ b/lib/philomena_web/controllers/profile/user_link_controller.ex @@ -8,7 +8,11 @@ defmodule PhilomenaWeb.Profile.UserLinkController do import Ecto.Query plug PhilomenaWeb.FilterBannedUsersPlug when action in [:new, :create] - plug :load_and_authorize_resource, model: UserLink, only: [:show, :edit, :update], preload: [:user, :tag, :contacted_by_user] + + plug :load_and_authorize_resource, + model: UserLink, + only: [:show, :edit, :update], + preload: [:user, :tag, :contacted_by_user] plug PhilomenaWeb.CanaryMapPlug, index: :create_links, @@ -18,10 +22,15 @@ defmodule PhilomenaWeb.Profile.UserLinkController do edit: :edit_links, update: :edit_links - plug :load_and_authorize_resource, model: User, id_field: "slug", id_name: "profile_id", persisted: true + plug :load_and_authorize_resource, + model: User, + id_field: "slug", + id_name: "profile_id", + persisted: true def index(conn, _params) do user = conn.assigns.current_user + user_links = UserLink |> where(user_id: ^user.id) @@ -39,7 +48,10 @@ defmodule PhilomenaWeb.Profile.UserLinkController do case UserLinks.create_user_link(conn.assigns.user, user_link_params) do {:ok, user_link} -> conn - |> put_flash(:info, "Link submitted! Please put '#{user_link.verification_code}' on your linked webpage now.") + |> put_flash( + :info, + "Link submitted! Please put '#{user_link.verification_code}' on your linked webpage now." + ) |> redirect(to: Routes.profile_user_link_path(conn, :show, conn.assigns.user, user_link)) {:error, %Ecto.Changeset{} = changeset} -> diff --git a/lib/philomena_web/controllers/profile_controller.ex b/lib/philomena_web/controllers/profile_controller.ex index 266eee04..63c586d7 100644 --- a/lib/philomena_web/controllers/profile_controller.ex +++ b/lib/philomena_web/controllers/profile_controller.ex @@ -19,9 +19,17 @@ defmodule PhilomenaWeb.ProfileController do alias Philomena.Repo import Ecto.Query - plug :load_and_authorize_resource, model: User, only: :show, id_field: "slug", preload: [ - awards: [:badge, :awarded_by], public_links: :tag, verified_links: :tag, commission: [sheet_image: :tags, items: [example_image: :tags]] - ] + plug :load_and_authorize_resource, + model: User, + only: :show, + id_field: "slug", + preload: [ + awards: [:badge, :awarded_by], + public_links: :tag, + verified_links: :tag, + commission: [sheet_image: :tags, items: [example_image: :tags]] + ] + plug :set_admin_metadata plug :set_mod_notes @@ -45,8 +53,8 @@ defmodule PhilomenaWeb.ProfileController do ) tags = tags(conn.assigns.user.public_links) - - all_tag_ids = + + all_tag_ids = conn.assigns.user.verified_links |> tags() |> Enum.map(& &1.id) @@ -54,7 +62,11 @@ defmodule PhilomenaWeb.ProfileController do watcher_counts = Tag |> where([t], t.id in ^all_tag_ids) - |> join(:inner_lateral, [t], _ in fragment("SELECT count(*) FROM users WHERE watched_tag_ids @> ARRAY[?]", t.id)) + |> join( + :inner_lateral, + [t], + _ in fragment("SELECT count(*) FROM users WHERE watched_tag_ids @> ARRAY[?]", t.id) + ) |> select([t, c], {t.id, c.count}) |> Repo.all() |> Map.new() @@ -110,14 +122,11 @@ defmodule PhilomenaWeb.ProfileController do ) |> Enum.filter(&Canada.Can.can?(current_user, :show, &1.topic)) - about_me = - Renderer.render_one(%{body: user.description || ""}, conn) + about_me = Renderer.render_one(%{body: user.description || ""}, conn) - scratchpad = - Renderer.render_one(%{body: user.scratchpad || ""}, conn) + scratchpad = Renderer.render_one(%{body: user.scratchpad || ""}, conn) - commission_information = - commission_info(user.commission, conn) + commission_information = commission_info(user.commission, conn) recent_galleries = Gallery @@ -183,7 +192,7 @@ defmodule PhilomenaWeb.ProfileController do end defp individual_stat(mapping, stat_name) do - Enum.map((89..0), &map_fetch(mapping[&1], stat_name) || 0) + Enum.map(89..0, &(map_fetch(mapping[&1], stat_name) || 0)) end defp map_fetch(nil, _field_name), do: nil @@ -191,12 +200,14 @@ defmodule PhilomenaWeb.ProfileController do defp commission_info(%{information: info}, conn) when info not in [nil, ""], do: Renderer.render_one(%{body: info}, conn) + defp commission_info(_commission, _conn), do: "" defp tags([]), do: [] defp tags(links), do: Enum.map(links, & &1.tag) |> Enum.reject(&is_nil/1) defp recent_artwork(_conn, []), do: [] + defp recent_artwork(conn, tags) do {images, _tags} = ImageLoader.query( @@ -213,6 +224,7 @@ defmodule PhilomenaWeb.ProfileController do true -> user = Repo.preload(conn.assigns.user, :current_filter) filter = user.current_filter + last_ip = UserIp |> where(user_id: ^user.id) @@ -227,7 +239,6 @@ defmodule PhilomenaWeb.ProfileController do |> limit(1) |> Repo.one() - conn |> assign(:filter, filter) |> assign(:last_ip, last_ip) diff --git a/lib/philomena_web/controllers/registration/totp_controller.ex b/lib/philomena_web/controllers/registration/totp_controller.ex index 3d76bc66..6cf57377 100644 --- a/lib/philomena_web/controllers/registration/totp_controller.ex +++ b/lib/philomena_web/controllers/registration/totp_controller.ex @@ -20,7 +20,13 @@ defmodule PhilomenaWeb.Registration.TotpController do changeset = Pow.Plug.change_user(conn) secret = User.totp_secret(user) qrcode = User.totp_qrcode(user) - render(conn, "edit.html", title: "Two-Factor Authentication", changeset: changeset, totp_secret: secret, totp_qrcode: qrcode) + + render(conn, "edit.html", + title: "Two-Factor Authentication", + changeset: changeset, + totp_secret: secret, + totp_qrcode: qrcode + ) end end @@ -36,7 +42,7 @@ defmodule PhilomenaWeb.Registration.TotpController do secret = User.totp_secret(user) qrcode = User.totp_qrcode(user) render(conn, "edit.html", changeset: changeset, totp_secret: secret, totp_qrcode: qrcode) - + {:ok, user} -> conn |> PhilomenaWeb.TotpPlug.update_valid_totp_at_for_session(user) diff --git a/lib/philomena_web/controllers/report_controller.ex b/lib/philomena_web/controllers/report_controller.ex index b6afb46a..32f753e2 100644 --- a/lib/philomena_web/controllers/report_controller.ex +++ b/lib/philomena_web/controllers/report_controller.ex @@ -9,6 +9,7 @@ defmodule PhilomenaWeb.ReportController do def index(conn, _params) do user = conn.assigns.current_user + reports = Report |> where(user_id: ^user.id) @@ -18,8 +19,7 @@ defmodule PhilomenaWeb.ReportController do reports |> Polymorphic.load_polymorphic(reportable: [reportable_id: :reportable_type]) - reports = - %{reports | entries: polymorphic} + reports = %{reports | entries: polymorphic} render(conn, "index.html", title: "My Reports", reports: reports) end @@ -37,7 +37,10 @@ defmodule PhilomenaWeb.ReportController do case too_many_reports?(conn) do true -> conn - |> put_flash(:error, "You may not have more than 5 open reports at a time. Did you read the reporting tips?") + |> put_flash( + :error, + "You may not have more than 5 open reports at a time. Did you read the reporting tips?" + ) |> redirect(to: "/") _falsy -> @@ -46,7 +49,10 @@ defmodule PhilomenaWeb.ReportController do Reports.reindex_report(report) conn - |> put_flash(:info, "Your report has been received and will be checked by staff shortly.") + |> put_flash( + :info, + "Your report has been received and will be checked by staff shortly." + ) |> redirect(to: redirect_path(conn, conn.assigns.current_user)) {:error, changeset} -> @@ -65,6 +71,7 @@ defmodule PhilomenaWeb.ReportController do end defp too_many_reports_user?(nil), do: false + defp too_many_reports_user?(user) do reports_open = Report diff --git a/lib/philomena_web/controllers/search/reverse_controller.ex b/lib/philomena_web/controllers/search/reverse_controller.ex index 247a3214..88c1df44 100644 --- a/lib/philomena_web/controllers/search/reverse_controller.ex +++ b/lib/philomena_web/controllers/search/reverse_controller.ex @@ -3,7 +3,8 @@ defmodule PhilomenaWeb.Search.ReverseController do alias PhilomenaWeb.ImageReverse - plug PhilomenaWeb.ScraperPlug, [params_key: "image", params_name: "image"] when action in [:create] + plug PhilomenaWeb.ScraperPlug, + [params_key: "image", params_name: "image"] when action in [:create] def index(conn, _params) do render(conn, "index.html", title: "Reverse Search", images: nil) diff --git a/lib/philomena_web/controllers/search_controller.ex b/lib/philomena_web/controllers/search_controller.ex index fce32212..1b23ca1e 100644 --- a/lib/philomena_web/controllers/search_controller.ex +++ b/lib/philomena_web/controllers/search_controller.ex @@ -9,16 +9,31 @@ defmodule PhilomenaWeb.SearchController do user = conn.assigns.current_user sort = ImageSorter.parse_sort(params) - case ImageLoader.search_string(conn, params["q"], sorts: sort.sorts, queries: sort.queries, constant_score: sort.constant_score) do + case ImageLoader.search_string(conn, params["q"], + sorts: sort.sorts, + queries: sort.queries, + constant_score: sort.constant_score + ) do {:ok, {images, tags}} -> - interactions = - Interactions.user_interactions(images, user) + interactions = Interactions.user_interactions(images, user) conn - |> render("index.html", title: "Searching for #{params["q"]}", images: images, tags: tags, search_query: params["q"], interactions: interactions, layout_class: "layout--wide") + |> render("index.html", + title: "Searching for #{params["q"]}", + images: images, + tags: tags, + search_query: params["q"], + interactions: interactions, + layout_class: "layout--wide" + ) {:error, msg} -> - render(conn, "index.html", title: "Searching for #{params["q"]}", images: [], error: msg, search_query: params["q"]) + render(conn, "index.html", + title: "Searching for #{params["q"]}", + images: [], + error: msg, + search_query: params["q"] + ) end end end diff --git a/lib/philomena_web/controllers/setting_controller.ex b/lib/philomena_web/controllers/setting_controller.ex index 22998985..f46bc5ec 100644 --- a/lib/philomena_web/controllers/setting_controller.ex +++ b/lib/philomena_web/controllers/setting_controller.ex @@ -45,10 +45,14 @@ defmodule PhilomenaWeb.SettingController do defp set_cookie(conn, params, param_name, cookie_name) do # JS wants access; max-age is set to 25 years from now - Conn.put_resp_cookie(conn, cookie_name, to_string(params[param_name] == "true"), max_age: 788_923_800, http_only: false) + Conn.put_resp_cookie(conn, cookie_name, to_string(params[param_name] == "true"), + max_age: 788_923_800, + http_only: false + ) end defp maybe_update_user(conn, nil, _user_params), do: {:ok, conn} + defp maybe_update_user(conn, user, user_params) do case Users.update_settings(user, user_params) do {:ok, _user} -> diff --git a/lib/philomena_web/controllers/staff_controller.ex b/lib/philomena_web/controllers/staff_controller.ex index 755c5970..ca201058 100644 --- a/lib/philomena_web/controllers/staff_controller.ex +++ b/lib/philomena_web/controllers/staff_controller.ex @@ -13,11 +13,17 @@ defmodule PhilomenaWeb.StaffController do |> Repo.all() categories = [ - "Administrators": Enum.filter(users, & &1.role == "admin"), - "Technical Team": Enum.filter(users, & &1.role != "admin" and &1.secondary_role in ["Site Developer", "System Administrator"]), - "Public Relations": Enum.filter(users, & &1.role != "admin" and &1.secondary_role == "Public Relations"), - "Moderators": Enum.filter(users, & &1.role == "moderator" and &1.secondary_role in [nil, ""]), - "Assistants": Enum.filter(users, & &1.role == "assistant" and &1.secondary_role in [nil, ""]) + Administrators: Enum.filter(users, &(&1.role == "admin")), + "Technical Team": + Enum.filter( + users, + &(&1.role != "admin" and &1.secondary_role in ["Site Developer", "System Administrator"]) + ), + "Public Relations": + Enum.filter(users, &(&1.role != "admin" and &1.secondary_role == "Public Relations")), + Moderators: + Enum.filter(users, &(&1.role == "moderator" and &1.secondary_role in [nil, ""])), + Assistants: Enum.filter(users, &(&1.role == "assistant" and &1.secondary_role in [nil, ""])) ] render(conn, "index.html", title: "Site Staff", categories: categories) diff --git a/lib/philomena_web/controllers/stat_controller.ex b/lib/philomena_web/controllers/stat_controller.ex index 6c024613..b6860f10 100644 --- a/lib/philomena_web/controllers/stat_controller.ex +++ b/lib/philomena_web/controllers/stat_controller.ex @@ -125,7 +125,7 @@ defmodule PhilomenaWeb.StatController do response_time = closed_reports - |> Enum.reduce(0, & &2 + NaiveDateTime.diff(&1.updated_at, &1.created_at, :second)) + |> Enum.reduce(0, &(&2 + NaiveDateTime.diff(&1.updated_at, &1.created_at, :second))) |> Kernel./(safe_length(closed_reports) * 3600) |> trunc() diff --git a/lib/philomena_web/controllers/tag/alias_controller.ex b/lib/philomena_web/controllers/tag/alias_controller.ex index 6b687a2a..65ef5876 100644 --- a/lib/philomena_web/controllers/tag/alias_controller.ex +++ b/lib/philomena_web/controllers/tag/alias_controller.ex @@ -5,7 +5,13 @@ defmodule PhilomenaWeb.Tag.AliasController do alias Philomena.Tags plug PhilomenaWeb.CanaryMapPlug, edit: :alias, update: :alias, delete: :alias - plug :load_and_authorize_resource, model: Tag, id_name: "tag_id", id_field: "slug", preload: [:implied_tags, :aliased_tag], persisted: true + + plug :load_and_authorize_resource, + model: Tag, + id_name: "tag_id", + id_field: "slug", + preload: [:implied_tags, :aliased_tag], + persisted: true def edit(conn, _params) do changeset = Tags.change_tag(conn.assigns.tag) @@ -13,9 +19,9 @@ defmodule PhilomenaWeb.Tag.AliasController do end def update(conn, %{"tag" => tag_params}) do - spawn fn -> + spawn(fn -> Tags.alias_tag(conn.assigns.tag, tag_params) - end + end) conn |> put_flash(:info, "Tag alias queued.") diff --git a/lib/philomena_web/controllers/tag/autocomplete_controller.ex b/lib/philomena_web/controllers/tag/autocomplete_controller.ex index 89c4356d..76c32ca9 100644 --- a/lib/philomena_web/controllers/tag/autocomplete_controller.ex +++ b/lib/philomena_web/controllers/tag/autocomplete_controller.ex @@ -39,5 +39,6 @@ defmodule PhilomenaWeb.Tag.AutocompleteController do |> String.downcase() |> String.trim() end + defp query(_params), do: nil end diff --git a/lib/philomena_web/controllers/tag/detail_controller.ex b/lib/philomena_web/controllers/tag/detail_controller.ex index 3893f6db..b5b7abf2 100644 --- a/lib/philomena_web/controllers/tag/detail_controller.ex +++ b/lib/philomena_web/controllers/tag/detail_controller.ex @@ -42,7 +42,7 @@ defmodule PhilomenaWeb.Tag.DetailController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :edit, %Tag{}) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/tag/fetch_controller.ex b/lib/philomena_web/controllers/tag/fetch_controller.ex index fc7b8d27..725d0ed5 100644 --- a/lib/philomena_web/controllers/tag/fetch_controller.ex +++ b/lib/philomena_web/controllers/tag/fetch_controller.ex @@ -30,10 +30,11 @@ defmodule PhilomenaWeb.Tag.FetchController do defp tag_image(%{image: image}) when image not in [nil, ""], do: tag_url_root() <> "/" <> image + defp tag_image(_other), do: nil defp tag_url_root do Application.get_env(:philomena, :tag_url_root) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/tag/image_controller.ex b/lib/philomena_web/controllers/tag/image_controller.ex index e9fb8ccc..6f34ec1a 100644 --- a/lib/philomena_web/controllers/tag/image_controller.ex +++ b/lib/philomena_web/controllers/tag/image_controller.ex @@ -5,7 +5,13 @@ defmodule PhilomenaWeb.Tag.ImageController do alias Philomena.Tags plug PhilomenaWeb.CanaryMapPlug, update: :edit, delete: :edit - plug :load_and_authorize_resource, model: Tag, id_name: "tag_id", id_field: "slug", preload: [:implied_tags], persisted: true + + plug :load_and_authorize_resource, + model: Tag, + id_name: "tag_id", + id_field: "slug", + preload: [:implied_tags], + persisted: true def edit(conn, _params) do changeset = Tags.change_tag(conn.assigns.tag) diff --git a/lib/philomena_web/controllers/tag/reindex_controller.ex b/lib/philomena_web/controllers/tag/reindex_controller.ex index fe0b96ff..ba0c6e04 100644 --- a/lib/philomena_web/controllers/tag/reindex_controller.ex +++ b/lib/philomena_web/controllers/tag/reindex_controller.ex @@ -5,12 +5,18 @@ defmodule PhilomenaWeb.Tag.ReindexController do alias Philomena.Tags plug PhilomenaWeb.CanaryMapPlug, create: :alias - plug :load_and_authorize_resource, model: Tag, id_name: "tag_id", id_field: "slug", preload: [:implied_tags, :aliased_tag], persisted: true + + plug :load_and_authorize_resource, + model: Tag, + id_name: "tag_id", + id_field: "slug", + preload: [:implied_tags, :aliased_tag], + persisted: true def create(conn, _params) do - spawn fn -> + spawn(fn -> Tags.reindex_tag_images(conn.assigns.tag) - end + end) conn |> put_flash(:info, "Tag reindex started.") diff --git a/lib/philomena_web/controllers/tag/tag_change_controller.ex b/lib/philomena_web/controllers/tag/tag_change_controller.ex index 2bc0d2c2..1313ec83 100644 --- a/lib/philomena_web/controllers/tag/tag_change_controller.ex +++ b/lib/philomena_web/controllers/tag/tag_change_controller.ex @@ -20,13 +20,19 @@ defmodule PhilomenaWeb.Tag.TagChangeController do |> order_by(desc: :created_at) |> Repo.paginate(conn.assigns.scrivener) - render(conn, "index.html", title: "Tag Changes for Tag `#{tag.name}'", tag: tag, tag_changes: tag_changes) + render(conn, "index.html", + title: "Tag Changes for Tag `#{tag.name}'", + tag: tag, + tag_changes: tag_changes + ) end defp added_filter(query, %{"added" => "1"}), do: where(query, added: true) + defp added_filter(query, %{"added" => "0"}), do: where(query, added: false) + defp added_filter(query, _params), do: query end diff --git a/lib/philomena_web/controllers/tag/watch_controller.ex b/lib/philomena_web/controllers/tag/watch_controller.ex index 48430f24..66dd8a46 100644 --- a/lib/philomena_web/controllers/tag/watch_controller.ex +++ b/lib/philomena_web/controllers/tag/watch_controller.ex @@ -34,4 +34,4 @@ defmodule PhilomenaWeb.Tag.WatchController do |> text("") end end -end \ No newline at end of file +end diff --git a/lib/philomena_web/controllers/tag_change/revert_controller.ex b/lib/philomena_web/controllers/tag_change/revert_controller.ex index 9c23a33c..fba63fee 100644 --- a/lib/philomena_web/controllers/tag_change/revert_controller.ex +++ b/lib/philomena_web/controllers/tag_change/revert_controller.ex @@ -9,6 +9,7 @@ defmodule PhilomenaWeb.TagChange.RevertController do def create(conn, %{"ids" => ids}) when is_list(ids) do attributes = conn.assigns.attributes + attributes = %{ ip: attributes[:ip], fingerprint: attributes[:fingerprint], @@ -32,7 +33,7 @@ defmodule PhilomenaWeb.TagChange.RevertController do defp verify_authorized(conn, _params) do case Canada.Can.can?(conn.assigns.current_user, :revert, TagChange) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/tag_controller.ex b/lib/philomena_web/controllers/tag_controller.ex index 9cb78253..2267ed68 100644 --- a/lib/philomena_web/controllers/tag_controller.ex +++ b/lib/philomena_web/controllers/tag_controller.ex @@ -9,9 +9,21 @@ defmodule PhilomenaWeb.TagController do plug PhilomenaWeb.RecodeParameterPlug, [name: "id"] when action in [:show] plug PhilomenaWeb.CanaryMapPlug, update: :edit - plug :load_and_authorize_resource, model: Tag, id_field: "slug", only: [:show, :edit, :update, :delete], preload: [ - :aliases, :aliased_tag, :implied_tags, :implied_by_tags, :dnp_entries, public_links: :user, hidden_links: :user - ] + + plug :load_and_authorize_resource, + model: Tag, + id_field: "slug", + only: [:show, :edit, :update, :delete], + preload: [ + :aliases, + :aliased_tag, + :implied_tags, + :implied_by_tags, + :dnp_entries, + public_links: :user, + hidden_links: :user + ] + plug :redirect_alias when action in [:show] def index(conn, params) do @@ -41,20 +53,16 @@ defmodule PhilomenaWeb.TagController do user = conn.assigns.current_user tag = conn.assigns.tag - {images, _tags} = - ImageLoader.query(conn, %{term: %{"namespaced_tags.name" => tag.name}}) + {images, _tags} = ImageLoader.query(conn, %{term: %{"namespaced_tags.name" => tag.name}}) - interactions = - Interactions.user_interactions(images, user) + interactions = Interactions.user_interactions(images, user) - body = - Renderer.render_one(%{body: tag.description || ""}, conn) + body = Renderer.render_one(%{body: tag.description || ""}, conn) dnp_bodies = Renderer.render_collection(Enum.map(tag.dnp_entries, &%{body: &1.conditions || ""}), conn) - dnp_entries = - Enum.zip(dnp_bodies, tag.dnp_entries) + dnp_entries = Enum.zip(dnp_bodies, tag.dnp_entries) search_query = escape_name(tag) params = Map.put(conn.params, "q", search_query) @@ -92,9 +100,9 @@ defmodule PhilomenaWeb.TagController do end def delete(conn, _params) do - spawn fn -> + spawn(fn -> Tags.delete_tag(conn.assigns.tag) - end + end) conn |> put_flash(:info, "Tag scheduled for deletion.") @@ -140,7 +148,10 @@ defmodule PhilomenaWeb.TagController do %{aliased_tag: tag} -> conn - |> put_flash(:info, "This tag (\"#{conn.assigns.tag.name}\") has been aliased into the tag \"#{tag.name}\".") + |> put_flash( + :info, + "This tag (\"#{conn.assigns.tag.name}\") has been aliased into the tag \"#{tag.name}\"." + ) |> redirect(to: Routes.tag_path(conn, :show, tag)) end end diff --git a/lib/philomena_web/controllers/topic/hide_controller.ex b/lib/philomena_web/controllers/topic/hide_controller.ex index beaf420d..eae39ed3 100644 --- a/lib/philomena_web/controllers/topic/hide_controller.ex +++ b/lib/philomena_web/controllers/topic/hide_controller.ex @@ -7,7 +7,12 @@ defmodule PhilomenaWeb.Topic.HideController do alias Philomena.Topics plug PhilomenaWeb.CanaryMapPlug, create: :show, delete: :show - plug :load_and_authorize_resource, model: Forum, id_name: "forum_id", id_field: "short_name", persisted: true + + plug :load_and_authorize_resource, + model: Forum, + id_name: "forum_id", + id_field: "short_name", + persisted: true plug PhilomenaWeb.LoadTopicPlug plug PhilomenaWeb.CanaryMapPlug, create: :hide, delete: :hide diff --git a/lib/philomena_web/controllers/topic/lock_controller.ex b/lib/philomena_web/controllers/topic/lock_controller.ex index b1ade7ab..8a96066b 100644 --- a/lib/philomena_web/controllers/topic/lock_controller.ex +++ b/lib/philomena_web/controllers/topic/lock_controller.ex @@ -7,7 +7,12 @@ defmodule PhilomenaWeb.Topic.LockController do alias Philomena.Topics plug PhilomenaWeb.CanaryMapPlug, create: :show, delete: :show - plug :load_and_authorize_resource, model: Forum, id_name: "forum_id", id_field: "short_name", persisted: true + + plug :load_and_authorize_resource, + model: Forum, + id_name: "forum_id", + id_field: "short_name", + persisted: true plug PhilomenaWeb.LoadTopicPlug plug PhilomenaWeb.CanaryMapPlug, create: :hide, delete: :hide diff --git a/lib/philomena_web/controllers/topic/move_controller.ex b/lib/philomena_web/controllers/topic/move_controller.ex index efee8401..50ded78a 100644 --- a/lib/philomena_web/controllers/topic/move_controller.ex +++ b/lib/philomena_web/controllers/topic/move_controller.ex @@ -8,7 +8,12 @@ defmodule PhilomenaWeb.Topic.MoveController do alias Philomena.Repo plug PhilomenaWeb.CanaryMapPlug, create: :show, delete: :show - plug :load_and_authorize_resource, model: Forum, id_name: "forum_id", id_field: "short_name", persisted: true + + plug :load_and_authorize_resource, + model: Forum, + id_name: "forum_id", + id_field: "short_name", + persisted: true plug PhilomenaWeb.LoadTopicPlug plug PhilomenaWeb.CanaryMapPlug, create: :hide, delete: :hide diff --git a/lib/philomena_web/controllers/topic/poll/vote_controller.ex b/lib/philomena_web/controllers/topic/poll/vote_controller.ex index 3e272100..b92f1c54 100644 --- a/lib/philomena_web/controllers/topic/poll/vote_controller.ex +++ b/lib/philomena_web/controllers/topic/poll/vote_controller.ex @@ -6,10 +6,15 @@ defmodule PhilomenaWeb.Topic.Poll.VoteController do alias Philomena.PollVotes alias Philomena.Repo import Ecto.Query - + plug PhilomenaWeb.FilterBannedUsersPlug when action in [:create] plug PhilomenaWeb.CanaryMapPlug, index: :show, create: :show, delete: :show - plug :load_and_authorize_resource, model: Forum, id_name: "forum_id", id_field: "short_name", persisted: true + + plug :load_and_authorize_resource, + model: Forum, + id_name: "forum_id", + id_field: "short_name", + persisted: true plug PhilomenaWeb.LoadTopicPlug plug PhilomenaWeb.LoadPollPlug @@ -24,7 +29,7 @@ defmodule PhilomenaWeb.Topic.Poll.VoteController do |> where(poll_id: ^poll.id) |> preload(poll_votes: :user) |> Repo.all() - |> Enum.filter(& &1.vote_count > 0) + |> Enum.filter(&(&1.vote_count > 0)) render(conn, "index.html", layout: false, options: options) end @@ -59,7 +64,7 @@ defmodule PhilomenaWeb.Topic.Poll.VoteController do defp verify_authorized(conn, _opts) do case Canada.Can.can?(conn.assigns.current_user, :hide, conn.assigns.topic) do - true -> conn + true -> conn _false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/controllers/topic/post/delete_controller.ex b/lib/philomena_web/controllers/topic/post/delete_controller.ex index e28fa63c..726a4a32 100644 --- a/lib/philomena_web/controllers/topic/post/delete_controller.ex +++ b/lib/philomena_web/controllers/topic/post/delete_controller.ex @@ -5,7 +5,12 @@ defmodule PhilomenaWeb.Topic.Post.DeleteController do alias Philomena.Posts plug PhilomenaWeb.CanaryMapPlug, create: :hide - plug :load_and_authorize_resource, model: Post, id_name: "post_id", persisted: true, preload: [:topic, topic: :forum] + + plug :load_and_authorize_resource, + model: Post, + id_name: "post_id", + persisted: true, + preload: [:topic, topic: :forum] def create(conn, _params) do post = conn.assigns.post @@ -16,12 +21,20 @@ defmodule PhilomenaWeb.Topic.Post.DeleteController do conn |> put_flash(:info, "Post successfully destroyed!") - |> redirect(to: Routes.forum_topic_path(conn, :show, post.topic.forum, post.topic, post_id: post.id) <> "#post_#{post.id}") + |> redirect( + to: + Routes.forum_topic_path(conn, :show, post.topic.forum, post.topic, post_id: post.id) <> + "#post_#{post.id}" + ) {:error, _changeset} -> conn |> put_flash(:error, "Unable to destroy post!") - |> redirect(to: Routes.forum_topic_path(conn, :show, post.topic.forum, post.topic, post_id: post.id) <> "#post_#{post.id}") + |> redirect( + to: + Routes.forum_topic_path(conn, :show, post.topic.forum, post.topic, post_id: post.id) <> + "#post_#{post.id}" + ) end end end diff --git a/lib/philomena_web/controllers/topic/post/hide_controller.ex b/lib/philomena_web/controllers/topic/post/hide_controller.ex index d2fafe54..3779d358 100644 --- a/lib/philomena_web/controllers/topic/post/hide_controller.ex +++ b/lib/philomena_web/controllers/topic/post/hide_controller.ex @@ -6,7 +6,12 @@ defmodule PhilomenaWeb.Topic.Post.HideController do alias Philomena.Posts plug PhilomenaWeb.CanaryMapPlug, create: :hide, delete: :hide - plug :load_and_authorize_resource, model: Post, id_name: "post_id", persisted: true, preload: [:topic, topic: :forum] + + plug :load_and_authorize_resource, + model: Post, + id_name: "post_id", + persisted: true, + preload: [:topic, topic: :forum] def create(conn, %{"post" => post_params}) do post = conn.assigns.post @@ -19,12 +24,20 @@ defmodule PhilomenaWeb.Topic.Post.HideController do conn |> put_flash(:info, "Post successfully hidden!") - |> redirect(to: Routes.forum_topic_path(conn, :show, post.topic.forum, post.topic, post_id: post.id) <> "#post_#{post.id}") + |> redirect( + to: + Routes.forum_topic_path(conn, :show, post.topic.forum, post.topic, post_id: post.id) <> + "#post_#{post.id}" + ) {:error, _changeset} -> conn |> put_flash(:error, "Unable to hide post!") - |> redirect(to: Routes.forum_topic_path(conn, :show, post.topic.forum, post.topic, post_id: post.id) <> "#post_#{post.id}") + |> redirect( + to: + Routes.forum_topic_path(conn, :show, post.topic.forum, post.topic, post_id: post.id) <> + "#post_#{post.id}" + ) end end @@ -37,12 +50,20 @@ defmodule PhilomenaWeb.Topic.Post.HideController do conn |> put_flash(:info, "Post successfully unhidden!") - |> redirect(to: Routes.forum_topic_path(conn, :show, post.topic.forum, post.topic, post_id: post.id) <> "#post_#{post.id}") + |> redirect( + to: + Routes.forum_topic_path(conn, :show, post.topic.forum, post.topic, post_id: post.id) <> + "#post_#{post.id}" + ) {:error, _changeset} -> conn |> put_flash(:error, "Unable to unhide post!") - |> redirect(to: Routes.forum_topic_path(conn, :show, post.topic.forum, post.topic, post_id: post.id) <> "#post_#{post.id}") + |> redirect( + to: + Routes.forum_topic_path(conn, :show, post.topic.forum, post.topic, post_id: post.id) <> + "#post_#{post.id}" + ) end end end diff --git a/lib/philomena_web/controllers/topic/post/history_controller.ex b/lib/philomena_web/controllers/topic/post/history_controller.ex index bc8bd4c8..d06480e7 100644 --- a/lib/philomena_web/controllers/topic/post/history_controller.ex +++ b/lib/philomena_web/controllers/topic/post/history_controller.ex @@ -8,7 +8,12 @@ defmodule PhilomenaWeb.Topic.Post.HistoryController do import Ecto.Query plug PhilomenaWeb.CanaryMapPlug, index: :show - plug :load_and_authorize_resource, model: Forum, id_name: "forum_id", id_field: "short_name", persisted: true + + plug :load_and_authorize_resource, + model: Forum, + id_name: "forum_id", + id_field: "short_name", + persisted: true plug PhilomenaWeb.LoadTopicPlug plug PhilomenaWeb.LoadPostPlug @@ -25,6 +30,9 @@ defmodule PhilomenaWeb.Topic.Post.HistoryController do |> Repo.all() |> Versions.load_data_and_associations(post) - render(conn, "index.html", title: "Post History for Post #{post.id} - #{topic.title} - Forums", versions: versions) + render(conn, "index.html", + title: "Post History for Post #{post.id} - #{topic.title} - Forums", + versions: versions + ) end end diff --git a/lib/philomena_web/controllers/topic/post/report_controller.ex b/lib/philomena_web/controllers/topic/post/report_controller.ex index 88d4db46..eaf8ae65 100644 --- a/lib/philomena_web/controllers/topic/post/report_controller.ex +++ b/lib/philomena_web/controllers/topic/post/report_controller.ex @@ -12,7 +12,12 @@ defmodule PhilomenaWeb.Topic.Post.ReportController do plug PhilomenaWeb.CaptchaPlug when action in [:create] plug PhilomenaWeb.CanaryMapPlug, new: :show, create: :show - plug :load_and_authorize_resource, model: Forum, id_name: "forum_id", id_field: "short_name", persisted: true + + plug :load_and_authorize_resource, + model: Forum, + id_name: "forum_id", + id_field: "short_name", + persisted: true plug PhilomenaWeb.LoadTopicPlug plug PhilomenaWeb.LoadPostPlug @@ -21,6 +26,7 @@ defmodule PhilomenaWeb.Topic.Post.ReportController do topic = conn.assigns.topic post = conn.assigns.post action = Routes.forum_topic_post_report_path(conn, :create, topic.forum, topic, post) + changeset = %Report{reportable_type: "Post", reportable_id: post.id} |> Reports.change_report() diff --git a/lib/philomena_web/controllers/topic/post_controller.ex b/lib/philomena_web/controllers/topic/post_controller.ex index feef4aaf..f1234dc3 100644 --- a/lib/philomena_web/controllers/topic/post_controller.ex +++ b/lib/philomena_web/controllers/topic/post_controller.ex @@ -9,7 +9,12 @@ defmodule PhilomenaWeb.Topic.PostController do plug PhilomenaWeb.UserAttributionPlug plug PhilomenaWeb.CanaryMapPlug, create: :show, edit: :show, update: :show - plug :load_and_authorize_resource, model: Forum, id_field: "short_name", id_name: "forum_id", persisted: true + + plug :load_and_authorize_resource, + model: Forum, + id_field: "short_name", + id_name: "forum_id", + persisted: true plug PhilomenaWeb.LoadTopicPlug plug PhilomenaWeb.CanaryMapPlug, create: :create_post, edit: :create_post, update: :create_post @@ -32,7 +37,11 @@ defmodule PhilomenaWeb.Topic.PostController do conn |> put_flash(:info, "Post created successfully.") - |> redirect(to: Routes.forum_topic_path(conn, :show, forum, topic, post_id: post.id) <> "#post_#{post.id}") + |> redirect( + to: + Routes.forum_topic_path(conn, :show, forum, topic, post_id: post.id) <> + "#post_#{post.id}" + ) _error -> conn @@ -56,7 +65,11 @@ defmodule PhilomenaWeb.Topic.PostController do conn |> put_flash(:info, "Post successfully edited.") - |> redirect(to: Routes.forum_topic_path(conn, :show, post.topic.forum, post.topic, post_id: post.id) <> "#post_#{post.id}") + |> redirect( + to: + Routes.forum_topic_path(conn, :show, post.topic.forum, post.topic, post_id: post.id) <> + "#post_#{post.id}" + ) {:error, :post, changeset, _changes} -> render(conn, "edit.html", post: conn.assigns.post, changeset: changeset) diff --git a/lib/philomena_web/controllers/topic/read_controller.ex b/lib/philomena_web/controllers/topic/read_controller.ex index aac0ae20..da7e77ce 100644 --- a/lib/philomena_web/controllers/topic/read_controller.ex +++ b/lib/philomena_web/controllers/topic/read_controller.ex @@ -6,7 +6,12 @@ defmodule PhilomenaWeb.Topic.ReadController do alias Philomena.Topics plug PhilomenaWeb.CanaryMapPlug, create: :show - plug :load_and_authorize_resource, model: Forum, id_name: "forum_id", id_field: "short_name", persisted: true + + plug :load_and_authorize_resource, + model: Forum, + id_name: "forum_id", + id_field: "short_name", + persisted: true plug PhilomenaWeb.LoadTopicPlug, show_hidden: true diff --git a/lib/philomena_web/controllers/topic/stick_controller.ex b/lib/philomena_web/controllers/topic/stick_controller.ex index 522f3529..e7787a23 100644 --- a/lib/philomena_web/controllers/topic/stick_controller.ex +++ b/lib/philomena_web/controllers/topic/stick_controller.ex @@ -7,7 +7,12 @@ defmodule PhilomenaWeb.Topic.StickController do alias Philomena.Topics plug PhilomenaWeb.CanaryMapPlug, create: :show - plug :load_and_authorize_resource, model: Forum, id_name: "forum_id", id_field: "short_name", persisted: true + + plug :load_and_authorize_resource, + model: Forum, + id_name: "forum_id", + id_field: "short_name", + persisted: true plug PhilomenaWeb.LoadTopicPlug plug PhilomenaWeb.CanaryMapPlug, create: :hide, delete: :hide diff --git a/lib/philomena_web/controllers/topic/subscription_controller.ex b/lib/philomena_web/controllers/topic/subscription_controller.ex index 921f2559..8be39d0b 100644 --- a/lib/philomena_web/controllers/topic/subscription_controller.ex +++ b/lib/philomena_web/controllers/topic/subscription_controller.ex @@ -5,7 +5,12 @@ defmodule PhilomenaWeb.Topic.SubscriptionController do alias Philomena.Topics plug PhilomenaWeb.CanaryMapPlug, create: :show, delete: :show - plug :load_and_authorize_resource, model: Forum, id_name: "forum_id", id_field: "short_name", persisted: true + + plug :load_and_authorize_resource, + model: Forum, + id_name: "forum_id", + id_field: "short_name", + persisted: true plug PhilomenaWeb.LoadTopicPlug, [show_hidden: true] when action in [:delete] plug PhilomenaWeb.LoadTopicPlug when action in [:create] @@ -16,7 +21,12 @@ defmodule PhilomenaWeb.Topic.SubscriptionController do case Topics.create_subscription(topic, user) do {:ok, _subscription} -> - render(conn, "_subscription.html", forum: conn.assigns.forum, topic: topic, watching: true, layout: false) + render(conn, "_subscription.html", + forum: conn.assigns.forum, + topic: topic, + watching: true, + layout: false + ) {:error, _changeset} -> render(conn, "_error.html", layout: false) @@ -29,7 +39,12 @@ defmodule PhilomenaWeb.Topic.SubscriptionController do case Topics.delete_subscription(topic, user) do {:ok, _subscription} -> - render(conn, "_subscription.html", forum: conn.assigns.forum, topic: topic, watching: false, layout: false) + render(conn, "_subscription.html", + forum: conn.assigns.forum, + topic: topic, + watching: false, + layout: false + ) {:error, _changeset} -> render(conn, "_error.html", layout: false) diff --git a/lib/philomena_web/controllers/topic_controller.ex b/lib/philomena_web/controllers/topic_controller.ex index 53232a10..bc092c10 100644 --- a/lib/philomena_web/controllers/topic_controller.ex +++ b/lib/philomena_web/controllers/topic_controller.ex @@ -14,7 +14,12 @@ defmodule PhilomenaWeb.TopicController do plug PhilomenaWeb.AdvertPlug when action in [:show] plug PhilomenaWeb.CanaryMapPlug, new: :show, create: :show - plug :load_and_authorize_resource, model: Forum, id_name: "forum_id", id_field: "short_name", persisted: true + + plug :load_and_authorize_resource, + model: Forum, + id_name: "forum_id", + id_field: "short_name", + persisted: true plug PhilomenaWeb.LoadTopicPlug, [param: "id"] when action in [:show] @@ -35,8 +40,7 @@ defmodule PhilomenaWeb.TopicController do page = with {post_id, _extra} <- Integer.parse(params["post_id"] || ""), - [post] <- Post |> where(id: ^post_id) |> Repo.all() - do + [post] <- Post |> where(id: ^post_id) |> Repo.all() do div(post.topic_position, 25) + 1 else _ -> @@ -51,26 +55,21 @@ defmodule PhilomenaWeb.TopicController do |> preload([:deleted_by, :topic, topic: :forum, user: [awards: :badge]]) |> Repo.all() - rendered = - Renderer.render_collection(posts, conn) + rendered = Renderer.render_collection(posts, conn) - posts = - Enum.zip(posts, rendered) + posts = Enum.zip(posts, rendered) - posts = - %Scrivener.Page{ - entries: posts, - page_number: page, - page_size: 25, - total_entries: topic.post_count, - total_pages: div(topic.post_count + 25 - 1, 25) - } + posts = %Scrivener.Page{ + entries: posts, + page_number: page, + page_size: 25, + total_entries: topic.post_count, + total_pages: div(topic.post_count + 25 - 1, 25) + } - watching = - Topics.subscribed?(topic, conn.assigns.current_user) + watching = Topics.subscribed?(topic, conn.assigns.current_user) - voted = - PollVotes.voted?(topic.poll, conn.assigns.current_user) + voted = PollVotes.voted?(topic.poll, conn.assigns.current_user) changeset = %Post{} @@ -78,7 +77,13 @@ defmodule PhilomenaWeb.TopicController do title = "#{topic.title} - #{forum.name} - Forums" - render(conn, "show.html", title: title, posts: posts, changeset: changeset, watching: watching, voted: voted) + render(conn, "show.html", + title: title, + posts: posts, + changeset: changeset, + watching: watching, + voted: voted + ) end def new(conn, _params) do diff --git a/lib/philomena_web/endpoint.ex b/lib/philomena_web/endpoint.ex index cd2a8a28..da9eae5b 100644 --- a/lib/philomena_web/endpoint.ex +++ b/lib/philomena_web/endpoint.ex @@ -46,6 +46,7 @@ defmodule PhilomenaWeb.Endpoint do encryption_salt: "authenticated encrypted cookie" plug Pow.Plug.Session, otp_app: :philomena + plug PowPersistentSession.Plug.Cookie, otp_app: :philomena, persistent_session_cookie_opts: [extra: "SameSite=Lax"] diff --git a/lib/philomena_web/forum_json.ex b/lib/philomena_web/forum_json.ex index c21236bb..50574511 100644 --- a/lib/philomena_web/forum_json.ex +++ b/lib/philomena_web/forum_json.ex @@ -1,5 +1,4 @@ defmodule PhilomenaWeb.ForumJson do - def as_json(%{access_level: "normal"} = forum) do %{ name: forum.name, @@ -9,6 +8,7 @@ defmodule PhilomenaWeb.ForumJson do post_count: forum.post_count } end + def as_json(_forum) do %{ name: nil, diff --git a/lib/philomena_web/gallery_json.ex b/lib/philomena_web/gallery_json.ex index ea6ad8f2..586bea68 100644 --- a/lib/philomena_web/gallery_json.ex +++ b/lib/philomena_web/gallery_json.ex @@ -10,4 +10,4 @@ defmodule PhilomenaWeb.GalleryJson do user_id: gallery.creator_id } end -end \ No newline at end of file +end diff --git a/lib/philomena_web/image_json.ex b/lib/philomena_web/image_json.ex index eb8d6d44..219a45ca 100644 --- a/lib/philomena_web/image_json.ex +++ b/lib/philomena_web/image_json.ex @@ -1,7 +1,8 @@ defmodule PhilomenaWeb.ImageJson do alias PhilomenaWeb.ImageView - def as_json(_conn, %{hidden_from_users: true, duplicate_id: duplicate_id} = image) when not is_nil(duplicate_id) do + def as_json(_conn, %{hidden_from_users: true, duplicate_id: duplicate_id} = image) + when not is_nil(duplicate_id) do %{ id: image.id, created_at: image.created_at, @@ -12,6 +13,7 @@ defmodule PhilomenaWeb.ImageJson do hidden_from_users: true } end + def as_json(_conn, %{hidden_from_users: true} = image) do %{ id: image.id, @@ -23,6 +25,7 @@ defmodule PhilomenaWeb.ImageJson do hidden_from_users: true } end + def as_json(conn, %{hidden_from_users: false} = image) do %{ id: image.id, @@ -62,6 +65,8 @@ defmodule PhilomenaWeb.ImageJson do } end - defp intensities(%{intensity: %{nw: nw, ne: ne, sw: sw, se: se}}), do: %{nw: nw, ne: ne, sw: sw, se: se} + defp intensities(%{intensity: %{nw: nw, ne: ne, sw: sw, se: se}}), + do: %{nw: nw, ne: ne, sw: sw, se: se} + defp intensities(_), do: nil end diff --git a/lib/philomena_web/image_loader.ex b/lib/philomena_web/image_loader.ex index 6793def6..ece6717c 100644 --- a/lib/philomena_web/image_loader.ex +++ b/lib/philomena_web/image_loader.ex @@ -18,10 +18,10 @@ defmodule PhilomenaWeb.ImageLoader do end def query(conn, body, options \\ []) do - sort_queries = Keyword.get(options, :queries, []) - sort_sorts = Keyword.get(options, :sorts, [%{created_at: :desc}]) - pagination = Keyword.get(options, :pagination, conn.assigns.image_pagination) - queryable = Keyword.get(options, :queryable, Image |> preload(:tags)) + sort_queries = Keyword.get(options, :queries, []) + sort_sorts = Keyword.get(options, :sorts, [%{created_at: :desc}]) + pagination = Keyword.get(options, :pagination, conn.assigns.image_pagination) + queryable = Keyword.get(options, :queryable, Image |> preload(:tags)) constant_score = Keyword.get(options, :constant_score, true) tags = @@ -30,10 +30,11 @@ defmodule PhilomenaWeb.ImageLoader do |> load_tags() |> render_bodies(conn) - user = conn.assigns.current_user - filter = conn.assigns.compiled_filter + user = conn.assigns.current_user + filter = conn.assigns.compiled_filter filters = create_filters(conn, user, filter) - body = maybe_constant_score(body, constant_score) + body = maybe_constant_score(body, constant_score) + records = Elasticsearch.search_records( Image, @@ -77,7 +78,7 @@ defmodule PhilomenaWeb.ImageLoader do do: [%{term: %{hidden_from_users: false}} | filters] defp maybe_show_deleted(filters, true, "deleted"), - do: [%{term: %{hidden_from_users: false}}, %{exists: %{field: :duplicate_id}} | filters] + do: [%{term: %{hidden_from_users: false}}, %{exists: %{field: :duplicate_id}} | filters] defp maybe_show_deleted(filters, true, _param), do: [%{term: %{hidden_from_users: true}} | filters] @@ -102,16 +103,28 @@ defmodule PhilomenaWeb.ImageLoader do defp search_tag_name(_other_query), do: [] defp search_tag_names(%{bool: %{must: musts}}), do: Enum.flat_map(musts, &search_tag_name(&1)) - defp search_tag_names(%{bool: %{should: shoulds}}), do: Enum.flat_map(shoulds, &search_tag_name(&1)) + + defp search_tag_names(%{bool: %{should: shoulds}}), + do: Enum.flat_map(shoulds, &search_tag_name(&1)) + defp search_tag_names(%{term: %{"namespaced_tags.name" => tag_name}}), do: [tag_name] defp search_tag_names(_other_query), do: [] defp load_tags([]), do: [] + defp load_tags(tags) do Tag |> join(:left, [t], at in Tag, on: t.id == at.aliased_tag_id) |> where([t, at], t.name in ^tags or at.name in ^tags) - |> preload([:aliases, :aliased_tag, :implied_tags, :implied_by_tags, :dnp_entries, public_links: :user, hidden_links: :user]) + |> preload([ + :aliases, + :aliased_tag, + :implied_tags, + :implied_by_tags, + :dnp_entries, + public_links: :user, + hidden_links: :user + ]) |> Repo.all() |> Enum.uniq_by(& &1.id) |> Enum.filter(&is_nil(&1.aliased_tag)) @@ -119,17 +132,17 @@ defmodule PhilomenaWeb.ImageLoader do end defp render_bodies([], _conn), do: [] + defp render_bodies([tag], conn) do dnp_bodies = Renderer.render_collection(Enum.map(tag.dnp_entries, &%{body: &1.conditions || ""}), conn) - dnp_entries = - Enum.zip(dnp_bodies, tag.dnp_entries) + dnp_entries = Enum.zip(dnp_bodies, tag.dnp_entries) - description = - Renderer.render_one(%{body: tag.description || ""}, conn) + description = Renderer.render_one(%{body: tag.description || ""}, conn) [{tag, description, dnp_entries}] end + defp render_bodies(tags, _conn), do: tags end diff --git a/lib/philomena_web/image_reverse.ex b/lib/philomena_web/image_reverse.ex index 039eefcc..62274817 100644 --- a/lib/philomena_web/image_reverse.ex +++ b/lib/philomena_web/image_reverse.ex @@ -29,9 +29,11 @@ defmodule PhilomenaWeb.ImageReverse do {:ok, analysis} = Analyzers.analyze(path) {analysis, path} end + defp analyze(_upload), do: :error defp intensities(:error), do: :error + defp intensities({analysis, path}) do {analysis, Processors.intensities(analysis, path)} end @@ -44,5 +46,6 @@ defmodule PhilomenaWeb.ImageReverse do |> max(0.01) |> min(1.0) end + defp normalize_dist(_dist), do: 0.25 end diff --git a/lib/philomena_web/mailer.ex b/lib/philomena_web/mailer.ex index 2dcf9a24..1bde668c 100644 --- a/lib/philomena_web/mailer.ex +++ b/lib/philomena_web/mailer.ex @@ -1,3 +1,3 @@ defmodule PhilomenaWeb.Mailer do use Bamboo.Mailer, otp_app: :philomena -end \ No newline at end of file +end diff --git a/lib/philomena_web/plugs/admin_counters_plug.ex b/lib/philomena_web/plugs/admin_counters_plug.ex index 24462f29..480bc692 100644 --- a/lib/philomena_web/plugs/admin_counters_plug.ex +++ b/lib/philomena_web/plugs/admin_counters_plug.ex @@ -29,6 +29,7 @@ defmodule PhilomenaWeb.AdminCountersPlug do end defp maybe_assign_admin_metrics(conn, _user, false), do: conn + defp maybe_assign_admin_metrics(conn, user, true) do duplicate_reports = DuplicateReports.count_duplicate_reports(user) reports = Reports.count_reports(user) diff --git a/lib/philomena_web/plugs/advert_plug.ex b/lib/philomena_web/plugs/advert_plug.ex index 09246743..c45ae20c 100644 --- a/lib/philomena_web/plugs/advert_plug.ex +++ b/lib/philomena_web/plugs/advert_plug.ex @@ -15,13 +15,16 @@ defmodule PhilomenaWeb.AdvertPlug do defp maybe_assign_ad(conn, nil, true), do: Conn.assign(conn, :advert, Adverts.random_live()) + defp maybe_assign_ad(conn, image, true), do: Conn.assign(conn, :advert, Adverts.random_live_for(image)) + defp maybe_assign_ad(conn, _image, _false), do: conn defp show_ads?(%{hide_advertisements: false}), do: true + defp show_ads?(_user), do: true -end \ No newline at end of file +end diff --git a/lib/philomena_web/plugs/api_token_plug.ex b/lib/philomena_web/plugs/api_token_plug.ex index 5d61c67f..087f912b 100644 --- a/lib/philomena_web/plugs/api_token_plug.ex +++ b/lib/philomena_web/plugs/api_token_plug.ex @@ -11,6 +11,7 @@ defmodule PhilomenaWeb.ApiTokenPlug do end defp maybe_find_user(conn, nil), do: {conn, nil} + defp maybe_find_user(conn, key) do user = Users.get_by(authentication_token: key) diff --git a/lib/philomena_web/plugs/canary_map_plug.ex b/lib/philomena_web/plugs/canary_map_plug.ex index 7372b6a6..2f07f3ae 100644 --- a/lib/philomena_web/plugs/canary_map_plug.ex +++ b/lib/philomena_web/plugs/canary_map_plug.ex @@ -5,13 +5,14 @@ defmodule PhilomenaWeb.CanaryMapPlug do def call(conn, opts) do phx_action = conn.private.phoenix_action + canary_action = case Keyword.fetch(opts, phx_action) do {:ok, action} -> action - _ -> phx_action + _ -> phx_action end conn |> assign(:canary_action, canary_action) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/plugs/captcha_plug.ex b/lib/philomena_web/plugs/captcha_plug.ex index e2ef61d0..2b5772fa 100644 --- a/lib/philomena_web/plugs/captcha_plug.ex +++ b/lib/philomena_web/plugs/captcha_plug.ex @@ -14,13 +14,19 @@ defmodule PhilomenaWeb.CaptchaPlug do defp maybe_check_captcha(conn, nil) do case Captcha.valid_solution?(conn.params) do - true -> conn + true -> + conn + false -> conn - |> Controller.put_flash(:error, "There was an error verifying you're not a robot. Please try again.") + |> Controller.put_flash( + :error, + "There was an error verifying you're not a robot. Please try again." + ) |> Controller.redirect(external: conn.assigns.referrer) |> Conn.halt() end end + defp maybe_check_captcha(conn, _user), do: conn end diff --git a/lib/philomena_web/plugs/channel_plug.ex b/lib/philomena_web/plugs/channel_plug.ex index 51d683d7..d736b241 100644 --- a/lib/philomena_web/plugs/channel_plug.ex +++ b/lib/philomena_web/plugs/channel_plug.ex @@ -15,4 +15,4 @@ defmodule PhilomenaWeb.ChannelPlug do conn |> Conn.assign(:live_channels, live_channels) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/plugs/content_security_policy_plug.ex b/lib/philomena_web/plugs/content_security_policy_plug.ex index f1d9607c..7fe0835b 100644 --- a/lib/philomena_web/plugs/content_security_policy_plug.ex +++ b/lib/philomena_web/plugs/content_security_policy_plug.ex @@ -7,14 +7,14 @@ defmodule PhilomenaWeb.ContentSecurityPolicyPlug do csp_value = "default-src 'self' #{cdn_uri}; object-src 'none'; " <> - "frame-ancestors 'none'; frame-src 'none'; form-action 'self'; " <> - "manifest-src 'self'; img-src 'self' data: #{cdn_uri} #{camo_uri}; " <> - "block-all-mixed-content" + "frame-ancestors 'none'; frame-src 'none'; form-action 'self'; " <> + "manifest-src 'self'; img-src 'self' data: #{cdn_uri} #{camo_uri}; " <> + "block-all-mixed-content" [csp_value: csp_value] end - def call(conn, [csp_value: csp_value]) do + def call(conn, csp_value: csp_value) do Conn.put_resp_header(conn, "content-security-policy", csp_value) end @@ -23,4 +23,4 @@ defmodule PhilomenaWeb.ContentSecurityPolicyPlug do defp to_uri(host) when host in [nil, ""], do: "" defp to_uri(host), do: URI.to_string(%URI{scheme: "https", host: host}) -end \ No newline at end of file +end diff --git a/lib/philomena_web/plugs/current_ban_plug.ex b/lib/philomena_web/plugs/current_ban_plug.ex index 4dccde3f..db7837c0 100644 --- a/lib/philomena_web/plugs/current_ban_plug.ex +++ b/lib/philomena_web/plugs/current_ban_plug.ex @@ -29,4 +29,4 @@ defmodule PhilomenaWeb.CurrentBanPlug do Conn.assign(conn, :current_ban, ban) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/plugs/current_filter_plug.ex b/lib/philomena_web/plugs/current_filter_plug.ex index e714a4b0..296061e7 100644 --- a/lib/philomena_web/plugs/current_filter_plug.ex +++ b/lib/philomena_web/plugs/current_filter_plug.ex @@ -21,7 +21,7 @@ defmodule PhilomenaWeb.CurrentFilterPlug do else filter_id = conn |> get_session(:filter_id) - filter = if filter_id, do: Repo.get(Filter, filter_id) + filter = if filter_id, do: Repo.get(Filter, filter_id) filter || Filters.default_filter() end @@ -40,5 +40,6 @@ defmodule PhilomenaWeb.CurrentFilterPlug do Map.put(user, :current_filter, filter) end + defp maybe_set_default_filter(user), do: user end diff --git a/lib/philomena_web/plugs/ensure_user_enabled_plug.ex b/lib/philomena_web/plugs/ensure_user_enabled_plug.ex index 1ae54e8b..8e5f5d9e 100644 --- a/lib/philomena_web/plugs/ensure_user_enabled_plug.ex +++ b/lib/philomena_web/plugs/ensure_user_enabled_plug.ex @@ -33,5 +33,6 @@ defmodule PhilomenaWeb.EnsureUserEnabledPlug do conn |> Controller.redirect(to: Routes.pow_session_path(conn, :new)) end + defp maybe_halt(_any, conn), do: conn end diff --git a/lib/philomena_web/plugs/filter_banned_users_plug.ex b/lib/philomena_web/plugs/filter_banned_users_plug.ex index 989edb71..4e9a8242 100644 --- a/lib/philomena_web/plugs/filter_banned_users_plug.ex +++ b/lib/philomena_web/plugs/filter_banned_users_plug.ex @@ -25,6 +25,7 @@ defmodule PhilomenaWeb.FilterBannedUsersPlug do end defp maybe_halt(nil, conn, _redirect_url), do: conn + defp maybe_halt(_current_ban, conn, redirect_url) do conn |> Controller.put_flash(:error, "You are currently banned.") @@ -33,6 +34,7 @@ defmodule PhilomenaWeb.FilterBannedUsersPlug do end defp maybe_halt_no_fingerprint(%{halted: true} = conn), do: conn + defp maybe_halt_no_fingerprint(conn) do conn = Conn.fetch_cookies(conn) diff --git a/lib/philomena_web/plugs/filter_id_plug.ex b/lib/philomena_web/plugs/filter_id_plug.ex index 8e1851dd..501c953f 100644 --- a/lib/philomena_web/plugs/filter_id_plug.ex +++ b/lib/philomena_web/plugs/filter_id_plug.ex @@ -10,11 +10,11 @@ defmodule PhilomenaWeb.FilterIdPlug do user = conn.assigns.current_user case not is_nil(filter) and Canada.Can.can?(user, :show, filter) do - true -> Plug.Conn.assign(conn, :current_filter, filter) + true -> Plug.Conn.assign(conn, :current_filter, filter) false -> conn end end defp load_filter(%{"filter_id" => filter_id}), do: Repo.get(Filter, filter_id) defp load_filter(_params), do: nil -end \ No newline at end of file +end diff --git a/lib/philomena_web/plugs/filter_select_plug.ex b/lib/philomena_web/plugs/filter_select_plug.ex index 64471837..9a2318ee 100644 --- a/lib/philomena_web/plugs/filter_select_plug.ex +++ b/lib/philomena_web/plugs/filter_select_plug.ex @@ -35,6 +35,7 @@ defmodule PhilomenaWeb.FilterSelectPlug do end defp maybe_assign_filters(conn, nil), do: conn + defp maybe_assign_filters(conn, user) do filters = Filters.recent_and_user_filters(user) user = Users.change_user(user) @@ -44,4 +45,4 @@ defmodule PhilomenaWeb.FilterSelectPlug do |> Conn.assign(:available_filters, filters) |> Conn.assign(:spoiler_types, @spoiler_types) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/plugs/forum_list_plug.ex b/lib/philomena_web/plugs/forum_list_plug.ex index 6f7726b5..b74bb762 100644 --- a/lib/philomena_web/plugs/forum_list_plug.ex +++ b/lib/philomena_web/plugs/forum_list_plug.ex @@ -22,4 +22,4 @@ defmodule PhilomenaWeb.ForumListPlug do |> Repo.all() |> Enum.filter(&Can.can?(user, :show, &1)) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/plugs/load_comment_plug.ex b/lib/philomena_web/plugs/load_comment_plug.ex index b7ae7191..c1b869e1 100644 --- a/lib/philomena_web/plugs/load_comment_plug.ex +++ b/lib/philomena_web/plugs/load_comment_plug.ex @@ -28,7 +28,7 @@ defmodule PhilomenaWeb.LoadCommentPlug do defp maybe_hide_comment(comment, %{assigns: %{current_user: user}} = conn, show_hidden) do case show_hidden or can?(user, :show, comment) do - true -> assign(conn, :comment, comment) + true -> assign(conn, :comment, comment) false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/plugs/load_poll_plug.ex b/lib/philomena_web/plugs/load_poll_plug.ex index 143f59cc..5bbfd257 100644 --- a/lib/philomena_web/plugs/load_poll_plug.ex +++ b/lib/philomena_web/plugs/load_poll_plug.ex @@ -26,7 +26,7 @@ defmodule PhilomenaWeb.LoadPollPlug do defp maybe_hide_poll(poll, %{assigns: %{current_user: user}} = conn, show_hidden) do case show_hidden or can?(user, :show, poll) do - true -> assign(conn, :poll, poll) + true -> assign(conn, :poll, poll) false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/plugs/load_post_plug.ex b/lib/philomena_web/plugs/load_post_plug.ex index 60dec97a..aa479c9d 100644 --- a/lib/philomena_web/plugs/load_post_plug.ex +++ b/lib/philomena_web/plugs/load_post_plug.ex @@ -15,7 +15,7 @@ defmodule PhilomenaWeb.LoadPostPlug do Post |> where(topic_id: ^topic.id, id: ^to_string(conn.params[param])) - |> preload([topic: :forum, user: [awards: :badge]]) + |> preload(topic: :forum, user: [awards: :badge]) |> Repo.one() |> maybe_hide_post(conn, show_hidden) end @@ -28,7 +28,7 @@ defmodule PhilomenaWeb.LoadPostPlug do defp maybe_hide_post(post, %{assigns: %{current_user: user}} = conn, show_hidden) do case show_hidden or can?(user, :show, post) do - true -> assign(conn, :post, post) + true -> assign(conn, :post, post) false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/plugs/load_topic_plug.ex b/lib/philomena_web/plugs/load_topic_plug.ex index 63642b4c..7e238535 100644 --- a/lib/philomena_web/plugs/load_topic_plug.ex +++ b/lib/philomena_web/plugs/load_topic_plug.ex @@ -28,7 +28,7 @@ defmodule PhilomenaWeb.LoadTopicPlug do defp maybe_hide_topic(topic, %{assigns: %{current_user: user}} = conn, show_hidden) do case show_hidden or can?(user, :show, topic) do - true -> assign(conn, :topic, topic) + true -> assign(conn, :topic, topic) false -> PhilomenaWeb.NotAuthorizedPlug.call(conn) end end diff --git a/lib/philomena_web/plugs/not_authorized_plug.ex b/lib/philomena_web/plugs/not_authorized_plug.ex index d0a99b4e..382551bb 100644 --- a/lib/philomena_web/plugs/not_authorized_plug.ex +++ b/lib/philomena_web/plugs/not_authorized_plug.ex @@ -5,6 +5,7 @@ defmodule PhilomenaWeb.NotAuthorizedPlug do def init([]), do: [] def call(conn), do: call(conn, nil) + def call(conn, _opts) do conn |> Controller.fetch_flash() diff --git a/lib/philomena_web/plugs/not_found_plug.ex b/lib/philomena_web/plugs/not_found_plug.ex index 364dc627..8f169d0c 100644 --- a/lib/philomena_web/plugs/not_found_plug.ex +++ b/lib/philomena_web/plugs/not_found_plug.ex @@ -5,6 +5,7 @@ defmodule PhilomenaWeb.NotFoundPlug do def init([]), do: [] def call(conn), do: call(conn, nil) + def call(conn, _opts) do conn |> Controller.fetch_flash() diff --git a/lib/philomena_web/plugs/notification_count_plug.ex b/lib/philomena_web/plugs/notification_count_plug.ex index cb0a3d75..e970fae4 100644 --- a/lib/philomena_web/plugs/notification_count_plug.ex +++ b/lib/philomena_web/plugs/notification_count_plug.ex @@ -30,6 +30,7 @@ defmodule PhilomenaWeb.NotificationCountPlug do end defp maybe_assign_notifications(conn, nil), do: conn + defp maybe_assign_notifications(conn, user) do notifications = Notifications.count_unread_notifications(user) @@ -38,10 +39,11 @@ defmodule PhilomenaWeb.NotificationCountPlug do end defp maybe_assign_conversations(conn, nil), do: conn + defp maybe_assign_conversations(conn, user) do conversations = Conversations.count_unread_conversations(user) conn |> Conn.assign(:conversation_count, conversations) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/plugs/pagination_plug.ex b/lib/philomena_web/plugs/pagination_plug.ex index 05f37e9d..59b1f6b4 100644 --- a/lib/philomena_web/plugs/pagination_plug.ex +++ b/lib/philomena_web/plugs/pagination_plug.ex @@ -19,13 +19,14 @@ defmodule PhilomenaWeb.PaginationPlug do conn |> assign(:pagination, %{page_number: page_number, page_size: page_size || 25}) |> assign(:image_pagination, %{page_number: page_number, page_size: image_page_size}) - |> assign(:scrivener, [page: page_number, page_size: page_size || 25]) - |> assign(:comment_scrivener, [page: page_number, page_size: comment_page_size]) + |> assign(:scrivener, page: page_number, page_size: page_size || 25) + |> assign(:comment_scrivener, page: page_number, page_size: comment_page_size) end defp get_page_number(%{"page" => page}) do to_integer(page) || 1 end + defp get_page_number(_params), do: 1 defp get_page_size(%{"per_page" => per_page}) do @@ -35,6 +36,7 @@ defmodule PhilomenaWeb.PaginationPlug do |> max(1) |> min(50) end + defp get_page_size(_params), do: nil defp to_integer(string) do diff --git a/lib/philomena_web/plugs/recode_parameter_plug.ex b/lib/philomena_web/plugs/recode_parameter_plug.ex index 9a5f6bbb..0cd5c0c4 100644 --- a/lib/philomena_web/plugs/recode_parameter_plug.ex +++ b/lib/philomena_web/plugs/recode_parameter_plug.ex @@ -1,7 +1,7 @@ defmodule PhilomenaWeb.RecodeParameterPlug do def init(opts), do: opts - def call(conn, [name: name]) do + def call(conn, name: name) do fixed_value = conn |> Map.get(:params) @@ -15,4 +15,4 @@ defmodule PhilomenaWeb.RecodeParameterPlug do %{conn | params: params} end -end \ No newline at end of file +end diff --git a/lib/philomena_web/plugs/referrer_plug.ex b/lib/philomena_web/plugs/referrer_plug.ex index e46fbc03..bef81917 100644 --- a/lib/philomena_web/plugs/referrer_plug.ex +++ b/lib/philomena_web/plugs/referrer_plug.ex @@ -27,4 +27,4 @@ defmodule PhilomenaWeb.ReferrerPlug do |> Conn.assign(:referrer, referrer) end end -end \ No newline at end of file +end diff --git a/lib/philomena_web/plugs/scraper_plug.ex b/lib/philomena_web/plugs/scraper_plug.ex index a094ec9f..56ac0cc1 100644 --- a/lib/philomena_web/plugs/scraper_plug.ex +++ b/lib/philomena_web/plugs/scraper_plug.ex @@ -26,20 +26,18 @@ defmodule PhilomenaWeb.ScraperPlug do File.write!(file, body) - fake_upload = - %Plug.Upload{ - path: file, - content_type: "application/octet-stream", - filename: "scraper-#{now}" - } + fake_upload = %Plug.Upload{ + path: file, + content_type: "application/octet-stream", + filename: "scraper-#{now}" + } - updated_form = - Map.put(conn.params[params_name], params_key, fake_upload) + updated_form = Map.put(conn.params[params_name], params_key, fake_upload) - updated_params = - Map.put(conn.params, params_name, updated_form) + updated_params = Map.put(conn.params, params_name, updated_form) %{conn | params: updated_params} end + defp maybe_fixup_params(_response, _opts, conn), do: conn end diff --git a/lib/philomena_web/plugs/site_notice_plug.ex b/lib/philomena_web/plugs/site_notice_plug.ex index 781d9ba0..30aaa586 100644 --- a/lib/philomena_web/plugs/site_notice_plug.ex +++ b/lib/philomena_web/plugs/site_notice_plug.ex @@ -22,4 +22,4 @@ defmodule PhilomenaWeb.SiteNoticePlug do conn |> Conn.assign(:site_notices, notices) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/plugs/tor_plug.ex b/lib/philomena_web/plugs/tor_plug.ex index 11541e02..9372467b 100644 --- a/lib/philomena_web/plugs/tor_plug.ex +++ b/lib/philomena_web/plugs/tor_plug.ex @@ -29,6 +29,7 @@ defmodule PhilomenaWeb.TorPlug do |> Controller.redirect(to: Routes.pow_session_path(conn, :new)) |> Conn.halt() end + def maybe_redirect(conn, _user, _ip, _onion?), do: conn # This is allowed, because nginx won't forward the request diff --git a/lib/philomena_web/plugs/totp_plug.ex b/lib/philomena_web/plugs/totp_plug.ex index b9ea20ef..c0511ed9 100644 --- a/lib/philomena_web/plugs/totp_plug.ex +++ b/lib/philomena_web/plugs/totp_plug.ex @@ -19,13 +19,14 @@ defmodule PhilomenaWeb.TotpPlug do conn |> Pow.Plug.current_user() |> case do - nil -> conn + nil -> conn user -> maybe_require_totp_phase(user, conn) end end - + defp maybe_require_totp_phase(%{otp_required_for_login: nil}, conn), do: conn defp maybe_require_totp_phase(%{otp_required_for_login: false}, conn), do: conn + defp maybe_require_totp_phase(_user, conn) do conn.private |> Map.get(:pow_session_metadata, []) @@ -50,14 +51,16 @@ defmodule PhilomenaWeb.TotpPlug do |> Keyword.put(:valid_totp_at, DateTime.utc_now()) config = Pow.Plug.fetch_config(conn) - plug = Pow.Plug.get_plug(config) - conn = Plug.Conn.put_private(conn, :pow_session_metadata, metadata) + plug = Pow.Plug.get_plug(config) + conn = Plug.Conn.put_private(conn, :pow_session_metadata, metadata) conn = conn - |> Plug.Conn.put_private(:pow_persistent_session_metadata, session_metadata: Keyword.take(metadata, [:valid_totp_at])) + |> Plug.Conn.put_private(:pow_persistent_session_metadata, + session_metadata: Keyword.take(metadata, [:valid_totp_at]) + ) |> PowPersistentSession.Plug.Cookie.create(user, config) plug.do_create(conn, user, config) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/plugs/user_attribution_plug.ex b/lib/philomena_web/plugs/user_attribution_plug.ex index e223694b..f7daa0f1 100644 --- a/lib/philomena_web/plugs/user_attribution_plug.ex +++ b/lib/philomena_web/plugs/user_attribution_plug.ex @@ -21,14 +21,13 @@ defmodule PhilomenaWeb.UserAttributionPlug do conn = Conn.fetch_cookies(conn) user = Pow.Plug.current_user(conn) - attributes = - [ - ip: remote_ip, - fingerprint: conn.cookies["_ses"], - referrer: conn.assigns.referrer, - user: user, - user_agent: user_agent(conn) - ] + attributes = [ + ip: remote_ip, + fingerprint: conn.cookies["_ses"], + referrer: conn.assigns.referrer, + user: user, + user_agent: user_agent(conn) + ] conn |> Conn.assign(:attributes, attributes) @@ -37,7 +36,7 @@ defmodule PhilomenaWeb.UserAttributionPlug do defp user_agent(conn) do case Conn.get_req_header(conn, "user-agent") do [ua] -> ua - _ -> nil + _ -> nil end end -end \ No newline at end of file +end diff --git a/lib/philomena_web/post_json.ex b/lib/philomena_web/post_json.ex index 92f8ac83..1403f23c 100644 --- a/lib/philomena_web/post_json.ex +++ b/lib/philomena_web/post_json.ex @@ -9,19 +9,29 @@ defmodule PhilomenaWeb.PostJson do body: nil } end + def as_json(%{hidden_from_users: true} = post) do %{ id: post.id, user_id: if(not post.anonymous, do: post.user_id), - author: if(post.anonymous or is_nil(post.user), do: UserAttributionView.anonymous_name(post), else: post.user.name), + author: + if(post.anonymous or is_nil(post.user), + do: UserAttributionView.anonymous_name(post), + else: post.user.name + ), body: nil } end + def as_json(post) do %{ id: post.id, user_id: if(not post.anonymous, do: post.user_id), - author: if(post.anonymous or is_nil(post.user), do: UserAttributionView.anonymous_name(post), else: post.user.name), + author: + if(post.anonymous or is_nil(post.user), + do: UserAttributionView.anonymous_name(post), + else: post.user.name + ), body: post.body } end diff --git a/lib/philomena_web/pow_mailer.ex b/lib/philomena_web/pow_mailer.ex index 73b40551..1fb8b078 100644 --- a/lib/philomena_web/pow_mailer.ex +++ b/lib/philomena_web/pow_mailer.ex @@ -4,7 +4,13 @@ defmodule PhilomenaWeb.PowMailer do alias Philomena.Users.User import Bamboo.Email - def cast(%{user: %User{email: email}, subject: subject, text: text, html: html, assigns: _assigns}) do + def cast(%{ + user: %User{email: email}, + subject: subject, + text: text, + html: html, + assigns: _assigns + }) do # Build email struct to be used in `process/1` new_email( to: email, @@ -19,4 +25,4 @@ defmodule PhilomenaWeb.PowMailer do email |> Mailer.deliver_later() end -end \ No newline at end of file +end diff --git a/lib/philomena_web/router.ex b/lib/philomena_web/router.ex index d79e1b41..d82efc39 100644 --- a/lib/philomena_web/router.ex +++ b/lib/philomena_web/router.ex @@ -95,9 +95,11 @@ defmodule PhilomenaWeb.Router do scope "/api/v1/json", PhilomenaWeb.Api.Json, as: :api_json do pipe_through [:accepts_json, :api, :ensure_tor_authorized] + scope "/images", Image, as: :image do resources "/featured", FeaturedController, only: [:show], singleton: true end + resources "/images", ImageController, only: [:show] scope "/search", Search, as: :search do @@ -116,6 +118,7 @@ defmodule PhilomenaWeb.Router do resources "/tags", TagController, only: [:show] resources "/comments", CommentController, only: [:show] resources "/posts", PostController, only: [:show] + resources "/forums", ForumController, only: [:show, :index] do resources "/topics", Forum.TopicController, only: [:show, :index] do resources "/posts", Forum.Topic.PostController, only: [:show, :index] @@ -129,23 +132,32 @@ defmodule PhilomenaWeb.Router do scope "/notifications", Notification, as: :notification do resources "/unread", UnreadController, only: [:index] end + resources "/notifications", NotificationController, only: [:index, :delete] + resources "/conversations", ConversationController, only: [:index, :show, :new, :create] do resources "/reports", Conversation.ReportController, only: [:new, :create] resources "/messages", Conversation.MessageController, only: [:create] resources "/read", Conversation.ReadController, only: [:create, :delete], singleton: true resources "/hide", Conversation.HideController, only: [:create, :delete], singleton: true end + resources "/images", ImageController, only: [] do resources "/vote", Image.VoteController, only: [:create, :delete], singleton: true resources "/fave", Image.FaveController, only: [:create, :delete], singleton: true resources "/hide", Image.HideController, only: [:create, :delete], singleton: true - resources "/subscription", Image.SubscriptionController, only: [:create, :delete], singleton: true + + resources "/subscription", Image.SubscriptionController, + only: [:create, :delete], + singleton: true + resources "/read", Image.ReadController, only: [:create], singleton: true + resources "/comments", Image.CommentController, only: [:edit, :update] do resources "/hide", Image.Comment.HideController, only: [:create, :delete], singleton: true resources "/delete", Image.Comment.DeleteController, only: [:create], singleton: true end + resources "/delete", Image.DeleteController, only: [:create, :delete], singleton: true resources "/tamper", Image.TamperController, only: [:create], singleton: true @@ -157,37 +169,64 @@ defmodule PhilomenaWeb.Router do resources "/scratchpad", Image.ScratchpadController, only: [:edit, :update], singleton: true resources "/uploader", Image.UploaderController, only: [:update], singleton: true - resources "/comment_lock", Image.CommentLockController, only: [:create, :delete], singleton: true - resources "/description_lock", Image.DescriptionLockController, only: [:create, :delete], singleton: true + resources "/comment_lock", Image.CommentLockController, + only: [:create, :delete], + singleton: true + + resources "/description_lock", Image.DescriptionLockController, + only: [:create, :delete], + singleton: true + resources "/tag_lock", Image.TagLockController, only: [:create, :delete], singleton: true end resources "/forums", ForumController, only: [] do resources "/topics", TopicController, only: [:new, :create] do - resources "/subscription", Topic.SubscriptionController, only: [:create, :delete], singleton: true + resources "/subscription", Topic.SubscriptionController, + only: [:create, :delete], + singleton: true + resources "/read", Topic.ReadController, only: [:create], singleton: true resources "/move", Topic.MoveController, only: [:create], singleton: true resources "/stick", Topic.StickController, only: [:create, :delete], singleton: true resources "/lock", Topic.LockController, only: [:create, :delete], singleton: true resources "/hide", Topic.HideController, only: [:create, :delete], singleton: true + resources "/posts", Topic.PostController, only: [:edit, :update] do resources "/hide", Topic.Post.HideController, only: [:create, :delete], singleton: true resources "/delete", Topic.Post.DeleteController, only: [:create], singleton: true end - resources "/poll/votes", Topic.Poll.VoteController, as: :poll_vote, only: [:index, :create, :delete] + + resources "/poll/votes", Topic.Poll.VoteController, + as: :poll_vote, + only: [:index, :create, :delete] end - resources "/subscription", Forum.SubscriptionController, only: [:create, :delete], singleton: true + resources "/subscription", Forum.SubscriptionController, + only: [:create, :delete], + singleton: true + resources "/read", Forum.ReadController, only: [:create], singleton: true end resources "/profiles", ProfileController, only: [] do - resources "/commission", Profile.CommissionController, only: [:new, :create, :edit, :update, :delete], singleton: true do - resources "/items", Profile.Commission.ItemController, only: [:new, :create, :edit, :update, :delete] + resources "/commission", Profile.CommissionController, + only: [:new, :create, :edit, :update, :delete], + singleton: true do + resources "/items", Profile.Commission.ItemController, + only: [:new, :create, :edit, :update, :delete] + resources "/reports", Profile.Commission.ReportController, only: [:new, :create] end - resources "/description", Profile.DescriptionController, only: [:edit, :update], singleton: true - resources "/scratchpad", Profile.ScratchpadController, only: [:edit, :update], singleton: true + + resources "/description", Profile.DescriptionController, + only: [:edit, :update], + singleton: true + + resources "/scratchpad", Profile.ScratchpadController, + only: [:edit, :update], + singleton: true + resources "/user_links", Profile.UserLinkController resources "/awards", Profile.AwardController, except: [:index, :show] @@ -211,16 +250,23 @@ defmodule PhilomenaWeb.Router do resources "/avatar", AvatarController, only: [:edit, :update, :delete], singleton: true resources "/reports", ReportController, only: [:index] + resources "/galleries", GalleryController, only: [:new, :create, :edit, :update, :delete] do resources "/images", Gallery.ImageController, only: [:create, :delete], singleton: true resources "/order", Gallery.OrderController, only: [:update], singleton: true resources "/read", Gallery.ReadController, only: [:create], singleton: true - resources "/subscription", Gallery.SubscriptionController, only: [:create, :delete], singleton: true + + resources "/subscription", Gallery.SubscriptionController, + only: [:create, :delete], + singleton: true end resources "/channels", ChannelController, only: [] do resources "/read", Channel.ReadController, only: [:create], singleton: true - resources "/subscription", Channel.SubscriptionController, only: [:create, :delete], singleton: true + + resources "/subscription", Channel.SubscriptionController, + only: [:create, :delete], + singleton: true end resources "/dnp", DnpEntryController, only: [:new, :create, :edit, :update] @@ -229,6 +275,7 @@ defmodule PhilomenaWeb.Router do resources "/tag_changes", IpProfile.TagChangeController, only: [:index] resources "/source_changes", IpProfile.SourceChangeController, only: [:index] end + resources "/fingerprint_profiles", FingerprintProfileController, only: [:show] do resources "/tag_changes", FingerprintProfile.TagChangeController, only: [:index] resources "/source_changes", FingerprintProfile.SourceChangeController, only: [:index] @@ -241,7 +288,10 @@ defmodule PhilomenaWeb.Router do end resources "/user_links", UserLinkController, only: [:index] do - resources "/verification", UserLink.VerificationController, only: [:create], singleton: true + resources "/verification", UserLink.VerificationController, + only: [:create], + singleton: true + resources "/contact", UserLink.ContactController, only: [:create], singleton: true resources "/reject", UserLink.RejectController, only: [:create], singleton: true end @@ -250,21 +300,33 @@ defmodule PhilomenaWeb.Router do resources "/transition", DnpEntry.TransitionController, only: [:create], singleton: true end - resources "/user_bans", UserBanController, only: [:index, :new, :create, :edit, :update, :delete] - resources "/subnet_bans", SubnetBanController, only: [:index, :new, :create, :edit, :update, :delete] - resources "/fingerprint_bans", FingerprintBanController, only: [:index, :new, :create, :edit, :update, :delete] + resources "/user_bans", UserBanController, + only: [:index, :new, :create, :edit, :update, :delete] + + resources "/subnet_bans", SubnetBanController, + only: [:index, :new, :create, :edit, :update, :delete] + + resources "/fingerprint_bans", FingerprintBanController, + only: [:index, :new, :create, :edit, :update, :delete] resources "/site_notices", SiteNoticeController, except: [:show] resources "/adverts", AdvertController, except: [:show] resources "/forums", ForumController, except: [:show, :delete] + resources "/badges", BadgeController, except: [:show, :delete] do resources "/users", Badge.UserController, only: [:index] end + resources "/mod_notes", ModNoteController, except: [:show] + resources "/users", UserController, only: [:index, :edit, :update] do resources "/avatar", User.AvatarController, only: [:delete], singleton: true - resources "/activation", User.ActivationController, only: [:create, :delete], singleton: true + + resources "/activation", User.ActivationController, + only: [:create, :delete], + singleton: true + resources "/api_key", User.ApiKeyController, only: [:delete], singleton: true resources "/downvotes", User.DownvoteController, only: [:delete], singleton: true resources "/votes", User.VoteController, only: [:delete], singleton: true @@ -272,17 +334,26 @@ defmodule PhilomenaWeb.Router do end resources "/batch/tags", Batch.TagController, only: [:update], singleton: true + scope "/donations", Donation, as: :donation do resources "/user", UserController, only: [:show] end + resources "/donations", DonationController, only: [:index, :create] end resources "/duplicate_reports", DuplicateReportController, only: [] do resources "/accept", DuplicateReport.AcceptController, only: [:create], singleton: true - resources "/accept_reverse", DuplicateReport.AcceptReverseController, only: [:create], singleton: true + + resources "/accept_reverse", DuplicateReport.AcceptReverseController, + only: [:create], + singleton: true + resources "/reject", DuplicateReport.RejectController, only: [:create], singleton: true - resources "/claim", DuplicateReport.ClaimController, only: [:create, :delete], singleton: true + + resources "/claim", DuplicateReport.ClaimController, + only: [:create, :delete], + singleton: true end resources "/tags", TagController, only: [:edit, :update, :delete] do @@ -291,7 +362,10 @@ defmodule PhilomenaWeb.Router do resources "/reindex", Tag.ReindexController, only: [:create], singleton: true end - resources "/tag_changes/revert", TagChange.RevertController, as: :tag_change_revert, only: [:create], singleton: true + resources "/tag_changes/revert", TagChange.RevertController, + as: :tag_change_revert, + only: [:create], + singleton: true resources "/pages", PageController, only: [:index, :new, :create, :edit, :update] resources "/channels", ChannelController, only: [:new, :create, :edit, :update] @@ -303,16 +377,20 @@ defmodule PhilomenaWeb.Router do get "/", ActivityController, :index resources "/activity", ActivityController, only: [:index] + scope "/images", Image, as: :image do resources "/scrape", ScrapeController, only: [:create] resources "/random", RandomController, only: [:index] end + resources "/images", ImageController, only: [:index, :show, :new, :create] do resources "/related", Image.RelatedController, only: [:index] + resources "/comments", Image.CommentController, only: [:index, :show, :create] do resources "/reports", Image.Comment.ReportController, only: [:new, :create] resources "/history", Image.Comment.HistoryController, only: [:index] end + resources "/tags", Image.TagController, only: [:update], singleton: true resources "/sources", Image.SourceController, only: [:update], singleton: true resources "/tag_changes", Image.TagChangeController, only: [:index] @@ -323,17 +401,22 @@ defmodule PhilomenaWeb.Router do resources "/reporting", Image.ReportingController, only: [:show], singleton: true resources "/favorites", Image.FavoriteController, only: [:index] end + scope "/tags", Tag, as: :tag do resources "/autocomplete", AutocompleteController, only: [:show], singleton: true resources "/fetch", FetchController, only: [:index] end + resources "/tags", TagController, only: [:index, :show] do resources "/tag_changes", Tag.TagChangeController, only: [:index] end + scope "/search", Search, as: :search do resources "/reverse", ReverseController, only: [:index, :create] end + resources "/search", SearchController, only: [:index] + resources "/forums", ForumController, only: [:index, :show] do resources "/topics", TopicController, only: [:show] do resources "/posts", Topic.PostController, only: [:create] do @@ -342,31 +425,41 @@ defmodule PhilomenaWeb.Router do end end end + resources "/comments", CommentController, only: [:index] scope "/filters", Filter, as: :filter do resources "/current", CurrentController, only: [:update], singleton: true end + resources "/filters", FilterController + resources "/profiles", ProfileController, only: [:show] do resources "/reports", Profile.ReportController, only: [:new, :create] resources "/commission", Profile.CommissionController, only: [:show], singleton: true resources "/tag_changes", Profile.TagChangeController, only: [:index] resources "/source_changes", Profile.SourceChangeController, only: [:index] end + resources "/captchas", CaptchaController, only: [:create] + scope "/posts", Post, as: :post do resources "/preview", PreviewController, only: [:create] end + resources "/posts", PostController, only: [:index] resources "/commissions", CommissionController, only: [:index] + resources "/galleries", GalleryController, only: [:index, :show] do resources "/reports", Gallery.ReportController, only: [:new, :create] end + resources "/adverts", AdvertController, only: [:show] + resources "/pages", PageController, only: [:show] do resources "/history", Page.HistoryController, only: [:index] end + resources "/dnp", DnpEntryController, only: [:index, :show] resources "/staff", StaffController, only: [:index] resources "/stats", StatController, only: [:index] diff --git a/lib/philomena_web/tag_json.ex b/lib/philomena_web/tag_json.ex index 83bb931e..c2d48cb8 100644 --- a/lib/philomena_web/tag_json.ex +++ b/lib/philomena_web/tag_json.ex @@ -25,10 +25,11 @@ defmodule PhilomenaWeb.TagJson do # TODO: copied from Tag.Fetch defp tag_image(%{image: image}) when image not in [nil, ""], do: tag_url_root() <> "/" <> image + defp tag_image(_other), do: nil defp tag_url_root do Application.get_env(:philomena, :tag_url_root) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/topic_json.ex b/lib/philomena_web/topic_json.ex index e1113122..daf0ddff 100644 --- a/lib/philomena_web/topic_json.ex +++ b/lib/philomena_web/topic_json.ex @@ -14,6 +14,7 @@ defmodule PhilomenaWeb.TopicJson do author: nil } end + def as_json(topic) do %{ slug: topic.slug, @@ -24,7 +25,11 @@ defmodule PhilomenaWeb.TopicJson do last_replied_to_at: topic.last_replied_to_at, locked: not is_nil(topic.locked_at), user_id: if(not topic.anonymous, do: topic.user.id), - author: if(topic.anonymous or is_nil(topic.user), do: UserAttributionView.anonymous_name(topic), else: topic.user.name) + author: + if(topic.anonymous or is_nil(topic.user), + do: UserAttributionView.anonymous_name(topic), + else: topic.user.name + ) } end end diff --git a/lib/philomena_web/views/admin/advert_view.ex b/lib/philomena_web/views/admin/advert_view.ex index ac4aabc2..ee4e35f0 100644 --- a/lib/philomena_web/views/admin/advert_view.ex +++ b/lib/philomena_web/views/admin/advert_view.ex @@ -10,7 +10,7 @@ defmodule PhilomenaWeb.Admin.AdvertView do now = DateTime.utc_now() case DateTime.diff(other_time, now) > 0 do - true -> "success" + true -> "success" _false -> "danger" end end diff --git a/lib/philomena_web/views/admin/dnp_entry_view.ex b/lib/philomena_web/views/admin/dnp_entry_view.ex index e9535278..859fc152 100644 --- a/lib/philomena_web/views/admin/dnp_entry_view.ex +++ b/lib/philomena_web/views/admin/dnp_entry_view.ex @@ -7,7 +7,10 @@ defmodule PhilomenaWeb.Admin.DnpEntryView do do: DnpEntryView.pretty_state(dnp_entry) def dnp_entry_row_class(%{aasm_state: state}) when state in ["closed", "listed"], do: "success" - def dnp_entry_row_class(%{aasm_state: state}) when state in ["claimed", "acknowledged"], do: "warning" + + def dnp_entry_row_class(%{aasm_state: state}) when state in ["claimed", "acknowledged"], + do: "warning" + def dnp_entry_row_class(_dnp_entry), do: "danger" def state_param(states) when is_list(states), do: states diff --git a/lib/philomena_web/views/admin/fingerprint_ban_view.ex b/lib/philomena_web/views/admin/fingerprint_ban_view.ex index c6c82c0b..e6f3eb87 100644 --- a/lib/philomena_web/views/admin/fingerprint_ban_view.ex +++ b/lib/philomena_web/views/admin/fingerprint_ban_view.ex @@ -10,7 +10,7 @@ defmodule PhilomenaWeb.Admin.FingerprintBanView do now = DateTime.utc_now() case enabled and DateTime.diff(until, now) > 0 do - true -> "success" + true -> "success" _false -> "danger" end end diff --git a/lib/philomena_web/views/admin/mod_note_view.ex b/lib/philomena_web/views/admin/mod_note_view.ex index 0e86e63e..7627598d 100644 --- a/lib/philomena_web/views/admin/mod_note_view.ex +++ b/lib/philomena_web/views/admin/mod_note_view.ex @@ -12,7 +12,10 @@ defmodule PhilomenaWeb.Admin.ModNoteView do do: link("Report #{report.id}", to: Routes.admin_report_path(conn, :show, report)) def link_to_noted_thing(conn, %Report{user: user} = report), - do: link("Report #{report.id} by #{user.name}", to: Routes.admin_report_path(conn, :show, report)) + do: + link("Report #{report.id} by #{user.name}", + to: Routes.admin_report_path(conn, :show, report) + ) def link_to_noted_thing(conn, %User{} = user), do: link("User #{user.name}", to: Routes.profile_path(conn, :show, user)) diff --git a/lib/philomena_web/views/admin/report_view.ex b/lib/philomena_web/views/admin/report_view.ex index a1615d85..a9cd5bcc 100644 --- a/lib/philomena_web/views/admin/report_view.ex +++ b/lib/philomena_web/views/admin/report_view.ex @@ -40,10 +40,20 @@ defmodule PhilomenaWeb.Admin.ReportView do end def reported_image(conn, %Image{} = image) do - render PhilomenaWeb.ImageView, "_image_container.html", image: image, size: :thumb_tiny, conn: conn + render(PhilomenaWeb.ImageView, "_image_container.html", + image: image, + size: :thumb_tiny, + conn: conn + ) end + def reported_image(conn, %Comment{image: image}) do - render PhilomenaWeb.ImageView, "_image_container.html", image: image, size: :thumb_tiny, conn: conn + render(PhilomenaWeb.ImageView, "_image_container.html", + image: image, + size: :thumb_tiny, + conn: conn + ) end + def reported_image(_conn, _reportable), do: nil end diff --git a/lib/philomena_web/views/admin/subnet_ban_view.ex b/lib/philomena_web/views/admin/subnet_ban_view.ex index 5190910f..00ae543b 100644 --- a/lib/philomena_web/views/admin/subnet_ban_view.ex +++ b/lib/philomena_web/views/admin/subnet_ban_view.ex @@ -10,7 +10,7 @@ defmodule PhilomenaWeb.Admin.SubnetBanView do now = DateTime.utc_now() case enabled and DateTime.diff(until, now) > 0 do - true -> "success" + true -> "success" _false -> "danger" end end diff --git a/lib/philomena_web/views/admin/user_ban_view.ex b/lib/philomena_web/views/admin/user_ban_view.ex index 12948daf..b8f34fb9 100644 --- a/lib/philomena_web/views/admin/user_ban_view.ex +++ b/lib/philomena_web/views/admin/user_ban_view.ex @@ -10,7 +10,7 @@ defmodule PhilomenaWeb.Admin.UserBanView do now = DateTime.utc_now() case enabled and DateTime.diff(until, now) > 0 do - true -> "success" + true -> "success" _false -> "danger" end end diff --git a/lib/philomena_web/views/admin/user_link_view.ex b/lib/philomena_web/views/admin/user_link_view.ex index 266e78fc..313256f5 100644 --- a/lib/philomena_web/views/admin/user_link_view.ex +++ b/lib/philomena_web/views/admin/user_link_view.ex @@ -6,8 +6,12 @@ defmodule PhilomenaWeb.Admin.UserLinkView do defp display_order(tags), do: Tag.display_order(tags) - def link_state_class(%{aasm_state: state}) when state in ["verified", "link_verified"], do: "success" - def link_state_class(%{aasm_state: state}) when state in ["unverified", "rejected"], do: "danger" + def link_state_class(%{aasm_state: state}) when state in ["verified", "link_verified"], + do: "success" + + def link_state_class(%{aasm_state: state}) when state in ["unverified", "rejected"], + do: "danger" + def link_state_class(%{aasm_state: "contacted"}), do: "warning" def link_state_class(_link), do: nil @@ -19,7 +23,7 @@ defmodule PhilomenaWeb.Admin.UserLinkView do def link_scope(conn) do case conn.params["all"] do - nil -> [] + nil -> [] _val -> [all: true] end end diff --git a/lib/philomena_web/views/admin/user_view.ex b/lib/philomena_web/views/admin/user_view.ex index dc8c9a3f..b655fa37 100644 --- a/lib/philomena_web/views/admin/user_view.ex +++ b/lib/philomena_web/views/admin/user_view.ex @@ -4,18 +4,22 @@ defmodule PhilomenaWeb.Admin.UserView do def checkbox_mapper(form, field, input_opts, role, _label_opts, _opts) do input_id = "user_roles_#{role.id}" label_opts = [for: input_id] + input_opts = - Keyword.merge(input_opts, [ - class: "checkbox", id: input_id, checked_value: to_string(role.id), hidden_input: false, + Keyword.merge(input_opts, + class: "checkbox", + id: input_id, + checked_value: to_string(role.id), + hidden_input: false, checked: Enum.member?(Enum.map(input_value(form, field), & &1.id), role.id) - ]) + ) content_tag(:li, class: "table-list__label") do content_tag(:div) do [ checkbox(form, field, input_opts), " ", - content_tag(:label, description(role.name, role.resource_type), label_opts), + content_tag(:label, description(role.name, role.resource_type), label_opts) ] end end diff --git a/lib/philomena_web/views/api/rss/watched_view.ex b/lib/philomena_web/views/api/rss/watched_view.ex index 0b4d7989..bfcdfa84 100644 --- a/lib/philomena_web/views/api/rss/watched_view.ex +++ b/lib/philomena_web/views/api/rss/watched_view.ex @@ -13,4 +13,4 @@ defmodule PhilomenaWeb.Api.Rss.WatchedView do |> ImageView.thumb_urls(false) |> Map.get(:medium) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/views/app_view.ex b/lib/philomena_web/views/app_view.ex index bb615e59..afe88721 100644 --- a/lib/philomena_web/views/app_view.ex +++ b/lib/philomena_web/views/app_view.ex @@ -38,7 +38,10 @@ defmodule PhilomenaWeb.AppView do words = distance_of_time_in_words(now, time) - content_tag(:time, "#{words} #{relation}", datetime: DateTime.to_iso8601(time), title: datetime_string(time)) + content_tag(:time, "#{words} #{relation}", + datetime: DateTime.to_iso8601(time), + title: datetime_string(time) + ) end def distance_of_time_in_words(time_2, time_1) do @@ -75,6 +78,7 @@ defmodule PhilomenaWeb.AppView do end def number_with_delimiter(nil), do: "0" + def number_with_delimiter(number) do number |> to_charlist() @@ -99,11 +103,12 @@ defmodule PhilomenaWeb.AppView do data = Keyword.get(args, :data, []) form_for(nil, route, [method: method, class: "button_to"], fn _f -> - submit text, class: class, data: data + submit(text, class: class, data: data) end) end def escape_nl2br(nil), do: nil + def escape_nl2br(text) do text |> String.split("\n") @@ -126,6 +131,7 @@ defmodule PhilomenaWeb.AppView do end def link_to_ip(_conn, nil), do: content_tag(:code, "null") + def link_to_ip(_conn, ip) do link(to: "/ip_profiles/#{ip}") do [ @@ -137,6 +143,7 @@ defmodule PhilomenaWeb.AppView do end def link_to_fingerprint(_conn, nil), do: content_tag(:code, "null") + def link_to_fingerprint(_conn, fp) do link(to: "/fingerprint_profiles/#{fp}") do [ diff --git a/lib/philomena_web/views/avatar_generator_view.ex b/lib/philomena_web/views/avatar_generator_view.ex index 44204df3..14f6ff4d 100644 --- a/lib/philomena_web/views/avatar_generator_view.ex +++ b/lib/philomena_web/views/avatar_generator_view.ex @@ -9,6 +9,7 @@ defmodule PhilomenaWeb.AvatarGeneratorView do # Generate 8 pseudorandom numbers seed = :erlang.crc32(displayed_name) + {rand, _acc} = Enum.map_reduce(1..8, seed, fn _elem, acc -> value = xorshift32(acc) @@ -42,7 +43,8 @@ defmodule PhilomenaWeb.AvatarGeneratorView do for_species(tail_shapes(config), species)["shape"] |> String.replace("HAIR_FILL", color_hr), for_species(body_shapes(config), species)["shape"] |> String.replace("BODY_FILL", color_bd), style_hr["shape"] |> String.replace("HAIR_FILL", color_hr), - all_species(extra_shapes(config), species) |> Enum.map(&String.replace(&1["shape"], "BODY_FILL", color_bd)), + all_species(extra_shapes(config), species) + |> Enum.map(&String.replace(&1["shape"], "BODY_FILL", color_bd)), footer(config) ] |> List.flatten() @@ -52,7 +54,7 @@ defmodule PhilomenaWeb.AvatarGeneratorView do # https://en.wikipedia.org/wiki/Xorshift # 32-bit xorshift deterministic PRNG defp xorshift32(state) do - state = state &&& 0xffff_ffff + state = state &&& 0xFFFF_FFFF state = state ^^^ (state <<< 13) state = state ^^^ (state >>> 17) @@ -79,7 +81,10 @@ defmodule PhilomenaWeb.AvatarGeneratorView do end defp for_species(styles, species), do: hd(all_species(styles, species)) - defp all_species(styles, species), do: Enum.filter(styles, &Enum.member?(&1["species"], species)) + + defp all_species(styles, species), + do: Enum.filter(styles, &Enum.member?(&1["species"], species)) + defp format(format_string, args), do: to_string(:io_lib.format(format_string, args)) defp species(%{"species" => species}), do: species diff --git a/lib/philomena_web/views/channel_view.ex b/lib/philomena_web/views/channel_view.ex index 85290217..a16112eb 100644 --- a/lib/philomena_web/views/channel_view.ex +++ b/lib/philomena_web/views/channel_view.ex @@ -6,7 +6,10 @@ defmodule PhilomenaWeb.ChannelView do def channel_image(%{type: "LivestreamChannel", short_name: short_name}) do now = DateTime.utc_now() |> DateTime.to_unix(:microsecond) - Camo.Image.image_url("https://thumbnail.api.livestream.com/thumbnail?name=#{short_name}&rand=#{now}") + + Camo.Image.image_url( + "https://thumbnail.api.livestream.com/thumbnail?name=#{short_name}&rand=#{now}" + ) end def channel_image(%{type: "PicartoChannel", thumbnail_url: thumbnail_url}), @@ -14,9 +17,12 @@ defmodule PhilomenaWeb.ChannelView do def channel_image(%{type: "PiczelChannel", remote_stream_id: remote_stream_id}), do: Camo.Image.image_url("https://piczel.tv/api/thumbnail/stream_#{remote_stream_id}.jpg") - + def channel_image(%{type: "TwitchChannel", short_name: short_name}), - do: Camo.Image.image_url("https://static-cdn.jtvnw.net/previews-ttv/live_user_#{String.downcase(short_name)}-320x180.jpg") + do: + Camo.Image.image_url( + "https://static-cdn.jtvnw.net/previews-ttv/live_user_#{String.downcase(short_name)}-320x180.jpg" + ) defp channel_url_root do Application.get_env(:philomena, :channel_url_root) diff --git a/lib/philomena_web/views/conversation_view.ex b/lib/philomena_web/views/conversation_view.ex index 66024381..75e44293 100644 --- a/lib/philomena_web/views/conversation_view.ex +++ b/lib/philomena_web/views/conversation_view.ex @@ -7,7 +7,6 @@ defmodule PhilomenaWeb.ConversationView do def other_party(_user, conversation), do: conversation.to - def read_by?(%{id: user_id}, %{to_id: user_id} = conversation), do: conversation.to_read @@ -17,11 +16,10 @@ defmodule PhilomenaWeb.ConversationView do def read_by?(_user, _conversation), do: false - def conversation_class(user, conversation) do case read_by?(user, conversation) do false -> "warning" - _ -> nil + _ -> nil end end @@ -30,4 +28,4 @@ defmodule PhilomenaWeb.ConversationView do Routes.conversation_path(conn, :show, conversation, page: page) end -end \ No newline at end of file +end diff --git a/lib/philomena_web/views/duplicate_report_view.ex b/lib/philomena_web/views/duplicate_report_view.ex index 29b0a9a7..ed30407d 100644 --- a/lib/philomena_web/views/duplicate_report_view.ex +++ b/lib/philomena_web/views/duplicate_report_view.ex @@ -30,17 +30,26 @@ defmodule PhilomenaWeb.DuplicateReportView do do: duplicate_of_image_id > image_id def higher_res?(%{image: image, duplicate_of_image: duplicate_of_image}), - do: duplicate_of_image.image_width > image.image_width or duplicate_of_image.image_height > image.image_height + do: + duplicate_of_image.image_width > image.image_width or + duplicate_of_image.image_height > image.image_height def same_res?(%{image: image, duplicate_of_image: duplicate_of_image}), - do: duplicate_of_image.image_width == image.image_width and duplicate_of_image.image_height == image.image_height + do: + duplicate_of_image.image_width == image.image_width and + duplicate_of_image.image_height == image.image_height def same_format?(%{image: image, duplicate_of_image: duplicate_of_image}), do: duplicate_of_image.image_mime_type == image.image_mime_type def better_format?(%{image: image, duplicate_of_image: duplicate_of_image}) do - source_index = Enum.find_index(@formats_order, &image.image_mime_type == &1) || length(@formats_order) - 1 - target_index = Enum.find_index(@formats_order, &duplicate_of_image.image_mime_type == &1) || length(@formats_order) - 1 + source_index = + Enum.find_index(@formats_order, &(image.image_mime_type == &1)) || + length(@formats_order) - 1 + + target_index = + Enum.find_index(@formats_order, &(duplicate_of_image.image_mime_type == &1)) || + length(@formats_order) - 1 target_index < source_index end @@ -95,27 +104,27 @@ defmodule PhilomenaWeb.DuplicateReportView do defp artist_tags(%{tags: tags}) do tags - |> Enum.filter(& &1.namespace == "artist") + |> Enum.filter(&(&1.namespace == "artist")) |> Enum.map(& &1.name) |> MapSet.new() end defp rating_tags(%{tags: tags}) do tags - |> Enum.filter(& &1.category == "rating") + |> Enum.filter(&(&1.category == "rating")) |> Enum.map(& &1.name) |> MapSet.new() end defp edit?(%{tags: tags}) do tags - |> Enum.filter(& &1.name == "edit") + |> Enum.filter(&(&1.name == "edit")) |> Enum.any?() end defp alternate_version?(%{tags: tags}) do tags - |> Enum.filter(& &1.name == "alternate version") + |> Enum.filter(&(&1.name == "alternate version")) |> Enum.any?() end diff --git a/lib/philomena_web/views/image/subscription_view.ex b/lib/philomena_web/views/image/subscription_view.ex index ed5da40f..16e15db9 100644 --- a/lib/philomena_web/views/image/subscription_view.ex +++ b/lib/philomena_web/views/image/subscription_view.ex @@ -1,3 +1,3 @@ defmodule PhilomenaWeb.Image.SubscriptionView do use PhilomenaWeb, :view -end \ No newline at end of file +end diff --git a/lib/philomena_web/views/image_view.ex b/lib/philomena_web/views/image_view.ex index ae44602c..b17fc686 100644 --- a/lib/philomena_web/views/image_view.ex +++ b/lib/philomena_web/views/image_view.ex @@ -14,6 +14,7 @@ defmodule PhilomenaWeb.ImageView do # this is a bit ridiculous def render_intent(_conn, %{thumbnails_generated: false}, _size), do: :not_rendered + def render_intent(conn, image, size) do uris = thumb_urls(image, can?(conn, :show, image)) vid? = image.image_mime_type == "video/webm" @@ -78,12 +79,14 @@ defmodule PhilomenaWeb.ImageView do } ) end + defp append_gif_urls(urls, _image, _show_hidden), do: urls def thumb_url(image, show_hidden, name) do %{year: year, month: month, day: day} = image.created_at deleted = image.hidden_from_users root = image_url_root() + format = image.image_format |> to_string() @@ -106,6 +109,7 @@ defmodule PhilomenaWeb.ImageView do view = if download, do: "download", else: "view" filename = if short, do: image.id, else: image.file_name_cache + format = image.image_format |> to_string() @@ -140,7 +144,10 @@ defmodule PhilomenaWeb.ImageView do end def image_container(conn, image, size, block) do - content_tag(:div, block.(), class: "image-container #{size}", data: image_container_data(conn, image, size)) + content_tag(:div, block.(), + class: "image-container #{size}", + data: image_container_data(conn, image, size) + ) end def display_order(tags) do @@ -157,16 +164,23 @@ defmodule PhilomenaWeb.ImageView do end def info_row(_conn, []), do: [] + def info_row(conn, [{tag, description, dnp_entries}]) do - render PhilomenaWeb.TagView, "_tag_info_row.html", conn: conn, tag: tag, body: description, dnp_entries: dnp_entries + render(PhilomenaWeb.TagView, "_tag_info_row.html", + conn: conn, + tag: tag, + body: description, + dnp_entries: dnp_entries + ) end + def info_row(conn, tags) do - render PhilomenaWeb.TagView, "_tags_row.html", conn: conn, tags: tags + render(PhilomenaWeb.TagView, "_tags_row.html", conn: conn, tags: tags) end def quick_tag(conn) do if can?(conn, :batch_update, Tag) do - render PhilomenaWeb.ImageView, "_quick_tag.html", conn: conn + render(PhilomenaWeb.ImageView, "_quick_tag.html", conn: conn) end end @@ -179,17 +193,22 @@ defmodule PhilomenaWeb.ImageView do def hides_images?(conn), do: can?(conn, :hide, %Philomena.Images.Image{}) def random_button(conn, params) do - render PhilomenaWeb.ImageView, "_random_button.html", conn: conn, params: params + render(PhilomenaWeb.ImageView, "_random_button.html", conn: conn, params: params) end def hidden_toggle(%{assigns: %{current_user: nil}}, _route, _params), do: nil + def hidden_toggle(conn, route, params) do - render PhilomenaWeb.ImageView, "_hidden_toggle.html", route: route, params: params, conn: conn + render(PhilomenaWeb.ImageView, "_hidden_toggle.html", route: route, params: params, conn: conn) end def deleted_toggle(conn, route, params) do if hides_images?(conn) do - render PhilomenaWeb.ImageView, "_deleted_toggle.html", route: route, params: params, conn: conn + render(PhilomenaWeb.ImageView, "_deleted_toggle.html", + route: route, + params: params, + conn: conn + ) end end @@ -199,21 +218,21 @@ defmodule PhilomenaWeb.ImageView do defp image_filter_data(image) do %{ - id: image.id, + id: image.id, "namespaced_tags.name": String.split(image.tag_list_plus_alias_cache || "", ", "), - score: image.score, - faves: image.faves_count, - upvotes: image.upvotes_count, - downvotes: image.downvotes_count, - comment_count: image.comments_count, - created_at: image.created_at, - first_seen_at: image.first_seen_at, - source_url: image.source_url, - width: image.image_width, - height: image.image_height, - aspect_ratio: image.image_aspect_ratio, - sha512_hash: image.image_sha512_hash, - orig_sha512_hash: image.image_orig_sha512_hash + score: image.score, + faves: image.faves_count, + upvotes: image.upvotes_count, + downvotes: image.downvotes_count, + comment_count: image.comments_count, + created_at: image.created_at, + first_seen_at: image.first_seen_at, + source_url: image.source_url, + width: image.image_width, + height: image.image_height, + aspect_ratio: image.image_aspect_ratio, + sha512_hash: image.image_sha512_hash, + orig_sha512_hash: image.image_orig_sha512_hash } end @@ -233,6 +252,7 @@ defmodule PhilomenaWeb.ImageView do doc = image_filter_data(image) complex_filter = conn.assigns.compiled_complex_filter complex_spoiler = conn.assigns.compiled_complex_spoiler + query = %{ bool: %{ should: [complex_filter, complex_spoiler] diff --git a/lib/philomena_web/views/layout_view.ex b/lib/philomena_web/views/layout_view.ex index dad5db50..5c369521 100644 --- a/lib/philomena_web/views/layout_view.ex +++ b/lib/philomena_web/views/layout_view.ex @@ -79,10 +79,12 @@ defmodule PhilomenaWeb.LayoutView do def theme_name(_user), do: "default" def artist_tags(tags), - do: Enum.filter(tags, & &1.namespace == "artist") + do: Enum.filter(tags, &(&1.namespace == "artist")) def opengraph?(conn), - do: !is_nil(conn.assigns[:image]) and conn.assigns.image.__meta__.state == :loaded and is_list(conn.assigns.image.tags) + do: + !is_nil(conn.assigns[:image]) and conn.assigns.image.__meta__.state == :loaded and + is_list(conn.assigns.image.tags) def hides_images?(conn), do: can?(conn, :hide, %Philomena.Images.Image{}) @@ -118,7 +120,7 @@ defmodule PhilomenaWeb.LayoutView do ua = get_user_agent(conn) case String.contains?(ua, ["Mobile", "webOS"]) do - true -> tag(:meta, name: "viewport", content: "width=device-width, initial-scale=1") + true -> tag(:meta, name: "viewport", content: "width=device-width, initial-scale=1") _false -> tag(:meta, name: "viewport", content: "width=1024, initial-scale=1") end end @@ -126,7 +128,7 @@ defmodule PhilomenaWeb.LayoutView do defp get_user_agent(conn) do case Plug.Conn.get_req_header(conn, "user-agent") do [ua] -> ua - _ -> "" + _ -> "" end end end diff --git a/lib/philomena_web/views/message_view.ex b/lib/philomena_web/views/message_view.ex index b57e0623..ed402912 100644 --- a/lib/philomena_web/views/message_view.ex +++ b/lib/philomena_web/views/message_view.ex @@ -1,3 +1,3 @@ defmodule PhilomenaWeb.MessageView do use PhilomenaWeb, :view -end \ No newline at end of file +end diff --git a/lib/philomena_web/views/notification_view.ex b/lib/philomena_web/views/notification_view.ex index b3ef40ce..52d05201 100644 --- a/lib/philomena_web/views/notification_view.ex +++ b/lib/philomena_web/views/notification_view.ex @@ -13,4 +13,4 @@ defmodule PhilomenaWeb.NotificationView do def notification_template_path(actor_type) do @template_paths[actor_type] end -end \ No newline at end of file +end diff --git a/lib/philomena_web/views/pagination_view.ex b/lib/philomena_web/views/pagination_view.ex index 0fe44f25..7bdbb618 100644 --- a/lib/philomena_web/views/pagination_view.ex +++ b/lib/philomena_web/views/pagination_view.ex @@ -27,8 +27,8 @@ defmodule PhilomenaWeb.PaginationView do min = 1 max = page.total_pages - (number - 5..number) - |> Enum.filter(& &1 >= min and &1 != number and &1 <= max) + (number - 5)..number + |> Enum.filter(&(&1 >= min and &1 != number and &1 <= max)) end def right_gap?(page) do @@ -40,7 +40,7 @@ defmodule PhilomenaWeb.PaginationView do min = 1 max = page.total_pages - (number .. number + 5) - |> Enum.filter(& &1 >= min and &1 != number and &1 <= max) + number..(number + 5) + |> Enum.filter(&(&1 >= min and &1 != number and &1 <= max)) end end diff --git a/lib/philomena_web/views/post/preview_view.ex b/lib/philomena_web/views/post/preview_view.ex index 3df2af84..af72e2c5 100644 --- a/lib/philomena_web/views/post/preview_view.ex +++ b/lib/philomena_web/views/post/preview_view.ex @@ -1,3 +1,3 @@ defmodule PhilomenaWeb.Post.PreviewView do use PhilomenaWeb, :view -end \ No newline at end of file +end diff --git a/lib/philomena_web/views/profile/alias_view.ex b/lib/philomena_web/views/profile/alias_view.ex index d97d71a4..fc884c86 100644 --- a/lib/philomena_web/views/profile/alias_view.ex +++ b/lib/philomena_web/views/profile/alias_view.ex @@ -2,15 +2,15 @@ defmodule PhilomenaWeb.Profile.AliasView do use PhilomenaWeb, :view def younger_than_7_days?(user), - do: younger_than_time_offset?(user, -7*24*60*60) + do: younger_than_time_offset?(user, -7 * 24 * 60 * 60) def younger_than_14_days?(user), - do: younger_than_time_offset?(user, -14*24*60*60) + do: younger_than_time_offset?(user, -14 * 24 * 60 * 60) def currently_banned?(%{bans: bans}) do now = DateTime.utc_now() - Enum.any?(bans, &DateTime.diff(&1.valid_until, now) >= 0) + Enum.any?(bans, &(DateTime.diff(&1.valid_until, now) >= 0)) end def previously_banned?(%{bans: []}), do: false diff --git a/lib/philomena_web/views/profile_view.ex b/lib/philomena_web/views/profile_view.ex index 3c1dcc6a..c45a1210 100644 --- a/lib/philomena_web/views/profile_view.ex +++ b/lib/philomena_web/views/profile_view.ex @@ -20,8 +20,10 @@ defmodule PhilomenaWeb.ProfileView do def award_title(%{badge_name: nil} = award), do: award.badge.title + def award_title(%{badge_name: ""} = award), do: award.badge.title + def award_title(award), do: award.badge_name @@ -34,7 +36,7 @@ defmodule PhilomenaWeb.ProfileView do max = max(max, 0) min = max(min, 0) - content_tag :svg, [width: "100%", preserveAspectRatio: "none", viewBox: "0 0 90 20"] do + content_tag :svg, width: "100%", preserveAspectRatio: "none", viewBox: "0 0 90 20" do for {val, i} <- Enum.with_index(data) do # Filter out negative values calc = max(val, 0) @@ -45,8 +47,8 @@ defmodule PhilomenaWeb.ProfileView do # In SVG coords, y grows down y = 20 - height - content_tag :rect, [class: "barline__bar", x: i, y: y, width: 1, height: height] do - content_tag :title, val + content_tag :rect, class: "barline__bar", x: i, y: y, width: 1, height: height do + content_tag(:title, val) end end end @@ -72,16 +74,24 @@ defmodule PhilomenaWeb.ProfileView do def enabled_text(_else), do: "Disabled" def user_abbrv(conn, %{name: name} = user) do - abbrv = String.upcase(initials_abbrv(name) || uppercase_abbrv(name) || first_letters_abbrv(name)) + abbrv = + String.upcase(initials_abbrv(name) || uppercase_abbrv(name) || first_letters_abbrv(name)) + abbrv = "(" <> abbrv <> ")" link(abbrv, to: Routes.profile_path(conn, :show, user)) end + def user_abbrv(_conn, _user), do: content_tag(:span, "(n/a)") defp initials_abbrv(name) do case String.split(name, " ", parts: 4) do - [<>, <>, <>, <>] -> + [ + <>, + <>, + <>, + <> + ] -> <> [<>, <>, <>] -> diff --git a/lib/philomena_web/views/registration/totp_view.ex b/lib/philomena_web/views/registration/totp_view.ex index 2f1125f4..3e7335ad 100644 --- a/lib/philomena_web/views/registration/totp_view.ex +++ b/lib/philomena_web/views/registration/totp_view.ex @@ -1,3 +1,3 @@ defmodule PhilomenaWeb.Registration.TotpView do use PhilomenaWeb, :view -end \ No newline at end of file +end diff --git a/lib/philomena_web/views/report_view.ex b/lib/philomena_web/views/report_view.ex index be4d1764..27f6f5a2 100644 --- a/lib/philomena_web/views/report_view.ex +++ b/lib/philomena_web/views/report_view.ex @@ -26,7 +26,7 @@ defmodule PhilomenaWeb.ReportView do "Rule #n: Spirit of the rules": "Rule #n", "Other (please explain)": "Other", "Takedown request": "Takedown request" - ] + ] end def image?(changeset), do: get_field(changeset, :reportable_type) == "Image" @@ -42,25 +42,39 @@ defmodule PhilomenaWeb.ReportView do def pretty_state(_report), do: "Open" def link_to_reported_thing(conn, %Image{} = r), - do: link "Image >>#{r.id}", to: Routes.image_path(conn, :show, r) + do: link("Image >>#{r.id}", to: Routes.image_path(conn, :show, r)) def link_to_reported_thing(conn, %Comment{} = r), - do: link "Comment on image >>#{r.image.id}", to: Routes.image_path(conn, :show, r.image) <> "#comment_#{r.id}" + do: + link("Comment on image >>#{r.image.id}", + to: Routes.image_path(conn, :show, r.image) <> "#comment_#{r.id}" + ) def link_to_reported_thing(conn, %Conversation{} = r), - do: link "Conversation between #{r.from.name} and #{r.to.name}", to: Routes.conversation_path(conn, :show, r) + do: + link("Conversation between #{r.from.name} and #{r.to.name}", + to: Routes.conversation_path(conn, :show, r) + ) def link_to_reported_thing(conn, %Commission{} = r), - do: link "#{r.user.name}'s commission page", to: Routes.profile_commission_path(conn, :show, r.user) + do: + link("#{r.user.name}'s commission page", + to: Routes.profile_commission_path(conn, :show, r.user) + ) def link_to_reported_thing(conn, %Gallery{} = r), - do: link "Gallery '#{r.title}' by #{r.creator.name}", to: Routes.gallery_path(conn, :show, r) + do: link("Gallery '#{r.title}' by #{r.creator.name}", to: Routes.gallery_path(conn, :show, r)) def link_to_reported_thing(conn, %Post{} = r), - do: link "Post in #{r.topic.title}", to: Routes.forum_topic_path(conn, :show, r.topic.forum, r.topic, post_id: r.id) <> "#post_#{r.id}" + do: + link("Post in #{r.topic.title}", + to: + Routes.forum_topic_path(conn, :show, r.topic.forum, r.topic, post_id: r.id) <> + "#post_#{r.id}" + ) def link_to_reported_thing(conn, %User{} = r), - do: link "User '#{r.name}'", to: Routes.profile_path(conn, :show, r) + do: link("User '#{r.name}'", to: Routes.profile_path(conn, :show, r)) def link_to_reported_thing(_conn, _reportable) do "Reported item permanently destroyed." diff --git a/lib/philomena_web/views/session/totp_view.ex b/lib/philomena_web/views/session/totp_view.ex index 0b899639..0955bd46 100644 --- a/lib/philomena_web/views/session/totp_view.ex +++ b/lib/philomena_web/views/session/totp_view.ex @@ -1,3 +1,3 @@ defmodule PhilomenaWeb.Session.TotpView do use PhilomenaWeb, :view -end \ No newline at end of file +end diff --git a/lib/philomena_web/views/setting_view.ex b/lib/philomena_web/views/setting_view.ex index d8ddf187..f570b1bd 100644 --- a/lib/philomena_web/views/setting_view.ex +++ b/lib/philomena_web/views/setting_view.ex @@ -3,7 +3,11 @@ defmodule PhilomenaWeb.SettingView do def theme_options(conn) do [ - [key: "Default", value: "default", data: [theme_path: Routes.static_path(conn, "/css/default.css")]], + [ + key: "Default", + value: "default", + data: [theme_path: Routes.static_path(conn, "/css/default.css")] + ], [key: "Dark", value: "dark", data: [theme_path: Routes.static_path(conn, "/css/dark.css")]], [key: "Red", value: "red", data: [theme_path: Routes.static_path(conn, "/css/red.css")]] ] @@ -11,7 +15,7 @@ defmodule PhilomenaWeb.SettingView do def local_tab_class(conn) do case conn.assigns.current_user do - nil -> "" + nil -> "" _user -> "hidden" end end diff --git a/lib/philomena_web/views/source_change_view.ex b/lib/philomena_web/views/source_change_view.ex index 5b1d0128..48d658d7 100644 --- a/lib/philomena_web/views/source_change_view.ex +++ b/lib/philomena_web/views/source_change_view.ex @@ -2,11 +2,13 @@ defmodule PhilomenaWeb.SourceChangeView do use PhilomenaWeb, :view def staff?(source_change), - do: not is_nil(source_change.user) and not Philomena.Attribution.anonymous?(source_change) and source_change.user.role != "user" + do: + not is_nil(source_change.user) and not Philomena.Attribution.anonymous?(source_change) and + source_change.user.role != "user" def user_column_class(source_change) do case staff?(source_change) do - true -> "success" + true -> "success" false -> nil end end diff --git a/lib/philomena_web/views/stat_view.ex b/lib/philomena_web/views/stat_view.ex index e550805a..c77297a0 100644 --- a/lib/philomena_web/views/stat_view.ex +++ b/lib/philomena_web/views/stat_view.ex @@ -20,11 +20,13 @@ defmodule PhilomenaWeb.StatView do bar_height = safe_div(datum["doc_count"], max_docs - min_docs) * graph_height x = i * bar_width - y = graph_height-bar_height + y = graph_height - bar_height height = bar_height content_tag :rect, width: bar_width, height: height, x: x, y: y, fill: "#000" do - content_tag :title, do: [datum["key_as_string"], " - ", Integer.to_string(datum["doc_count"]), " uploads"] + content_tag(:title, + do: [datum["key_as_string"], " - ", Integer.to_string(datum["doc_count"]), " uploads"] + ) end end end diff --git a/lib/philomena_web/views/tag_change_view.ex b/lib/philomena_web/views/tag_change_view.ex index f3ffb411..07d99e16 100644 --- a/lib/philomena_web/views/tag_change_view.ex +++ b/lib/philomena_web/views/tag_change_view.ex @@ -2,11 +2,13 @@ defmodule PhilomenaWeb.TagChangeView do use PhilomenaWeb, :view def staff?(tag_change), - do: not is_nil(tag_change.user) and not Philomena.Attribution.anonymous?(tag_change) and tag_change.user.role != "user" + do: + not is_nil(tag_change.user) and not Philomena.Attribution.anonymous?(tag_change) and + tag_change.user.role != "user" def user_column_class(tag_change) do case staff?(tag_change) do - true -> "success" + true -> "success" false -> nil end end diff --git a/lib/philomena_web/views/tag_view.ex b/lib/philomena_web/views/tag_view.ex index b3a11b69..5ddfb108 100644 --- a/lib/philomena_web/views/tag_view.ex +++ b/lib/philomena_web/views/tag_view.ex @@ -9,7 +9,7 @@ defmodule PhilomenaWeb.TagView do import Ecto.Query def tag_categories do - [[key: "-", value: ""] | Tag.categories] + [[key: "-", value: ""] | Tag.categories()] end def manages_tags?(conn) do @@ -48,10 +48,11 @@ defmodule PhilomenaWeb.TagView do def tab_body_class(_), do: "hidden" def tag_link(nil, tag_name), do: tag_name + def tag_link(tag, tag_name) do title = title(implications(tag) ++ short_description(tag)) - link tag_name, to: "#", title: title, data: [tag_name: tag_name, click_addtag: tag_name] + link(tag_name, to: "#", title: title, data: [tag_name: tag_name, click_addtag: tag_name]) end def tags_row_class(%{params: %{"page" => "0"}}), do: nil @@ -60,6 +61,7 @@ defmodule PhilomenaWeb.TagView do def tags_row_class(_conn), do: nil defp implications(%{implied_tags: []}), do: [] + defp implications(%{implied_tags: it}) do names = it @@ -84,7 +86,7 @@ defmodule PhilomenaWeb.TagView do shipping = tabs - |> Enum.filter(&tab_modes[&1] == "shipping") + |> Enum.filter(&(tab_modes[&1] == "shipping")) |> Map.new(fn tab -> sd = data[tab] @@ -95,7 +97,12 @@ defmodule PhilomenaWeb.TagView do end defp render_quick_tags({tags, shipping, data}, conn) do - render PhilomenaWeb.TagView, "_quick_tag_table.html", tags: tags, shipping: shipping, data: data, conn: conn + render(PhilomenaWeb.TagView, "_quick_tag_table.html", + tags: tags, + shipping: shipping, + data: data, + conn: conn + ) end defp names_in_tab("default", data) do @@ -131,7 +138,7 @@ defmodule PhilomenaWeb.TagView do query: %{ bool: %{ must: Enum.map(tag_names, &%{term: %{implied_tags: &1}}), - must_not: Enum.map(ignore_tag_names, &%{term: %{implied_tags: &1}}), + must_not: Enum.map(ignore_tag_names, &%{term: %{implied_tags: &1}}) } }, sort: %{images: :desc} diff --git a/lib/philomena_web/views/topic/poll_view.ex b/lib/philomena_web/views/topic/poll_view.ex index 1d7024bb..04801def 100644 --- a/lib/philomena_web/views/topic/poll_view.ex +++ b/lib/philomena_web/views/topic/poll_view.ex @@ -24,13 +24,16 @@ defmodule PhilomenaWeb.Topic.PollView do def input_name(_poll), do: "poll[option_ids][]" def percent_of_total(_option, %{total_votes: 0}), do: "0%" + def percent_of_total(%{vote_count: vote_count}, %{total_votes: total_votes}) do - :io_lib.format("~.2f%", [(vote_count / total_votes * 100)]) + :io_lib.format("~.2f%", [vote_count / total_votes * 100]) end def option_class(%{id: option_id}, %{id: option_id}, true), do: "poll-option-top" def option_class(_option, _top_option, _winners?), do: nil - def poll_bar_class(%{id: option_id}, %{id: option_id}, true), do: "poll-bar__fill poll-bar__fill--top" + def poll_bar_class(%{id: option_id}, %{id: option_id}, true), + do: "poll-bar__fill poll-bar__fill--top" + def poll_bar_class(_option, _top_option, _winners?), do: "poll-bar__fill" end diff --git a/lib/philomena_web/views/topic/subscription_view.ex b/lib/philomena_web/views/topic/subscription_view.ex index 2133f1e6..bfb89563 100644 --- a/lib/philomena_web/views/topic/subscription_view.ex +++ b/lib/philomena_web/views/topic/subscription_view.ex @@ -1,3 +1,3 @@ defmodule PhilomenaWeb.Topic.SubscriptionView do use PhilomenaWeb, :view -end \ No newline at end of file +end diff --git a/lib/philomena_web/views/user_attribution_view.ex b/lib/philomena_web/views/user_attribution_view.ex index f822770f..e9f0bdb3 100644 --- a/lib/philomena_web/views/user_attribution_view.ex +++ b/lib/philomena_web/views/user_attribution_view.ex @@ -14,12 +14,12 @@ defmodule PhilomenaWeb.UserAttributionView do user_id = Attribution.best_user_identifier(object) hash = - (:erlang.crc32(salt <> id <> user_id) &&& 0xffff) + (:erlang.crc32(salt <> id <> user_id) &&& 0xFFFF) |> Integer.to_string(16) |> String.pad_leading(4, "0") case not is_nil(object.user) and reveal_anon? do - true -> "#{object.user.name} (##{hash}, hidden)" + true -> "#{object.user.name} (##{hash}, hidden)" false -> "Background Pony ##{hash}" end end @@ -27,7 +27,7 @@ defmodule PhilomenaWeb.UserAttributionView do def anonymous_avatar(name, class \\ "avatar--100px") do class = Enum.join(["image-constrained", class], " ") - content_tag :div, [class: class] do + content_tag :div, class: class do PhilomenaWeb.AvatarGeneratorView.generated_avatar(name) end end @@ -36,12 +36,14 @@ defmodule PhilomenaWeb.UserAttributionView do def user_avatar(%{user: nil} = object, class), do: anonymous_avatar(anonymous_name(object), class) + def user_avatar(%{user: %{avatar: nil}} = object, class), do: anonymous_avatar(object.user.name, class) + def user_avatar(%{user: %{avatar: avatar}}, class) do class = Enum.join(["image-constrained", class], " ") - content_tag :div, [class: class] do + content_tag :div, class: class do img_tag(avatar_url_root() <> "/" <> avatar) end end @@ -55,26 +57,31 @@ defmodule PhilomenaWeb.UserAttributionView do defp personal_title(labels, %{personal_title: t}) do case blank?(t) do - true -> labels + true -> labels false -> [{"label--primary", t} | labels] end end + defp personal_title(labels, _user), do: labels defp secondary_role(labels, %{secondary_role: t}) do case blank?(t) do - true -> labels + true -> labels false -> [{"label--warning", t} | labels] end end + defp secondary_role(labels, _user), do: labels defp staff_role(labels, %{hide_default_role: false, role: "admin"}), do: [{"label--danger", "Site Administrator"} | labels] + defp staff_role(labels, %{hide_default_role: false, role: "moderator"}), do: [{"label--success", "Site Moderator"} | labels] + defp staff_role(labels, %{hide_default_role: false, role: "assistant"}), do: [{"label--purple", "Site Assistant"} | labels] + defp staff_role(labels, _user), do: labels diff --git a/lib/pow_captcha/captcha.ex b/lib/pow_captcha/captcha.ex index f0c99bf5..eaf724f2 100644 --- a/lib/pow_captcha/captcha.ex +++ b/lib/pow_captcha/captcha.ex @@ -4,4 +4,4 @@ defmodule PowCaptcha do @impl true def phoenix_controller_callbacks?(), do: true -end \ No newline at end of file +end diff --git a/lib/pow_captcha/phoenix/controllers/controller_callbacks.ex b/lib/pow_captcha/phoenix/controllers/controller_callbacks.ex index e59af33a..96c14ab5 100644 --- a/lib/pow_captcha/phoenix/controllers/controller_callbacks.ex +++ b/lib/pow_captcha/phoenix/controllers/controller_callbacks.ex @@ -29,10 +29,12 @@ defmodule PowCaptcha.Phoenix.ControllerCallbacks do |> maybe_halt(conn, return_path) end - defp maybe_halt(false, conn, return_path) do conn - |> Controller.put_flash(:error, "There was an error verifying you're not a robot. Please try again.") + |> Controller.put_flash( + :error, + "There was an error verifying you're not a robot. Please try again." + ) |> Controller.redirect(to: return_path) |> Conn.halt() end @@ -40,4 +42,4 @@ defmodule PowCaptcha.Phoenix.ControllerCallbacks do defp maybe_halt(true, conn, _return_path) do conn end -end \ No newline at end of file +end diff --git a/lib/pow_lockout/ecto/context.ex b/lib/pow_lockout/ecto/context.ex index 8e77e936..2f1fff7d 100644 --- a/lib/pow_lockout/ecto/context.ex +++ b/lib/pow_lockout/ecto/context.ex @@ -18,6 +18,7 @@ defmodule PowLockout.Ecto.Context do @spec locked_out?(Context.user(), Config.t()) :: boolean() def locked_out?(%{locked_at: time}, _config) when not is_nil(time), do: true + def locked_out?(_user, _config), do: false @@ -26,7 +27,8 @@ defmodule PowLockout.Ecto.Context do See `PowLockout.Ecto.Schema.unlock_changeset/1`. """ - @spec unlock_account(Context.user(), Config.t()) :: {:ok, Context.user()} | {:error, Context.changeset()} + @spec unlock_account(Context.user(), Config.t()) :: + {:ok, Context.user()} | {:error, Context.changeset()} def unlock_account(user, config) do user |> Schema.unlock_changeset() @@ -38,7 +40,8 @@ defmodule PowLockout.Ecto.Context do See `PowLockout.Ecto.Schema.attempt_changeset/1`. """ - @spec fail_attempt(Context.user(), Config.t()) :: {:ok, Context.user()} | {:error, Context.changeset()} + @spec fail_attempt(Context.user(), Config.t()) :: + {:ok, Context.user()} | {:error, Context.changeset()} def fail_attempt(user, config) do user |> Schema.attempt_changeset() @@ -50,7 +53,8 @@ defmodule PowLockout.Ecto.Context do See `PowLockout.Ecto.Schema.attempt_reset_changeset/1`. """ - @spec succeed_attempt(Context.user(), Config.t()) :: {:ok, Context.user()} | {:error, Context.changeset()} + @spec succeed_attempt(Context.user(), Config.t()) :: + {:ok, Context.user()} | {:error, Context.changeset()} def succeed_attempt(user, config) do user |> Schema.attempt_reset_changeset() diff --git a/lib/pow_lockout/ecto/schema.ex b/lib/pow_lockout/ecto/schema.ex index 45c881c7..20338536 100644 --- a/lib/pow_lockout/ecto/schema.ex +++ b/lib/pow_lockout/ecto/schema.ex @@ -54,12 +54,11 @@ defmodule PowLockout.Ecto.Schema do """ @spec unlock_changeset(Ecto.Schema.t() | Changeset.t()) :: Changeset.t() def unlock_changeset(user_or_changeset) do - changes = - [ - locked_at: nil, - unlock_token: nil, - failed_attempts: 0 - ] + changes = [ + locked_at: nil, + unlock_token: nil, + failed_attempts: 0 + ] user_or_changeset |> Changeset.change(changes) @@ -74,11 +73,11 @@ defmodule PowLockout.Ecto.Schema do def lock_changeset(user_or_changeset) do changeset = Changeset.change(user_or_changeset) locked_at = Pow.Ecto.Schema.__timestamp_for__(changeset.data.__struct__, :locked_at) - changes = - [ - locked_at: locked_at, - unlock_token: UUID.generate() - ] + + changes = [ + locked_at: locked_at, + unlock_token: UUID.generate() + ] changeset |> Changeset.change(changes) @@ -91,15 +90,25 @@ defmodule PowLockout.Ecto.Schema do The first time it becomes greater than 10, it also locks the user. """ @spec attempt_changeset(Ecto.Schema.t() | Changeset.t()) :: Changeset.t() - def attempt_changeset(%Changeset{data: %{failed_attempts: attempts}} = changeset) when is_integer(attempts) and attempts < 10 do + def attempt_changeset(%Changeset{data: %{failed_attempts: attempts}} = changeset) + when is_integer(attempts) and attempts < 10 do Changeset.change(changeset, failed_attempts: attempts + 1) end - def attempt_changeset(%Changeset{data: %{failed_attempts: attempts, locked_at: nil}} = changeset) when is_integer(attempts) do + + def attempt_changeset( + %Changeset{data: %{failed_attempts: attempts, locked_at: nil}} = changeset + ) + when is_integer(attempts) do lock_changeset(changeset) end - def attempt_changeset(%Changeset{data: %{failed_attempts: attempts, locked_at: _locked_at}} = changeset) when is_integer(attempts) do + + def attempt_changeset( + %Changeset{data: %{failed_attempts: attempts, locked_at: _locked_at}} = changeset + ) + when is_integer(attempts) do changeset end + def attempt_changeset(%Changeset{} = changeset) do Changeset.change(changeset, failed_attempts: 1) end diff --git a/lib/pow_lockout/lockout.ex b/lib/pow_lockout/lockout.ex index aa1df6af..21e21269 100644 --- a/lib/pow_lockout/lockout.ex +++ b/lib/pow_lockout/lockout.ex @@ -13,4 +13,4 @@ defmodule PowLockout do @impl true def phoenix_messages?(), do: true -end \ No newline at end of file +end diff --git a/lib/pow_lockout/phoenix/controllers/controller_callbacks.ex b/lib/pow_lockout/phoenix/controllers/controller_callbacks.ex index 267c2f02..9f11a19a 100644 --- a/lib/pow_lockout/phoenix/controllers/controller_callbacks.ex +++ b/lib/pow_lockout/phoenix/controllers/controller_callbacks.ex @@ -83,7 +83,7 @@ defmodule PowLockout.Phoenix.ControllerCallbacks do """ @spec send_unlock_email(map(), Conn.t()) :: any() def send_unlock_email(user, conn) do - url = unlock_url(conn, user.unlock_token) + url = unlock_url(conn, user.unlock_token) email = Mailer.email_unlock(conn, user, url) Pow.Phoenix.Mailer.deliver(conn, email) diff --git a/lib/pow_lockout/phoenix/controllers/unlock_controller.ex b/lib/pow_lockout/phoenix/controllers/unlock_controller.ex index daeeeb0b..824b0d34 100644 --- a/lib/pow_lockout/phoenix/controllers/unlock_controller.ex +++ b/lib/pow_lockout/phoenix/controllers/unlock_controller.ex @@ -14,6 +14,7 @@ defmodule PowLockout.Phoenix.UnlockController do |> put_flash(:info, extension_messages(conn).account_has_been_unlocked(conn)) |> redirect(to: routes(conn).session_path(conn, :new)) end + def respond_show({:error, _changeset, conn}) do conn |> put_flash(:error, extension_messages(conn).account_unlock_failed(conn)) diff --git a/lib/pow_lockout/phoenix/mailers/mailer_template.ex b/lib/pow_lockout/phoenix/mailers/mailer_template.ex index 7d886ba7..0f877976 100644 --- a/lib/pow_lockout/phoenix/mailers/mailer_template.ex +++ b/lib/pow_lockout/phoenix/mailers/mailer_template.ex @@ -2,22 +2,24 @@ defmodule PowLockout.Phoenix.MailerTemplate do @moduledoc false use Pow.Phoenix.Mailer.Template - template :email_unlock, - "Unlock your account", - """ - Hi, + template( + :email_unlock, + "Unlock your account", + """ + Hi, - Your account has been automatically disabled due to too many unsuccessful - attempts to sign in. + Your account has been automatically disabled due to too many unsuccessful + attempts to sign in. - Please use the following link to unlock your account: + Please use the following link to unlock your account: - <%= @url %> - """, - """ - <%= content_tag(:h3, "Hi,") %> - <%= content_tag(:p, "Your account has been automatically disabled due to too many unsuccessful attempts to sign in.") %> - <%= content_tag(:p, "Please use the following link to unlock your account:") %> - <%= content_tag(:p, link(@url, to: @url)) %> - """ + <%= @url %> + """, + """ + <%= content_tag(:h3, "Hi,") %> + <%= content_tag(:p, "Your account has been automatically disabled due to too many unsuccessful attempts to sign in.") %> + <%= content_tag(:p, "Please use the following link to unlock your account:") %> + <%= content_tag(:p, link(@url, to: @url)) %> + """ + ) end diff --git a/lib/pow_lockout/phoenix/router.ex b/lib/pow_lockout/phoenix/router.ex index 9a6b092a..e469cd26 100644 --- a/lib/pow_lockout/phoenix/router.ex +++ b/lib/pow_lockout/phoenix/router.ex @@ -6,7 +6,7 @@ defmodule PowLockout.Phoenix.Router do defmacro routes(_config) do quote location: :keep do - Router.pow_resources "/unlock", UnlockController, only: [:show] + Router.pow_resources("/unlock", UnlockController, only: [:show]) end end end diff --git a/lib/pow_lockout/plug.ex b/lib/pow_lockout/plug.ex index 590e040c..f4fa79d6 100644 --- a/lib/pow_lockout/plug.ex +++ b/lib/pow_lockout/plug.ex @@ -46,12 +46,13 @@ defmodule PowLockout.Plug do defp maybe_unlock_account(nil, conn, _config) do {:error, nil, conn} end + defp maybe_unlock_account(user, conn, config) do user |> Context.unlock_account(config) |> case do {:error, changeset} -> {:error, changeset, conn} - {:ok, user} -> {:ok, user, conn} + {:ok, user} -> {:ok, user, conn} end end @@ -65,7 +66,7 @@ defmodule PowLockout.Plug do Context.fail_attempt(user, config) |> case do {:error, changeset} -> {:error, changeset, conn} - {:ok, user} -> {:ok, user, conn} + {:ok, user} -> {:ok, user, conn} end end @@ -79,7 +80,7 @@ defmodule PowLockout.Plug do Context.succeed_attempt(user, config) |> case do {:error, changeset} -> {:error, changeset, conn} - {:ok, user} -> {:ok, user, conn} + {:ok, user} -> {:ok, user, conn} end end end diff --git a/lib/relative_date/parser.ex b/lib/relative_date/parser.ex index a801b74c..4d8e24b3 100644 --- a/lib/relative_date/parser.ex +++ b/lib/relative_date/parser.ex @@ -70,7 +70,7 @@ defmodule RelativeDate.Parser do date ]) - defparsecp :relative_date, relative_date + defparsecp(:relative_date, relative_date) def parse(input) do input = @@ -100,13 +100,17 @@ defmodule RelativeDate.Parser do def parse_relative(input) do case relative_date(input) do {:ok, [moon: _moon], _1, _2, _3, _4} -> - {:ok, DateTime.utc_now() |> DateTime.add(31_536_000_000, :second) |> DateTime.truncate(:second)} + {:ok, + DateTime.utc_now() |> DateTime.add(31_536_000_000, :second) |> DateTime.truncate(:second)} {:ok, [now: _now], _1, _2, _3, _4} -> {:ok, DateTime.utc_now() |> DateTime.truncate(:second)} {:ok, [relative_date: [amount, scale, direction]], _1, _2, _3, _4} -> - {:ok, DateTime.utc_now() |> DateTime.add(amount * scale * direction, :second) |> DateTime.truncate(:second)} + {:ok, + DateTime.utc_now() + |> DateTime.add(amount * scale * direction, :second) + |> DateTime.truncate(:second)} _error -> {:error, "Parse error"} diff --git a/lib/search/bool_parser.ex b/lib/search/bool_parser.ex index 1ab611bf..547b16cf 100644 --- a/lib/search/bool_parser.ex +++ b/lib/search/bool_parser.ex @@ -15,5 +15,5 @@ defmodule Search.BoolParser do |> eos() |> label("a boolean, like `true' or `false'") - defparsec :parse, bool -end \ No newline at end of file + defparsec(:parse, bool) +end diff --git a/lib/search/date_parser.ex b/lib/search/date_parser.ex index fab45ac4..528e0f43 100644 --- a/lib/search/date_parser.ex +++ b/lib/search/date_parser.ex @@ -32,6 +32,7 @@ defmodule Search.DateParser do defp days_in_month(year, month) when month in 1..12 do Calendar.ISO.days_in_month(year, month) end + defp days_in_month(_year, _month) do 0 end @@ -80,8 +81,7 @@ defmodule Search.DateParser do with {:ok, [lower, upper]} <- date_bounds(date), {:ok, lower} <- build_datetime(lower, tz_off, tz_hour, tz_minute), - {:ok, upper} <- build_datetime(upper, tz_off, tz_hour, tz_minute) - do + {:ok, upper} <- build_datetime(upper, tz_off, tz_hour, tz_minute) do {[[lower, upper]], context} else _ -> @@ -183,7 +183,9 @@ defmodule Search.DateParser do ]) |> repeat(space) |> eos() - |> label("a RFC3339 datetime fragment, like `2019-01-01', or relative date, like `3 days ago'") + |> label( + "a RFC3339 datetime fragment, like `2019-01-01', or relative date, like `3 days ago'" + ) - defparsec :parse, date + defparsec(:parse, date) end diff --git a/lib/search/evaluator.ex b/lib/search/evaluator.ex index 5fabc406..ecd1d3bc 100644 --- a/lib/search/evaluator.ex +++ b/lib/search/evaluator.ex @@ -16,13 +16,16 @@ defmodule Search.Evaluator do range_query[term] |> Enum.all?(fn {:gt, query_val} -> - Enum.any?(doc_values, & &1 > query_val) + Enum.any?(doc_values, &(&1 > query_val)) + {:gte, query_val} -> - Enum.any?(doc_values, & &1 >= query_val) + Enum.any?(doc_values, &(&1 >= query_val)) + {:lt, query_val} -> - Enum.any?(doc_values, & &1 < query_val) + Enum.any?(doc_values, &(&1 < query_val)) + {:lte, query_val} -> - Enum.any?(doc_values, & &1 <= query_val) + Enum.any?(doc_values, &(&1 <= query_val)) end) end @@ -110,12 +113,15 @@ defmodule Search.Evaluator do end # Avoid pursuing excessively time-consuming substrings - defp levenshtein_execute(s1, s2, lookup, times) when times > 2, do: {max(byte_size(s1), byte_size(s2)), lookup} + defp levenshtein_execute(s1, s2, lookup, times) when times > 2, + do: {max(byte_size(s1), byte_size(s2)), lookup} + defp levenshtein_execute("", s2, lookup, _times), do: {byte_size(s2), lookup} defp levenshtein_execute(s1, "", lookup, _times), do: {byte_size(s1), lookup} defp levenshtein_execute(s1, s1, lookup, _times), do: {0, lookup} + defp levenshtein_execute(s1, s2, lookup, times) do - {deletion, lookup} = levenshtein_lookup(chop(s1), s2, lookup, times + 1) + {deletion, lookup} = levenshtein_lookup(chop(s1), s2, lookup, times + 1) {insertion, lookup} = levenshtein_lookup(s1, chop(s2), lookup, times + 1) {substitution, lookup} = levenshtein_lookup(chop(s1), chop(s2), lookup, times + 1) @@ -132,17 +138,26 @@ defmodule Search.Evaluator do end defp chop(str) when is_binary(str), do: binary_part(str, 0, byte_size(str) - 1) - defp last_bytes_different?(s1, s2) when binary_part(s1, byte_size(s1) - 1, 1) == binary_part(s2, byte_size(s2) - 1, 1), do: 0 + + defp last_bytes_different?(s1, s2) + when binary_part(s1, byte_size(s1) - 1, 1) == binary_part(s2, byte_size(s2) - 1, 1), + do: 0 + defp last_bytes_different?(_s1, _s2), do: 1 defp wildcard_to_regex(input) do re = input - |> String.replace(~r/([.+^$\[\]\\\(\){}|-])/, "\\\\\\1") # escape regex metacharacters - |> String.replace(~r/([^\\]|[^\\](?:\\\\)+)\*/, "\\1.*") # * -> .* (kleene star) - |> String.replace(~r/\A(?:\\\\)*\*/, ".*") # * -> .* (kleene star) - |> String.replace(~r/([^\\]|[^\\](?:\\\\)+)\?/, "\\1.?") # ? -> .? (concatenation/alternation) - |> String.replace(~r/\A(?:\\\\)*\?/, ".?") # ? -> .? (concatenation/alternation) + # escape regex metacharacters + |> String.replace(~r/([.+^$\[\]\\\(\){}|-])/, "\\\\\\1") + # * -> .* (kleene star) + |> String.replace(~r/([^\\]|[^\\](?:\\\\)+)\*/, "\\1.*") + # * -> .* (kleene star) + |> String.replace(~r/\A(?:\\\\)*\*/, ".*") + # ? -> .? (concatenation/alternation) + |> String.replace(~r/([^\\]|[^\\](?:\\\\)+)\?/, "\\1.?") + # ? -> .? (concatenation/alternation) + |> String.replace(~r/\A(?:\\\\)*\?/, ".?") Regex.compile!("\\A#{re}\\z", "im") end diff --git a/lib/search/float_parser.ex b/lib/search/float_parser.ex index 157feb2a..c9be9eeb 100644 --- a/lib/search/float_parser.ex +++ b/lib/search/float_parser.ex @@ -27,12 +27,16 @@ defmodule Search.FloatParser do float_parser = choice([ - float |> concat(fuzz) |> concat(unsigned_float) |> reduce(:range) |> unwrap_and_tag(:float_range), + float + |> concat(fuzz) + |> concat(unsigned_float) + |> reduce(:range) + |> unwrap_and_tag(:float_range), float |> unwrap_and_tag(:float) ]) |> repeat(space) |> eos() |> label("a real number, like `2.7182818' or `-10'") - defparsec :parse, float_parser + defparsec(:parse, float_parser) end diff --git a/lib/search/helpers.ex b/lib/search/helpers.ex index c2d66d8f..92a6db70 100644 --- a/lib/search/helpers.ex +++ b/lib/search/helpers.ex @@ -23,4 +23,4 @@ defmodule Search.Helpers do def range([center, deviation]) do [center - deviation, center + deviation] end -end \ No newline at end of file +end diff --git a/lib/search/int_parser.ex b/lib/search/int_parser.ex index 61756a50..5499bd62 100644 --- a/lib/search/int_parser.ex +++ b/lib/search/int_parser.ex @@ -27,5 +27,5 @@ defmodule Search.IntParser do |> eos() |> label("an integer, like `3' or `-10'") - defparsec :parse, int_parser + defparsec(:parse, int_parser) end diff --git a/lib/search/ip_parser.ex b/lib/search/ip_parser.ex index a537c8a6..2cf301be 100644 --- a/lib/search/ip_parser.ex +++ b/lib/search/ip_parser.ex @@ -139,5 +139,5 @@ defmodule Search.IpParser do |> eos() |> label("a valid IPv4 or IPv6 address and optional CIDR prefix") - defparsec :parse, ip -end \ No newline at end of file + defparsec(:parse, ip) +end diff --git a/lib/search/lexer.ex b/lib/search/lexer.ex index 925182a4..7b56573e 100644 --- a/lib/search/lexer.ex +++ b/lib/search/lexer.ex @@ -64,12 +64,14 @@ defmodule Search.Lexer do quoted_text = ignore(quot) - |> repeat(choice([ - ignore(string("\\")) |> string("\""), - ignore(string("\\")) |> string("\\"), - string("\\") |> utf8_char([]), - utf8_char(not: ?") - ])) + |> repeat( + choice([ + ignore(string("\\")) |> string("\""), + ignore(string("\\")) |> string("\\"), + string("\\") |> utf8_char([]), + utf8_char(not: ?") + ]) + ) |> ignore(quot) |> reduce({List, :to_string, []}) |> unwrap_and_tag(:term) @@ -97,5 +99,5 @@ defmodule Search.Lexer do repeat(outer) |> eos() - defparsec :lex, search + defparsec(:lex, search) end diff --git a/lib/search/literal_parser.ex b/lib/search/literal_parser.ex index 8db31d95..934a4967 100644 --- a/lib/search/literal_parser.ex +++ b/lib/search/literal_parser.ex @@ -55,5 +55,5 @@ defmodule Search.LiteralParser do wildcard ]) - defparsec :parse, literal + defparsec(:parse, literal) end diff --git a/lib/search/ngram_parser.ex b/lib/search/ngram_parser.ex index 370e1e42..65857b22 100644 --- a/lib/search/ngram_parser.ex +++ b/lib/search/ngram_parser.ex @@ -3,4 +3,4 @@ defmodule Search.NgramParser do # Dummy stub. Used for convenient parser implementation. def parse(input), do: LiteralParser.parse(input) -end \ No newline at end of file +end diff --git a/lib/search/parser.ex b/lib/search/parser.ex index 980a2e82..92ff2578 100644 --- a/lib/search/parser.ex +++ b/lib/search/parser.ex @@ -30,15 +30,16 @@ defmodule Search.Parser do def parser(options) do parser = struct(Parser, options) + fields = Enum.map(parser.bool_fields, fn f -> {f, BoolParser} end) ++ - Enum.map(parser.date_fields, fn f -> {f, DateParser} end) ++ - Enum.map(parser.float_fields, fn f -> {f, FloatParser} end) ++ - Enum.map(parser.int_fields, fn f -> {f, IntParser} end) ++ - Enum.map(parser.ip_fields, fn f -> {f, IpParser} end) ++ - Enum.map(parser.literal_fields, fn f -> {f, LiteralParser} end) ++ - Enum.map(parser.ngram_fields, fn f -> {f, NgramParser} end) ++ - Enum.map(parser.custom_fields, fn f -> {f, :custom_field} end) + Enum.map(parser.date_fields, fn f -> {f, DateParser} end) ++ + Enum.map(parser.float_fields, fn f -> {f, FloatParser} end) ++ + Enum.map(parser.int_fields, fn f -> {f, IntParser} end) ++ + Enum.map(parser.ip_fields, fn f -> {f, IpParser} end) ++ + Enum.map(parser.literal_fields, fn f -> {f, LiteralParser} end) ++ + Enum.map(parser.ngram_fields, fn f -> {f, NgramParser} end) ++ + Enum.map(parser.custom_fields, fn f -> {f, :custom_field} end) %{parser | __fields__: Map.new(fields)} end @@ -54,8 +55,7 @@ defmodule Search.Parser do parser = %{parser | __data__: context} with {:ok, tokens, _1, _2, _3, _4} <- Lexer.lex(input), - {:ok, {tree, []}} <- search_top(parser, tokens) - do + {:ok, {tree, []}} <- search_top(parser, tokens) do {:ok, tree} else {:ok, {_tree, tokens}} -> @@ -69,7 +69,7 @@ defmodule Search.Parser do err -> err - #{:error, "unknown parsing error"} + # {:error, "unknown parsing error"} end end @@ -87,8 +87,7 @@ defmodule Search.Parser do defp search_or(parser, tokens) do with {:ok, {left, [{:or, _} | r_tokens]}} <- search_and(parser, tokens), - {:ok, {right, rest}} <- search_or(parser, r_tokens) - do + {:ok, {right, rest}} <- search_or(parser, r_tokens) do {:ok, {flatten_disjunction_child(left, right), rest}} else value -> @@ -98,8 +97,7 @@ defmodule Search.Parser do defp search_and(parser, tokens) do with {:ok, {left, [{:and, _} | r_tokens]}} <- search_boost(parser, tokens), - {:ok, {right, rest}} <- search_and(parser, r_tokens) - do + {:ok, {right, rest}} <- search_and(parser, r_tokens) do {:ok, {flatten_conjunction_child(left, right), rest}} else value -> @@ -160,8 +158,7 @@ defmodule Search.Parser do end end - defp search_field(_parser, _tokens), do: - {:error, "Expected a term."} + defp search_field(_parser, _tokens), do: {:error, "Expected a term."} # # Predictive LL(k) RD parser for search terms in parent grammar @@ -169,7 +166,7 @@ defmodule Search.Parser do defp field_top(parser, tokens), do: field_term(parser, tokens) - defp field_term(parser, [custom_field: field_name, range: :eq, value: value]) do + defp field_term(parser, custom_field: field_name, range: :eq, value: value) do case parser.transforms[field_name].(parser.__data__, String.trim(value)) do {:ok, child} -> {:ok, {child, []}} @@ -187,7 +184,7 @@ defmodule Search.Parser do err -> err - end + end end # Types which do not support ranges @@ -196,7 +193,13 @@ defmodule Search.Parser do do: {:ok, {%{term: %{field(parser, field_name) => normalize_value(parser, value)}}, []}} defp field_type(parser, [{LiteralParser, field_name}, range: :eq, literal: value, fuzz: fuzz]), - do: {:ok, {%{fuzzy: %{field(parser, field_name) => %{value: normalize_value(parser, value), fuzziness: fuzz}}}, []}} + do: + {:ok, + {%{ + fuzzy: %{ + field(parser, field_name) => %{value: normalize_value(parser, value), fuzziness: fuzz} + } + }, []}} defp field_type(_parser, [{LiteralParser, _field_name}, range: :eq, wildcard: "*"]), do: {:ok, {%{match_all: %{}}, []}} @@ -204,12 +207,13 @@ defmodule Search.Parser do defp field_type(parser, [{LiteralParser, field_name}, range: :eq, wildcard: value]), do: {:ok, {%{wildcard: %{field(parser, field_name) => normalize_value(parser, value)}}, []}} - defp field_type(parser, [{NgramParser, field_name}, range: :eq, literal: value]), - do: {:ok, {%{match_phrase: %{field(parser, field_name) => normalize_value(parser, value)}}, []}} + do: + {:ok, {%{match_phrase: %{field(parser, field_name) => normalize_value(parser, value)}}, []}} defp field_type(parser, [{NgramParser, field_name}, range: :eq, literal: value, fuzz: _fuzz]), - do: {:ok, {%{match_phrase: %{field(parser, field_name) => normalize_value(parser, value)}}, []}} + do: + {:ok, {%{match_phrase: %{field(parser, field_name) => normalize_value(parser, value)}}, []}} defp field_type(_parser, [{NgramParser, _field_name}, range: :eq, wildcard: "*"]), do: {:ok, {%{match_all: %{}}, []}} @@ -217,14 +221,12 @@ defmodule Search.Parser do defp field_type(parser, [{NgramParser, field_name}, range: :eq, wildcard: value]), do: {:ok, {%{wildcard: %{field(parser, field_name) => normalize_value(parser, value)}}, []}} - defp field_type(parser, [{BoolParser, field_name}, range: :eq, bool: value]), do: {:ok, {%{term: %{field(parser, field_name) => value}}, []}} defp field_type(parser, [{IpParser, field_name}, range: :eq, ip: value]), do: {:ok, {%{term: %{field(parser, field_name) => value}}, []}} - # Types which do support ranges defp field_type(parser, [{IntParser, field_name}, range: :eq, int: value]), @@ -239,7 +241,6 @@ defmodule Search.Parser do defp field_type(_parser, [{IntParser, field_name}, range: _range, int_range: _value]), do: {:error, "multiple ranges specified for " <> field_name} - defp field_type(parser, [{FloatParser, field_name}, range: :eq, float: value]), do: {:ok, {%{term: %{field(parser, field_name) => value}}, []}} @@ -252,16 +253,16 @@ defmodule Search.Parser do defp field_type(_parser, [{FloatParser, field_name}, range: _range, float_range: _value]), do: {:error, "multiple ranges specified for " <> field_name} - defp field_type(parser, [{DateParser, field_name}, range: :eq, date: [lower, upper]]), do: {:ok, {%{range: %{field(parser, field_name) => %{gte: lower, lt: upper}}}, []}} - defp field_type(parser, [{DateParser, field_name}, range: r, date: [_lower, upper]]) when r in [:lte, :gt], - do: {:ok, {%{range: %{field(parser, field_name) => %{r => upper}}}, []}} - - defp field_type(parser, [{DateParser, field_name}, range: r, date: [lower, _upper]]) when r in [:gte, :lt], - do: {:ok, {%{range: %{field(parser, field_name) => %{r => lower}}}, []}} + defp field_type(parser, [{DateParser, field_name}, range: r, date: [_lower, upper]]) + when r in [:lte, :gt], + do: {:ok, {%{range: %{field(parser, field_name) => %{r => upper}}}, []}} + defp field_type(parser, [{DateParser, field_name}, range: r, date: [lower, _upper]]) + when r in [:gte, :lt], + do: {:ok, {%{range: %{field(parser, field_name) => %{r => lower}}}, []}} defp field(parser, field_name) do parser.aliases[field_name] || field_name @@ -275,23 +276,23 @@ defmodule Search.Parser do # Flattens the child of a disjunction or conjunction to improve performance. defp flatten_disjunction_child(this_child, %{bool: %{should: next_child}} = child) - when child == %{bool: %{should: next_child}} and is_list(next_child), - do: %{bool: %{should: [this_child | next_child]}} + when child == %{bool: %{should: next_child}} and is_list(next_child), + do: %{bool: %{should: [this_child | next_child]}} defp flatten_disjunction_child(this_child, next_child), do: %{bool: %{should: [this_child, next_child]}} defp flatten_conjunction_child(this_child, %{bool: %{must: next_child}} = child) - when child == %{bool: %{must: next_child}} and is_list(next_child), - do: %{bool: %{must: [this_child | next_child]}} + when child == %{bool: %{must: next_child}} and is_list(next_child), + do: %{bool: %{must: [this_child | next_child]}} defp flatten_conjunction_child(this_child, next_child), do: %{bool: %{must: [this_child, next_child]}} # Flattens the child of a negation to eliminate double negation. defp flatten_negation_child(%{bool: %{must_not: next_child}} = child) - when child == %{bool: %{must_not: next_child}} and is_map(next_child), - do: next_child + when child == %{bool: %{must_not: next_child}} and is_map(next_child), + do: next_child defp flatten_negation_child(next_child), do: %{bool: %{must_not: next_child}} diff --git a/lib/search/term_range_parser.ex b/lib/search/term_range_parser.ex index a67a27e3..eaa6b5ba 100644 --- a/lib/search/term_range_parser.ex +++ b/lib/search/term_range_parser.ex @@ -23,16 +23,22 @@ defmodule Search.TermRangeParser do case input do <<^field_name::binary-size(field_sz), ":", value::binary>> -> [{field_parser, field_name}, range: :eq, value: String.trim(value)] + <<^field_name::binary-size(field_sz), ".eq:", value::binary>> -> [{field_parser, field_name}, range: :eq, value: String.trim(value)] + <<^field_name::binary-size(field_sz), ".gt:", value::binary>> -> [{field_parser, field_name}, range: :gt, value: String.trim(value)] + <<^field_name::binary-size(field_sz), ".gte:", value::binary>> -> [{field_parser, field_name}, range: :gte, value: String.trim(value)] + <<^field_name::binary-size(field_sz), ".lt:", value::binary>> -> [{field_parser, field_name}, range: :lt, value: String.trim(value)] + <<^field_name::binary-size(field_sz), ".lte:", value::binary>> -> [{field_parser, field_name}, range: :lte, value: String.trim(value)] + _ -> nil end diff --git a/lib/textile/lexer.ex b/lib/textile/lexer.ex index a11c23fd..53a9fc0c 100644 --- a/lib/textile/lexer.ex +++ b/lib/textile/lexer.ex @@ -1,8 +1,7 @@ defmodule Textile.Lexer do import NimbleParsec - space = - utf8_char('\f \r\t\u00a0\u1680\u180e\u202f\u205f\u3000' ++ Enum.to_list(0x2000..0x200a)) + space = utf8_char('\f \r\t\u00a0\u1680\u180e\u202f\u205f\u3000' ++ Enum.to_list(0x2000..0x200A)) extended_space = choice([ @@ -26,11 +25,9 @@ defmodule Textile.Lexer do string("\n") |> unwrap_and_tag(:newline) - link_ending_characters = - utf8_char('@#$%&(),.:;<=?\\`|\'') + link_ending_characters = utf8_char('@#$%&(),.:;<=?\\`|\'') - bracket_link_ending_characters = - utf8_char('" []') + bracket_link_ending_characters = utf8_char('" []') end_of_link = choice([ @@ -173,7 +170,8 @@ defmodule Textile.Lexer do sup_delim = string("^") |> unwrap_and_tag(:sup_delim) sub_delim = string("~") |> unwrap_and_tag(:sub_delim) - del_delim = lookahead_not(string("-"), choice([string("-"), string(">")])) |> unwrap_and_tag(:del_delim) + del_delim = + lookahead_not(string("-"), choice([string("-"), string(">")])) |> unwrap_and_tag(:del_delim) quicktxt = utf8_char('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz*@_{}') @@ -234,5 +232,5 @@ defmodule Textile.Lexer do |> repeat() |> eos() - defparsec :lex, textile + defparsec(:lex, textile) end diff --git a/lib/textile/parser.ex b/lib/textile/parser.ex index b1720212..e1c2f09d 100644 --- a/lib/textile/parser.ex +++ b/lib/textile/parser.ex @@ -6,8 +6,7 @@ defmodule Textile.Parser do parser = Map.put(parser, :state, %{}) with {:ok, tokens, _1, _2, _3, _4} <- Lexer.lex(String.trim(input || "")), - {:ok, tree, []} <- repeat(&textile/2, parser, tokens) - do + {:ok, tree, []} <- repeat(&textile/2, parser, tokens) do partial_flatten(tree) else _ -> @@ -65,7 +64,9 @@ defmodule Textile.Parser do # # open_token callback* close_token # - defp simple_recursive(open_token, close_token, open_tag, close_tag, callback, parser, [{open_token, open} | r_tokens]) do + defp simple_recursive(open_token, close_token, open_tag, close_tag, callback, parser, [ + {open_token, open} | r_tokens + ]) do case repeat(callback, parser, r_tokens) do {:ok, tree, [{^close_token, _} | r2_tokens]} -> {:ok, [{:markup, open_tag}, tree, {:markup, close_tag}], r2_tokens} @@ -74,7 +75,16 @@ defmodule Textile.Parser do {:ok, [{:text, escape(open)}, tree], r2_tokens} end end - defp simple_recursive(_open_token, _close_token, _open_tag, _close_tag, _callback, _parser, _tokens) do + + defp simple_recursive( + _open_token, + _close_token, + _open_tag, + _close_tag, + _callback, + _parser, + _tokens + ) do {:error, "Expected a simple recursive rule"} end @@ -82,7 +92,17 @@ defmodule Textile.Parser do # # open_token callback* close_token (?!lookahead_not) # - defp simple_lookahead_not(open_token, close_token, open_tag, close_tag, lookahead_not, callback, state, parser, [{open_token, open} | r_tokens]) do + defp simple_lookahead_not( + open_token, + close_token, + open_tag, + close_tag, + lookahead_not, + callback, + state, + parser, + [{open_token, open} | r_tokens] + ) do case parser.state do %{^state => _} -> {:error, "End of rule"} @@ -95,7 +115,8 @@ defmodule Textile.Parser do _ -> case repeat(callback, put_state(parser, state), r_tokens) do {:ok, tree, [{^close_token, close}, {^lookahead_not, ln} | r2_tokens]} -> - {:ok, [{:text, escape(open)}, tree, {:text, escape(close)}], [{lookahead_not, ln} | r2_tokens]} + {:ok, [{:text, escape(open)}, tree, {:text, escape(close)}], + [{lookahead_not, ln} | r2_tokens]} {:ok, tree, [{^close_token, _} | r2_tokens]} -> {:ok, [{:markup, open_tag}, tree, {:markup, close_tag}], r2_tokens} @@ -106,7 +127,18 @@ defmodule Textile.Parser do end end end - defp simple_lookahead_not(_open_token, _close_token, _open_tag, _close_tag, _lookahead_not, _callback, _state, _parser, _tokens) do + + defp simple_lookahead_not( + _open_token, + _close_token, + _open_tag, + _close_tag, + _lookahead_not, + _callback, + _state, + _parser, + _tokens + ) do {:error, "Expected a simple lookahead not rule"} end @@ -115,6 +147,7 @@ defmodule Textile.Parser do defp assemble_binary(token_type, accumulator, [{token_type, t} | stream]) do assemble_binary(token_type, accumulator <> <>, stream) end + defp assemble_binary(_token_type, accumulator, tokens), do: {accumulator, tokens} # @@ -159,54 +192,88 @@ defmodule Textile.Parser do end end) |> case do - nil -> inner_inline_textile_element(parser, tokens) + nil -> inner_inline_textile_element(parser, tokens) value -> value end end defp inner_inline_textile_element(parser, [{token, t}, {:quicktxt, q} | r_tokens]) - when token in [:b_delim, :i_delim, :strong_delim, :em_delim, :ins_delim, :sup_delim, :del_delim, :sub_delim] - do + when token in [ + :b_delim, + :i_delim, + :strong_delim, + :em_delim, + :ins_delim, + :sup_delim, + :del_delim, + :sub_delim + ] do case inline_textile_element(parser, [{:quicktxt, q} | r_tokens]) do {:ok, tree, r2_tokens} -> {:ok, [{:text, escape(t)}, tree], r2_tokens} - _ -> + _ -> {:ok, [{:text, escape(t)}], [{:quicktxt, q} | r_tokens]} end end + defp inner_inline_textile_element(parser, [{:link_delim, open} | r_tokens]) do case repeat(&block_textile_element/2, parser, r_tokens) do {:ok, tree, [{:unbracketed_link_url, <<"\":", url::binary>>} | r2_tokens]} -> href = escape(url) - {:ok, [{:markup, ""}, tree, {:markup, ""}], r2_tokens} + {:ok, + [{:markup, ""}, tree, {:markup, ""}], + r2_tokens} {:ok, tree, r2_tokens} -> {:ok, [{:text, escape(open)}, tree], r2_tokens} end end + defp inner_inline_textile_element(parser, [{:bracketed_link_open, open} | r_tokens]) do case repeat(&inline_textile_element/2, parser, r_tokens) do {:ok, tree, [{:bracketed_link_url, <<"\":", url::binary>>} | r2_tokens]} -> href = escape(url) - {:ok, [{:markup, ""}, tree, {:markup, ""}], r2_tokens} + {:ok, + [{:markup, ""}, tree, {:markup, ""}], + r2_tokens} {:ok, tree, r2_tokens} -> {:ok, [{:text, escape(open)}, tree], r2_tokens} end end - defp inner_inline_textile_element(parser, [{token, img}, {:unbracketed_image_url, <<":", url::binary>>} | r_tokens]) when token in [:unbracketed_image, :bracketed_image] do + + defp inner_inline_textile_element(parser, [ + {token, img}, + {:unbracketed_image_url, <<":", url::binary>>} | r_tokens + ]) + when token in [:unbracketed_image, :bracketed_image] do img = parser.image_transform.(img) - {:ok, [{:markup, ""}], r_tokens} + {:ok, + [ + {:markup, ""} + ], r_tokens} end - defp inner_inline_textile_element(parser, [{token, img} | r_tokens]) when token in [:unbracketed_image, :bracketed_image] do + + defp inner_inline_textile_element(parser, [{token, img} | r_tokens]) + when token in [:unbracketed_image, :bracketed_image] do img = parser.image_transform.(img) - {:ok, [{:markup, ""}], r_tokens} + {:ok, + [ + {:markup, ""} + ], r_tokens} end + defp inner_inline_textile_element(parser, [{:code_delim, open} | r_tokens]) do case parser.state do %{code: _} -> @@ -222,6 +289,7 @@ defmodule Textile.Parser do end end end + defp inner_inline_textile_element(parser, tokens) do inline_textile_element_not_opening_markup(parser, tokens) end @@ -235,18 +303,23 @@ defmodule Textile.Parser do defp bq_cite_text(_parser, [{:bq_cite_open, _open} | _rest]) do {:error, "Expected cite tokens"} end + defp bq_cite_text(_parser, [{:char, lit} | r_tokens]) do {:ok, [{:text, <>}], r_tokens} end + defp bq_cite_text(_parser, [{:quicktxt, lit} | r_tokens]) do {:ok, [{:text, <>}], r_tokens} end + defp bq_cite_text(_parser, [{:space, _} | r_tokens]) do {:ok, [{:text, " "}], r_tokens} end + defp bq_cite_text(_parser, [{_token, t} | r_tokens]) do {:ok, [{:text, t}], r_tokens} end + defp bq_cite_text(_parser, _tokens) do {:error, "Expected cite tokens"} end @@ -260,24 +333,43 @@ defmodule Textile.Parser do # defp inline_textile_element_not_opening_markup(_parser, [{:literal, lit} | r_tokens]) do - {:ok, [{:markup, ""}, {:markup, escape(lit)}, {:markup, ""}], r_tokens} + {:ok, [{:markup, ""}, {:markup, escape(lit)}, {:markup, ""}], + r_tokens} end + defp inline_textile_element_not_opening_markup(_parser, [{:space, _} | r_tokens]) do {:ok, [{:text, " "}], r_tokens} end + defp inline_textile_element_not_opening_markup(_parser, [{:char, lit} | r_tokens]) do {binary, r2_tokens} = assemble_binary(:char, <>, r_tokens) {:ok, [{:text, escape(binary)}], r2_tokens} end - defp inline_textile_element_not_opening_markup(_parser, [{:quicktxt, q1}, {token, t}, {:quicktxt, q2} | r_tokens]) - when token in [:b_delim, :i_delim, :strong_delim, :em_delim, :ins_delim, :sup_delim, :del_delim, :sub_delim] - do - {:ok, [{:text, escape(<>)}, {:text, escape(t)}, {:text, escape(<>)}], r_tokens} + + defp inline_textile_element_not_opening_markup(_parser, [ + {:quicktxt, q1}, + {token, t}, + {:quicktxt, q2} | r_tokens + ]) + when token in [ + :b_delim, + :i_delim, + :strong_delim, + :em_delim, + :ins_delim, + :sup_delim, + :del_delim, + :sub_delim + ] do + {:ok, [{:text, escape(<>)}, {:text, escape(t)}, {:text, escape(<>)}], + r_tokens} end + defp inline_textile_element_not_opening_markup(_parser, [{:quicktxt, lit} | r_tokens]) do {:ok, [{:text, escape(<>)}], r_tokens} end + defp inline_textile_element_not_opening_markup(parser, [{:bq_cite_start, start} | r_tokens]) do case repeat(&bq_cite_text/2, parser, r_tokens) do {:ok, tree, [{:bq_cite_open, open} | r2_tokens]} -> @@ -285,22 +377,38 @@ defmodule Textile.Parser do {:ok, tree2, [{:bq_close, _} | r3_tokens]} -> cite = escape(flatten(tree)) - {:ok, [{:markup, "
"}, tree2, {:markup, "
"}], r3_tokens} + {:ok, + [ + {:markup, "
"}, + tree2, + {:markup, "
"} + ], r3_tokens} {:ok, tree2, r3_tokens} -> - {:ok, [{:text, escape(start)}, {:text, escape(flatten(tree))}, {:text, escape(open)}, tree2], r3_tokens} + {:ok, + [ + {:text, escape(start)}, + {:text, escape(flatten(tree))}, + {:text, escape(open)}, + tree2 + ], r3_tokens} _ -> - {:ok, [{:text, escape(start)}, {:text, escape(flatten(tree))}, {:text, escape(open)}], r_tokens} + {:ok, [{:text, escape(start)}, {:text, escape(flatten(tree))}, {:text, escape(open)}], + r_tokens} end _ -> {:ok, [{:text, escape(start)}], r_tokens} end end + defp inline_textile_element_not_opening_markup(_parser, [{:bq_cite_open, tok} | r_tokens]) do {:ok, [{:text, escape(tok)}], r_tokens} end + defp inline_textile_element_not_opening_markup(parser, tokens) do [ {:bq_open, :bq_close, "
", "
"}, @@ -344,9 +452,11 @@ defmodule Textile.Parser do defp block_textile_element(_parser, [{:double_newline, _} | r_tokens]) do {:ok, [{:markup, "

"}], r_tokens} end + defp block_textile_element(_parser, [{:newline, _} | r_tokens]) do {:ok, [{:markup, "
"}], r_tokens} end + defp block_textile_element(parser, tokens) do inline_textile_element(parser, tokens) end diff --git a/mix.exs b/mix.exs index 4523a88d..f65fc990 100644 --- a/mix.exs +++ b/mix.exs @@ -75,7 +75,12 @@ defmodule Philomena.MixProject do defp aliases do [ "ecto.setup": ["ecto.create", "ecto.load", "run priv/repo/seeds.exs"], - "ecto.setup_dev": ["ecto.create", "ecto.load", "run priv/repo/seeds.exs", "run priv/repo/seeds_development.exs"], + "ecto.setup_dev": [ + "ecto.create", + "ecto.load", + "run priv/repo/seeds.exs", + "run priv/repo/seeds_development.exs" + ], "ecto.reset": ["ecto.drop", "ecto.setup"], "ecto.migrate": ["ecto.migrate", "ecto.dump"], "ecto.rollback": ["ecto.rollback", "ecto.dump"], diff --git a/priv/repo/seeds.exs b/priv/repo/seeds.exs index 00417061..25584b8b 100644 --- a/priv/repo/seeds.exs +++ b/priv/repo/seeds.exs @@ -10,12 +10,26 @@ # We recommend using the bang functions (`insert!`, `update!` # and so on) as they will fail if something goes wrong. -alias Philomena.{Repo, Comments.Comment, Filters.Filter, Forums.Forum, Galleries.Gallery, Posts.Post, Images.Image, Reports.Report, Roles.Role, Tags.Tag, Users.User} +alias Philomena.{ + Repo, + Comments.Comment, + Filters.Filter, + Forums.Forum, + Galleries.Gallery, + Posts.Post, + Images.Image, + Reports.Report, + Roles.Role, + Tags.Tag, + Users.User +} + alias Philomena.Elasticsearch alias Philomena.Tags import Ecto.Query -IO.puts "---- Creating Elasticsearch indices" +IO.puts("---- Creating Elasticsearch indices") + for model <- [Image, Comment, Gallery, Tag, Post, Report] do Elasticsearch.delete_index!(model) Elasticsearch.create_index!(model) @@ -26,14 +40,16 @@ resources = |> File.read!() |> Jason.decode!() -IO.puts "---- Generating rating tags" +IO.puts("---- Generating rating tags") + for tag_name <- resources["rating_tags"] do %Tag{category: "rating"} |> Tag.creation_changeset(%{name: tag_name}) |> Repo.insert(on_conflict: :nothing) end -IO.puts "---- Generating system filters" +IO.puts("---- Generating system filters") + for filter_def <- resources["system_filters"] do spoilered_tag_list = Enum.join(filter_def["spoilered"], ",") hidden_tag_list = Enum.join(filter_def["hidden"], ",") @@ -48,28 +64,31 @@ for filter_def <- resources["system_filters"] do |> Repo.insert(on_conflict: :nothing) end -IO.puts "---- Generating forums" +IO.puts("---- Generating forums") + for forum_def <- resources["forums"] do %Forum{} |> Forum.changeset(forum_def) |> Repo.insert(on_conflict: :nothing) end -IO.puts "---- Generating users" +IO.puts("---- Generating users") + for user_def <- resources["users"] do %User{role: user_def["role"]} |> User.creation_changeset(user_def) |> Repo.insert(on_conflict: :nothing) end -IO.puts "---- Generating roles" +IO.puts("---- Generating roles") + for role_def <- resources["roles"] do %Role{name: role_def["name"], resource_type: role_def["resource_type"]} |> Role.changeset(%{}) |> Repo.insert(on_conflict: :nothing) end -IO.puts "---- Indexing content" +IO.puts("---- Indexing content") Elasticsearch.reindex(Tag |> preload(^Tags.indexing_preloads()), Tag) -IO.puts "---- Done." +IO.puts("---- Done.")