Commit 4afbef39 authored by lain's avatar lain

Format the code.

parent 480932c8
......@@ -6,14 +6,11 @@
use Mix.Config
# General application configuration
config :pleroma,
ecto_repos: [Pleroma.Repo]
config :pleroma, ecto_repos: [Pleroma.Repo]
config :pleroma, Pleroma.Repo,
types: Pleroma.PostgresTypes
config :pleroma, Pleroma.Repo, types: Pleroma.PostgresTypes
config :pleroma, Pleroma.Upload,
uploads: "uploads"
config :pleroma, Pleroma.Upload, uploads: "uploads"
# Configures the endpoint
config :pleroma, Pleroma.Web.Endpoint,
......@@ -21,8 +18,7 @@ config :pleroma, Pleroma.Web.Endpoint,
protocol: "https",
secret_key_base: "aK4Abxf29xU9TTDKre9coZPUgevcVCFQJe/5xP/7Lt4BEif6idBIbjupVbOrbKxl",
render_errors: [view: Pleroma.Web.ErrorView, accepts: ~w(json)],
pubsub: [name: Pleroma.PubSub,
adapter: Phoenix.PubSub.PG2]
pubsub: [name: Pleroma.PubSub, adapter: Phoenix.PubSub.PG2]
# Configures Elixir's Logger
config :logger, :console,
......@@ -38,15 +34,15 @@ config :pleroma, :websub, Pleroma.Web.Websub
config :pleroma, :ostatus, Pleroma.Web.OStatus
config :pleroma, :httpoison, Pleroma.HTTP
version = with {version, 0} <- System.cmd("git", ["rev-parse", "HEAD"]) do
"Pleroma #{Mix.Project.config[:version]} #{String.trim(version)}"
else
_ -> "Pleroma #{Mix.Project.config[:version]} dev"
end
version =
with {version, 0} <- System.cmd("git", ["rev-parse", "HEAD"]) do
"Pleroma #{Mix.Project.config()[:version]} #{String.trim(version)}"
else
_ -> "Pleroma #{Mix.Project.config()[:version]} dev"
end
# Configures http settings, upstream proxy etc.
config :pleroma, :http,
proxy_url: nil
config :pleroma, :http, proxy_url: nil
config :pleroma, :instance,
version: version,
......@@ -59,16 +55,15 @@ config :pleroma, :instance,
config :pleroma, :media_proxy,
enabled: false,
redirect_on_failure: true
#base_url: "https://cache.pleroma.social"
config :pleroma, :chat,
enabled: true
# base_url: "https://cache.pleroma.social"
config :pleroma, :chat, enabled: true
config :ecto, json_library: Jason
config :phoenix, :format_encoders,
json: Jason
config :phoenix, :format_encoders, json: Jason
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env}.exs"
import_config "#{Mix.env()}.exs"
......@@ -7,7 +7,10 @@ use Mix.Config
# watchers to your application. For example, we use it
# with brunch.io to recompile .js and .css sources.
config :pleroma, Pleroma.Web.Endpoint,
http: [port: 4000, protocol_options: [max_request_line_length: 8192, max_header_value_length: 8192]],
http: [
port: 4000,
protocol_options: [max_request_line_length: 8192, max_header_value_length: 8192]
],
protocol: "http",
debug_errors: true,
code_reloader: true,
......@@ -49,5 +52,8 @@ config :pleroma, Pleroma.Repo,
try do
import_config "dev.secret.exs"
rescue
_-> IO.puts("!!! RUNNING IN LOCALHOST DEV MODE! !!!\nFEDERATION WON'T WORK UNTIL YOU CONFIGURE A dev.secret.exs")
_ ->
IO.puts(
"!!! RUNNING IN LOCALHOST DEV MODE! !!!\nFEDERATION WON'T WORK UNTIL YOU CONFIGURE A dev.secret.exs"
)
end
......@@ -9,8 +9,7 @@ config :pleroma, Pleroma.Web.Endpoint,
# Print only warnings and errors during test
config :logger, level: :warn
config :pleroma, Pleroma.Upload,
uploads: "test/uploads"
config :pleroma, Pleroma.Upload, uploads: "test/uploads"
# Configure your database
config :pleroma, Pleroma.Repo,
......@@ -21,7 +20,6 @@ config :pleroma, Pleroma.Repo,
hostname: System.get_env("DB_HOST") || "localhost",
pool: Ecto.Adapters.SQL.Sandbox
# Reduce hash rounds for testing
config :comeonin, :pbkdf2_rounds, 1
......
Postgrex.Types.define(Pleroma.PostgresTypes, [] ++ Ecto.Adapters.Postgres.extensions(), json: Jason)
Postgrex.Types.define(
Pleroma.PostgresTypes,
[] ++ Ecto.Adapters.Postgres.extensions(),
json: Jason
)
......@@ -8,12 +8,16 @@ defmodule Mix.Tasks.FixApUsers do
def run([]) do
Mix.Task.run("app.start")
q = from u in User,
where: fragment("? @> ?", u.info, ^%{"ap_enabled" => true}),
where: u.local == false
q =
from(
u in User,
where: fragment("? @> ?", u.info, ^%{"ap_enabled" => true}),
where: u.local == false
)
users = Repo.all(q)
Enum.each(users, fn(user) ->
Enum.each(users, fn user ->
try do
IO.puts("Fetching #{user.nickname}")
Pleroma.Web.ActivityPub.Transmogrifier.upgrade_user_from_ap_id(user.ap_id, false)
......
......@@ -5,27 +5,51 @@ defmodule Mix.Tasks.GenerateConfig do
def run(_) do
IO.puts("Answer a few questions to generate a new config\n")
IO.puts("--- THIS WILL OVERWRITE YOUR config/generated_config.exs! ---\n")
domain = IO.gets("What is your domain name? (e.g. pleroma.soykaf.com): ") |> String.trim
name = IO.gets("What is the name of your instance? (e.g. Pleroma/Soykaf): ") |> String.trim
email = IO.gets("What's your admin email address: ") |> String.trim
mediaproxy = IO.gets("Do you want to activate the mediaproxy? (y/N): ")
|> String.trim()
|> String.downcase()
|> String.starts_with?("y")
proxy_url = if mediaproxy do
IO.gets("What is the mediaproxy's URL? (e.g. https://cache.example.com): ") |> String.trim
else
"https://cache.example.com"
end
secret = :crypto.strong_rand_bytes(64) |> Base.encode64 |> binary_part(0, 64)
dbpass = :crypto.strong_rand_bytes(64) |> Base.encode64 |> binary_part(0, 64)
resultSql = EEx.eval_file("lib/mix/tasks/sample_psql.eex", [dbpass: dbpass])
result = EEx.eval_file("lib/mix/tasks/sample_config.eex", [domain: domain, email: email, name: name, secret: secret, mediaproxy: mediaproxy, proxy_url: proxy_url, dbpass: dbpass])
IO.puts("\nWriting config to config/generated_config.exs.\n\nCheck it and configure your database, then copy it to either config/dev.secret.exs or config/prod.secret.exs")
domain = IO.gets("What is your domain name? (e.g. pleroma.soykaf.com): ") |> String.trim()
name = IO.gets("What is the name of your instance? (e.g. Pleroma/Soykaf): ") |> String.trim()
email = IO.gets("What's your admin email address: ") |> String.trim()
mediaproxy =
IO.gets("Do you want to activate the mediaproxy? (y/N): ")
|> String.trim()
|> String.downcase()
|> String.starts_with?("y")
proxy_url =
if mediaproxy do
IO.gets("What is the mediaproxy's URL? (e.g. https://cache.example.com): ")
|> String.trim()
else
"https://cache.example.com"
end
secret = :crypto.strong_rand_bytes(64) |> Base.encode64() |> binary_part(0, 64)
dbpass = :crypto.strong_rand_bytes(64) |> Base.encode64() |> binary_part(0, 64)
resultSql = EEx.eval_file("lib/mix/tasks/sample_psql.eex", dbpass: dbpass)
result =
EEx.eval_file(
"lib/mix/tasks/sample_config.eex",
domain: domain,
email: email,
name: name,
secret: secret,
mediaproxy: mediaproxy,
proxy_url: proxy_url,
dbpass: dbpass
)
IO.puts(
"\nWriting config to config/generated_config.exs.\n\nCheck it and configure your database, then copy it to either config/dev.secret.exs or config/prod.secret.exs"
)
File.write("config/generated_config.exs", result)
IO.puts("\nWriting setup_db.psql, please run it as postgre superuser, i.e.: sudo su postgres -c 'psql -f config/setup_db.psql'")
IO.puts(
"\nWriting setup_db.psql, please run it as postgre superuser, i.e.: sudo su postgres -c 'psql -f config/setup_db.psql'"
)
File.write("config/setup_db.psql", resultSql)
end
end
......@@ -9,11 +9,20 @@ defmodule Mix.Tasks.GeneratePasswordReset do
with %User{local: true} = user <- User.get_by_nickname(nickname),
{:ok, token} <- Pleroma.PasswordResetToken.create_token(user) do
IO.puts "Generated password reset token for #{user.nickname}"
IO.puts "Url: #{Pleroma.Web.Router.Helpers.util_url(Pleroma.Web.Endpoint, :show_password_reset, token.token)}"
IO.puts("Generated password reset token for #{user.nickname}")
IO.puts(
"Url: #{
Pleroma.Web.Router.Helpers.util_url(
Pleroma.Web.Endpoint,
:show_password_reset,
token.token
)
}"
)
else
_ ->
IO.puts "No local user #{nickname}"
IO.puts("No local user #{nickname}")
end
end
end
......@@ -7,21 +7,24 @@ defmodule Mix.Tasks.SetModerator do
def run([nickname | rest]) do
ensure_started(Repo, [])
moderator = case rest do
[moderator] -> moderator == "true"
_ -> true
end
moderator =
case rest do
[moderator] -> moderator == "true"
_ -> true
end
with %User{local: true} = user <- User.get_by_nickname(nickname) do
info = user.info
|> Map.put("is_moderator", !!moderator)
info =
user.info
|> Map.put("is_moderator", !!moderator)
cng = User.info_changeset(user, %{info: info})
user = Repo.update!(cng)
IO.puts "Moderator status of #{nickname}: #{user.info["is_moderator"]}"
IO.puts("Moderator status of #{nickname}: #{user.info["is_moderator"]}")
else
_ ->
IO.puts "No local user #{nickname}"
IO.puts("No local user #{nickname}")
end
end
end
......@@ -6,15 +6,15 @@ defmodule Pleroma.PasswordResetToken do
alias Pleroma.{User, PasswordResetToken, Repo}
schema "password_reset_tokens" do
belongs_to :user, User
field :token, :string
field :used, :boolean, default: false
belongs_to(:user, User)
field(:token, :string)
field(:used, :boolean, default: false)
timestamps()
end
def create_token(%User{} = user) do
token = :crypto.strong_rand_bytes(32) |> Base.url_encode64
token = :crypto.strong_rand_bytes(32) |> Base.url_encode64()
token = %PasswordResetToken{
user_id: user.id,
......
......@@ -4,33 +4,53 @@ defmodule Pleroma.Activity do
import Ecto.Query
schema "activities" do
field :data, :map
field :local, :boolean, default: true
field :actor, :string
field :recipients, {:array, :string}
has_many :notifications, Notification, on_delete: :delete_all
field(:data, :map)
field(:local, :boolean, default: true)
field(:actor, :string)
field(:recipients, {:array, :string})
has_many(:notifications, Notification, on_delete: :delete_all)
timestamps()
end
def get_by_ap_id(ap_id) do
Repo.one(from activity in Activity,
where: fragment("(?)->>'id' = ?", activity.data, ^to_string(ap_id)))
Repo.one(
from(
activity in Activity,
where: fragment("(?)->>'id' = ?", activity.data, ^to_string(ap_id))
)
)
end
# TODO:
# Go through these and fix them everywhere.
# Wrong name, only returns create activities
def all_by_object_ap_id_q(ap_id) do
from activity in Activity,
where: fragment("coalesce((?)->'object'->>'id', (?)->>'object') = ?", activity.data, activity.data, ^to_string(ap_id)),
from(
activity in Activity,
where:
fragment(
"coalesce((?)->'object'->>'id', (?)->>'object') = ?",
activity.data,
activity.data,
^to_string(ap_id)
),
where: fragment("(?)->>'type' = 'Create'", activity.data)
)
end
# Wrong name, returns all.
def all_non_create_by_object_ap_id_q(ap_id) do
from activity in Activity,
where: fragment("coalesce((?)->'object'->>'id', (?)->>'object') = ?", activity.data, activity.data, ^to_string(ap_id))
from(
activity in Activity,
where:
fragment(
"coalesce((?)->'object'->>'id', (?)->>'object') = ?",
activity.data,
activity.data,
^to_string(ap_id)
)
)
end
# Wrong name plz fix thx
......@@ -39,13 +59,21 @@ defmodule Pleroma.Activity do
end
def create_activity_by_object_id_query(ap_ids) do
from activity in Activity,
where: fragment("coalesce((?)->'object'->>'id', (?)->>'object') = ANY(?)", activity.data, activity.data, ^ap_ids),
from(
activity in Activity,
where:
fragment(
"coalesce((?)->'object'->>'id', (?)->>'object') = ANY(?)",
activity.data,
activity.data,
^ap_ids
),
where: fragment("(?)->>'type' = 'Create'", activity.data)
)
end
def get_create_activity_by_object_ap_id(ap_id) do
create_activity_by_object_id_query([ap_id])
|> Repo.one
|> Repo.one()
end
end
......@@ -7,23 +7,34 @@ defmodule Pleroma.Application do
import Supervisor.Spec
# Define workers and child supervisors to be supervised
children = [
# Start the Ecto repository
supervisor(Pleroma.Repo, []),
# Start the endpoint when the application starts
supervisor(Pleroma.Web.Endpoint, []),
# Start your own worker by calling: Pleroma.Worker.start_link(arg1, arg2, arg3)
# worker(Pleroma.Worker, [arg1, arg2, arg3]),
worker(Cachex, [:user_cache, [
default_ttl: 25000,
ttl_interval: 1000,
limit: 2500
]]),
worker(Pleroma.Web.Federator, []),
worker(Pleroma.Stats, []),
]
++ if Mix.env == :test, do: [], else: [worker(Pleroma.Web.Streamer, [])]
++ if !chat_enabled(), do: [], else: [worker(Pleroma.Web.ChatChannel.ChatChannelState, [])]
children =
[
# Start the Ecto repository
supervisor(Pleroma.Repo, []),
# Start the endpoint when the application starts
supervisor(Pleroma.Web.Endpoint, []),
# Start your own worker by calling: Pleroma.Worker.start_link(arg1, arg2, arg3)
# worker(Pleroma.Worker, [arg1, arg2, arg3]),
worker(Cachex, [
:user_cache,
[
default_ttl: 25000,
ttl_interval: 1000,
limit: 2500
]
]),
worker(Pleroma.Web.Federator, []),
worker(Pleroma.Stats, [])
] ++
if Mix.env() == :test,
do: [],
else:
[worker(Pleroma.Web.Streamer, [])] ++
if(
!chat_enabled(),
do: [],
else: [worker(Pleroma.Web.ChatChannel.ChatChannelState, [])]
)
# See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
# for other strategies and supported options
......
......@@ -5,19 +5,26 @@ defmodule Pleroma.Formatter do
@tag_regex ~r/\#\w+/u
def parse_tags(text, data \\ %{}) do
Regex.scan(@tag_regex, text)
|> Enum.map(fn (["#" <> tag = full_tag]) -> {full_tag, String.downcase(tag)} end)
|> (fn map -> if data["sensitive"] in [true, "True", "true", "1"], do: [{"#nsfw", "nsfw"}] ++ map, else: map end).()
|> Enum.map(fn ["#" <> tag = full_tag] -> {full_tag, String.downcase(tag)} end)
|> (fn map ->
if data["sensitive"] in [true, "True", "true", "1"],
do: [{"#nsfw", "nsfw"}] ++ map,
else: map
end).()
end
def parse_mentions(text) do
# Modified from https://www.w3.org/TR/html5/forms.html#valid-e-mail-address
regex = ~r/@[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@?[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*/u
regex =
~r/@[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@?[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*/u
Regex.scan(regex, text)
|> List.flatten
|> Enum.uniq
|> Enum.map(fn ("@" <> match = full_match) -> {full_match, User.get_cached_by_nickname(match)} end)
|> Enum.filter(fn ({_match, user}) -> user end)
|> List.flatten()
|> Enum.uniq()
|> Enum.map(fn "@" <> match = full_match ->
{full_match, User.get_cached_by_nickname(match)}
end)
|> Enum.filter(fn {_match, user} -> user end)
end
@finmoji [
......@@ -86,9 +93,9 @@ defmodule Pleroma.Formatter do
"woollysocks"
]
@finmoji_with_filenames Enum.map(@finmoji, fn (finmoji) ->
{finmoji, "/finmoji/128px/#{finmoji}-128.png"}
end)
@finmoji_with_filenames Enum.map(@finmoji, fn finmoji ->
{finmoji, "/finmoji/128px/#{finmoji}-128.png"}
end)
@emoji_from_file (with {:ok, default} <- File.read("config/emoji.txt") do
custom =
......@@ -97,31 +104,40 @@ defmodule Pleroma.Formatter do
else
_e -> ""
end
(default <> "\n" <> custom)
|> String.trim()
|> String.split(~r/\n+/)
|> Enum.map(fn(line) ->
|> Enum.map(fn line ->
[name, file] = String.split(line, ~r/,\s*/)
{name, file}
end)
end)
else
_ -> []
end)
end)
@emoji @finmoji_with_filenames ++ @emoji_from_file
def emojify(text, emoji \\ @emoji)
def emojify(text, nil), do: text
def emojify(text, emoji) do
Enum.reduce(emoji, text, fn ({emoji, file}, text) ->
Enum.reduce(emoji, text, fn {emoji, file}, text ->
emoji = HtmlSanitizeEx.strip_tags(emoji)
file = HtmlSanitizeEx.strip_tags(file)
String.replace(text, ":#{emoji}:", "<img height='32px' width='32px' alt='#{emoji}' title='#{emoji}' src='#{MediaProxy.url(file)}' />")
String.replace(
text,
":#{emoji}:",
"<img height='32px' width='32px' alt='#{emoji}' title='#{emoji}' src='#{
MediaProxy.url(file)
}' />"
)
end)
end
def get_emoji(text) do
Enum.filter(@emoji, fn ({emoji, _}) -> String.contains?(text, ":#{emoji}:") end)
Enum.filter(@emoji, fn {emoji, _} -> String.contains?(text, ":#{emoji}:") end)
end
def get_custom_emoji() do
......@@ -141,59 +157,71 @@ defmodule Pleroma.Formatter do
@doc "changes http:... links to html links"
def add_links({subs, text}) do
links = Regex.scan(@link_regex, text)
|> Enum.map(fn ([url]) -> {Ecto.UUID.generate, url} end)
links =
Regex.scan(@link_regex, text)
|> Enum.map(fn [url] -> {Ecto.UUID.generate(), url} end)
uuid_text = links
|> Enum.reduce(text, fn({uuid, url}, acc) -> String.replace(acc, url, uuid) end)
uuid_text =
links
|> Enum.reduce(text, fn {uuid, url}, acc -> String.replace(acc, url, uuid) end)
subs = subs ++ Enum.map(links, fn({uuid, url}) ->
{uuid, "<a href='#{url}'>#{url}</a>"}
end)
subs =
subs ++
Enum.map(links, fn {uuid, url} ->
{uuid, "<a href='#{url}'>#{url}</a>"}
end)
{subs, uuid_text}
end
@doc "Adds the links to mentioned users"
def add_user_links({subs, text}, mentions) do
mentions = mentions
|> Enum.sort_by(fn ({name, _}) -> -String.length(name) end)
|> Enum.map(fn({name, user}) -> {name, user, Ecto.UUID.generate} end)
uuid_text = mentions
|> Enum.reduce(text, fn ({match, _user, uuid}, text) ->
String.replace(text, match, uuid)
end)
subs = subs ++ Enum.map(mentions, fn ({match, %User{ap_id: ap_id}, uuid}) ->
short_match = String.split(match, "@") |> tl() |> hd()
{uuid, "<span><a href='#{ap_id}'>@<span>#{short_match}</span></a></span>"}
end)
mentions =
mentions
|> Enum.sort_by(fn {name, _} -> -String.length(name) end)
|> Enum.map(fn {name, user} -> {name, user, Ecto.UUID.generate()} end)
uuid_text =
mentions
|> Enum.reduce(text, fn {match, _user, uuid}, text ->
String.replace(text, match, uuid)
end)
subs =
subs ++
Enum.map(mentions, fn {match, %User{ap_id: ap_id}, uuid} ->
short_match = String.split(match, "@") |> tl() |> hd()
{uuid, "<span><a href='#{ap_id}'>@<span>#{short_match}</span></a></span>"}
end)
{subs, uuid_text}
end
@doc "Adds the hashtag links"
def add_hashtag_links({subs, text}, tags) do
tags = tags
|> Enum.sort_by(fn ({name, _}) -> -String.length(name) end)
|> Enum.map(fn({name, short}) -> {name, short, Ecto.UUID.generate} end)
uuid_text = tags
|> Enum.reduce(text, fn ({match, _short, uuid}, text) ->
String.replace(text, match, uuid)
end)
subs = subs ++ Enum.map(tags, fn ({_, tag, uuid}) ->
url = "<a href='#{Pleroma.Web.base_url}/tag/#{tag}' rel='tag'>##{tag}</a>"
{uuid, url}
end)
tags =
tags
|> Enum.sort_by(fn {name, _} -> -String.length(name) end)
|> Enum.map(fn {name, short} -> {name, short, Ecto.UUID.generate()} end)
uuid_text =
tags
|> Enum.reduce(text, fn {match, _short, uuid}, text ->
String.replace(text, match, uuid)
end)
subs =
subs ++
Enum.map(tags, fn {_, tag, uuid} ->
url = "<a href='#{Pleroma.Web.base_url()}/tag/#{tag}' rel='tag'>##{tag}</a>"
{uuid, url}
end)
{subs, uuid_text}
end
def finalize({subs, text}) do
Enum.reduce(subs, text, fn({uuid, replacement}, result_text) ->
Enum.reduce(subs, text, fn {uuid, replacement}, result_text ->
String.replace(result_text, uuid, replacement)
end)
end
......
defmodule Pleroma.HTTP do
use HTTPoison.Base
def process_request_options(options) do
config = Application.get_env(:pleroma, :http, [])
proxy = Keyword.get(config, :proxy_url, nil)
case proxy do
nil -> options
_ -> options ++ [proxy: proxy]
end
end
end
......@@ -4,75 +4,89 @@ defmodule Pleroma.Notification do
import Ecto.Query
schema "notifications" do
field :seen, :boolean, default: false
belongs_to :user, Pleroma.User
belongs_to :activity, Pleroma.Activity
field(:seen, :boolean, default: false)