account.rb 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: accounts
  5. #
  6. # id :integer not null, primary key
  7. # username :string default(""), not null
  8. # domain :string
  9. # secret :string default(""), not null
  10. # private_key :text
  11. # public_key :text default(""), not null
  12. # remote_url :string default(""), not null
  13. # salmon_url :string default(""), not null
  14. # hub_url :string default(""), not null
  15. # created_at :datetime not null
  16. # updated_at :datetime not null
  17. # note :text default(""), not null
  18. # display_name :string default(""), not null
  19. # uri :string default(""), not null
  20. # url :string
  21. # avatar_file_name :string
  22. # avatar_content_type :string
  23. # avatar_file_size :integer
  24. # avatar_updated_at :datetime
  25. # header_file_name :string
  26. # header_content_type :string
  27. # header_file_size :integer
  28. # header_updated_at :datetime
  29. # avatar_remote_url :string
  30. # subscription_expires_at :datetime
  31. # silenced :boolean default(FALSE), not null
  32. # suspended :boolean default(FALSE), not null
  33. # locked :boolean default(FALSE), not null
  34. # header_remote_url :string default(""), not null
  35. # statuses_count :integer default(0), not null
  36. # followers_count :integer default(0), not null
  37. # following_count :integer default(0), not null
  38. # last_webfingered_at :datetime
  39. #
  40. class Account < ApplicationRecord
  41. include Targetable
  42. MENTION_RE = /(?:^|[^\/\w])@([a-z0-9_]+(?:@[a-z0-9\.\-]+[a-z0-9]+)?)/i
  43. IMAGE_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif'].freeze
  44. # Local users
  45. has_one :user, inverse_of: :account
  46. validates :username, presence: true, format: { with: /\A[a-z0-9_]+\z/i }, uniqueness: { scope: :domain, case_sensitive: false }, length: { maximum: 30 }, if: 'local?'
  47. validates :username, presence: true, uniqueness: { scope: :domain, case_sensitive: true }, unless: 'local?'
  48. # Avatar upload
  49. has_attached_file :avatar, styles: ->(f) { avatar_styles(f) }, convert_options: { all: '-quality 80 -strip' }
  50. validates_attachment_content_type :avatar, content_type: IMAGE_MIME_TYPES
  51. validates_attachment_size :avatar, less_than: 2.megabytes
  52. # Header upload
  53. has_attached_file :header, styles: ->(f) { header_styles(f) }, convert_options: { all: '-quality 80 -strip' }
  54. validates_attachment_content_type :header, content_type: IMAGE_MIME_TYPES
  55. validates_attachment_size :header, less_than: 2.megabytes
  56. include Attachmentable
  57. # Local user profile validations
  58. validates :display_name, length: { maximum: 30 }, if: 'local?'
  59. validates :note, length: { maximum: 160 }, if: 'local?'
  60. # Timelines
  61. has_many :stream_entries, inverse_of: :account, dependent: :destroy
  62. has_many :statuses, inverse_of: :account, dependent: :destroy
  63. has_many :favourites, inverse_of: :account, dependent: :destroy
  64. has_many :mentions, inverse_of: :account, dependent: :destroy
  65. has_many :notifications, inverse_of: :account, dependent: :destroy
  66. # Follow relations
  67. has_many :follow_requests, dependent: :destroy
  68. has_many :active_relationships, class_name: 'Follow', foreign_key: 'account_id', dependent: :destroy
  69. has_many :passive_relationships, class_name: 'Follow', foreign_key: 'target_account_id', dependent: :destroy
  70. has_many :following, -> { order('follows.id desc') }, through: :active_relationships, source: :target_account
  71. has_many :followers, -> { order('follows.id desc') }, through: :passive_relationships, source: :account
  72. # Block relationships
  73. has_many :block_relationships, class_name: 'Block', foreign_key: 'account_id', dependent: :destroy
  74. has_many :blocking, -> { order('blocks.id desc') }, through: :block_relationships, source: :target_account
  75. has_many :blocked_by_relationships, class_name: 'Block', foreign_key: :target_account_id, dependent: :destroy
  76. has_many :blocked_by, -> { order('blocks.id desc') }, through: :blocked_by_relationships, source: :account
  77. # Mute relationships
  78. has_many :mute_relationships, class_name: 'Mute', foreign_key: 'account_id', dependent: :destroy
  79. has_many :muting, -> { order('mutes.id desc') }, through: :mute_relationships, source: :target_account
  80. # Media
  81. has_many :media_attachments, dependent: :destroy
  82. # PuSH subscriptions
  83. has_many :subscriptions, dependent: :destroy
  84. # Report relationships
  85. has_many :reports
  86. has_many :targeted_reports, class_name: 'Report', foreign_key: :target_account_id
  87. scope :remote, -> { where.not(domain: nil) }
  88. scope :local, -> { where(domain: nil) }
  89. scope :without_followers, -> { where(followers_count: 0) }
  90. scope :with_followers, -> { where('followers_count > 0') }
  91. scope :expiring, ->(time) { where(subscription_expires_at: nil).or(where('subscription_expires_at < ?', time)).remote.with_followers }
  92. scope :partitioned, -> { order('row_number() over (partition by domain)') }
  93. scope :silenced, -> { where(silenced: true) }
  94. scope :suspended, -> { where(suspended: true) }
  95. scope :recent, -> { reorder(id: :desc) }
  96. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  97. scope :by_domain_accounts, -> { group(:domain).select(:domain, 'COUNT(*) AS accounts_count').order('accounts_count desc') }
  98. delegate :email,
  99. :current_sign_in_ip,
  100. :current_sign_in_at,
  101. :confirmed?,
  102. to: :user,
  103. prefix: true,
  104. allow_nil: true
  105. delegate :allowed_languages, to: :user, prefix: false, allow_nil: true
  106. def follow!(other_account)
  107. active_relationships.where(target_account: other_account).first_or_create!(target_account: other_account)
  108. end
  109. def block!(other_account)
  110. block_relationships.where(target_account: other_account).first_or_create!(target_account: other_account)
  111. end
  112. def mute!(other_account)
  113. mute_relationships.where(target_account: other_account).first_or_create!(target_account: other_account)
  114. end
  115. def unfollow!(other_account)
  116. follow = active_relationships.find_by(target_account: other_account)
  117. follow&.destroy
  118. end
  119. def unblock!(other_account)
  120. block = block_relationships.find_by(target_account: other_account)
  121. block&.destroy
  122. end
  123. def unmute!(other_account)
  124. mute = mute_relationships.find_by(target_account: other_account)
  125. mute&.destroy
  126. end
  127. def following?(other_account)
  128. following.include?(other_account)
  129. end
  130. def blocking?(other_account)
  131. blocking.include?(other_account)
  132. end
  133. def muting?(other_account)
  134. muting.include?(other_account)
  135. end
  136. def requested?(other_account)
  137. follow_requests.where(target_account: other_account).exists?
  138. end
  139. def local?
  140. domain.nil?
  141. end
  142. def acct
  143. local? ? username : "#{username}@#{domain}"
  144. end
  145. def local_username_and_domain
  146. "#{username}@#{Rails.configuration.x.local_domain}"
  147. end
  148. def to_webfinger_s
  149. "acct:#{local_username_and_domain}"
  150. end
  151. def subscribed?
  152. subscription_expires_at.present?
  153. end
  154. def followers_domains
  155. followers.reorder(nil).pluck('distinct accounts.domain')
  156. end
  157. def favourited?(status)
  158. status.proper.favourites.where(account: self).count.positive?
  159. end
  160. def reblogged?(status)
  161. status.proper.reblogs.where(account: self).count.positive?
  162. end
  163. def keypair
  164. private_key.nil? ? OpenSSL::PKey::RSA.new(public_key) : OpenSSL::PKey::RSA.new(private_key)
  165. end
  166. def subscription(webhook_url)
  167. OStatus2::Subscription.new(remote_url, secret: secret, lease_seconds: 86_400 * 30, webhook: webhook_url, hub: hub_url)
  168. end
  169. def save_with_optional_avatar!
  170. save!
  171. rescue ActiveRecord::RecordInvalid
  172. self.avatar = nil
  173. self.header = nil
  174. self[:avatar_remote_url] = ''
  175. self[:header_remote_url] = ''
  176. save!
  177. end
  178. def avatar_original_url
  179. avatar.url(:original)
  180. end
  181. def avatar_static_url
  182. avatar_content_type == 'image/gif' ? avatar.url(:static) : avatar_original_url
  183. end
  184. def header_original_url
  185. header.url(:original)
  186. end
  187. def header_static_url
  188. header_content_type == 'image/gif' ? header.url(:static) : header_original_url
  189. end
  190. def avatar_remote_url=(url)
  191. parsed_url = Addressable::URI.parse(url).normalize
  192. return if !%w(http https).include?(parsed_url.scheme) || parsed_url.host.empty? || self[:avatar_remote_url] == url
  193. self.avatar = URI.parse(parsed_url.to_s)
  194. self[:avatar_remote_url] = url
  195. rescue OpenURI::HTTPError => e
  196. Rails.logger.debug "Error fetching remote avatar: #{e}"
  197. end
  198. def header_remote_url=(url)
  199. parsed_url = Addressable::URI.parse(url).normalize
  200. return if !%w(http https).include?(parsed_url.scheme) || parsed_url.host.empty? || self[:header_remote_url] == url
  201. self.header = URI.parse(parsed_url.to_s)
  202. self[:header_remote_url] = url
  203. rescue OpenURI::HTTPError => e
  204. Rails.logger.debug "Error fetching remote header: #{e}"
  205. end
  206. def object_type
  207. :person
  208. end
  209. def to_param
  210. username
  211. end
  212. def excluded_from_timeline_account_ids
  213. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  214. end
  215. class << self
  216. def find_local!(username)
  217. find_remote!(username, nil)
  218. end
  219. def find_remote!(username, domain)
  220. return if username.blank?
  221. where('lower(accounts.username) = ?', username.downcase).where(domain.nil? ? { domain: nil } : 'lower(accounts.domain) = ?', domain&.downcase).take!
  222. end
  223. def find_local(username)
  224. find_local!(username)
  225. rescue ActiveRecord::RecordNotFound
  226. nil
  227. end
  228. def find_remote(username, domain)
  229. find_remote!(username, domain)
  230. rescue ActiveRecord::RecordNotFound
  231. nil
  232. end
  233. def triadic_closures(account, limit = 5)
  234. sql = <<-SQL.squish
  235. WITH first_degree AS (
  236. SELECT target_account_id
  237. FROM follows
  238. WHERE account_id = :account_id
  239. )
  240. SELECT accounts.*
  241. FROM follows
  242. INNER JOIN accounts ON follows.target_account_id = accounts.id
  243. WHERE account_id IN (SELECT * FROM first_degree) AND target_account_id NOT IN (SELECT * FROM first_degree) AND target_account_id <> :account_id
  244. GROUP BY target_account_id, accounts.id
  245. ORDER BY count(account_id) DESC
  246. LIMIT :limit
  247. SQL
  248. find_by_sql(
  249. [sql, { account_id: account.id, limit: limit }]
  250. )
  251. end
  252. def search_for(terms, limit = 10)
  253. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  254. textsearch = '(setweight(to_tsvector(\'simple\', accounts.display_name), \'A\') || setweight(to_tsvector(\'simple\', accounts.username), \'B\') || setweight(to_tsvector(\'simple\', coalesce(accounts.domain, \'\')), \'C\'))'
  255. query = 'to_tsquery(\'simple\', \'\'\' \' || ' + terms + ' || \' \'\'\' || \':*\')'
  256. sql = <<-SQL.squish
  257. SELECT
  258. accounts.*,
  259. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  260. FROM accounts
  261. WHERE #{query} @@ #{textsearch}
  262. ORDER BY rank DESC
  263. LIMIT ?
  264. SQL
  265. Account.find_by_sql([sql, limit])
  266. end
  267. def advanced_search_for(terms, account, limit = 10)
  268. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  269. textsearch = '(setweight(to_tsvector(\'simple\', accounts.display_name), \'A\') || setweight(to_tsvector(\'simple\', accounts.username), \'B\') || setweight(to_tsvector(\'simple\', coalesce(accounts.domain, \'\')), \'C\'))'
  270. query = 'to_tsquery(\'simple\', \'\'\' \' || ' + terms + ' || \' \'\'\' || \':*\')'
  271. sql = <<-SQL.squish
  272. SELECT
  273. accounts.*,
  274. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  275. FROM accounts
  276. LEFT OUTER JOIN follows AS f ON (accounts.id = f.account_id AND f.target_account_id = ?) OR (accounts.id = f.target_account_id AND f.account_id = ?)
  277. WHERE #{query} @@ #{textsearch}
  278. GROUP BY accounts.id
  279. ORDER BY rank DESC
  280. LIMIT ?
  281. SQL
  282. Account.find_by_sql([sql, account.id, account.id, limit])
  283. end
  284. def following_map(target_account_ids, account_id)
  285. follow_mapping(Follow.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  286. end
  287. def followed_by_map(target_account_ids, account_id)
  288. follow_mapping(Follow.where(account_id: target_account_ids, target_account_id: account_id), :account_id)
  289. end
  290. def blocking_map(target_account_ids, account_id)
  291. follow_mapping(Block.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  292. end
  293. def muting_map(target_account_ids, account_id)
  294. follow_mapping(Mute.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  295. end
  296. def requested_map(target_account_ids, account_id)
  297. follow_mapping(FollowRequest.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  298. end
  299. private
  300. def follow_mapping(query, field)
  301. query.pluck(field).each_with_object({}) { |id, mapping| mapping[id] = true }
  302. end
  303. def avatar_styles(file)
  304. styles = { original: '120x120#' }
  305. styles[:static] = { format: 'png' } if file.content_type == 'image/gif'
  306. styles
  307. end
  308. def header_styles(file)
  309. styles = { original: '700x335#' }
  310. styles[:static] = { format: 'png' } if file.content_type == 'image/gif'
  311. styles
  312. end
  313. end
  314. before_create :generate_keys
  315. before_validation :normalize_domain
  316. private
  317. def generate_keys
  318. return unless local?
  319. keypair = OpenSSL::PKey::RSA.new(Rails.env.test? ? 1024 : 2048)
  320. self.private_key = keypair.to_pem
  321. self.public_key = keypair.public_key.to_pem
  322. end
  323. def normalize_domain
  324. return if local?
  325. self.domain = TagManager.instance.normalize_domain(domain)
  326. end
  327. end