You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

335 lines
11 KiB

8 years ago
8 years ago
8 years ago
8 years ago
  1. # frozen_string_literal: true
  2. class Account < ApplicationRecord
  3. include Targetable
  4. MENTION_RE = /(?:^|[^\/\w])@([a-z0-9_]+(?:@[a-z0-9\.\-]+[a-z0-9]+)?)/i
  5. IMAGE_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif'].freeze
  6. # Local users
  7. has_one :user, inverse_of: :account
  8. validates :username, presence: true, format: { with: /\A[a-z0-9_]+\z/i, message: 'only letters, numbers and underscores' }, uniqueness: { scope: :domain, case_sensitive: false }, length: { maximum: 30 }, if: 'local?'
  9. validates :username, presence: true, uniqueness: { scope: :domain, case_sensitive: true }, unless: 'local?'
  10. # Avatar upload
  11. has_attached_file :avatar, styles: ->(f) { avatar_styles(f) }, convert_options: { all: '-quality 80 -strip' }
  12. validates_attachment_content_type :avatar, content_type: IMAGE_MIME_TYPES
  13. validates_attachment_size :avatar, less_than: 2.megabytes
  14. # Header upload
  15. has_attached_file :header, styles: ->(f) { header_styles(f) }, convert_options: { all: '-quality 80 -strip' }
  16. validates_attachment_content_type :header, content_type: IMAGE_MIME_TYPES
  17. validates_attachment_size :header, less_than: 2.megabytes
  18. # Local user profile validations
  19. validates :display_name, length: { maximum: 30 }, if: 'local?'
  20. validates :note, length: { maximum: 160 }, if: 'local?'
  21. # Timelines
  22. has_many :stream_entries, inverse_of: :account, dependent: :destroy
  23. has_many :statuses, inverse_of: :account, dependent: :destroy
  24. has_many :favourites, inverse_of: :account, dependent: :destroy
  25. has_many :mentions, inverse_of: :account, dependent: :destroy
  26. has_many :notifications, inverse_of: :account, dependent: :destroy
  27. # Follow relations
  28. has_many :follow_requests, dependent: :destroy
  29. has_many :active_relationships, class_name: 'Follow', foreign_key: 'account_id', dependent: :destroy
  30. has_many :passive_relationships, class_name: 'Follow', foreign_key: 'target_account_id', dependent: :destroy
  31. has_many :following, -> { order('follows.id desc') }, through: :active_relationships, source: :target_account
  32. has_many :followers, -> { order('follows.id desc') }, through: :passive_relationships, source: :account
  33. # Block relationships
  34. has_many :block_relationships, class_name: 'Block', foreign_key: 'account_id', dependent: :destroy
  35. has_many :blocking, -> { order('blocks.id desc') }, through: :block_relationships, source: :target_account
  36. # Mute relationships
  37. has_many :mute_relationships, class_name: 'Mute', foreign_key: 'account_id', dependent: :destroy
  38. has_many :muting, -> { order('mutes.id desc') }, through: :mute_relationships, source: :target_account
  39. # Media
  40. has_many :media_attachments, dependent: :destroy
  41. # PuSH subscriptions
  42. has_many :subscriptions, dependent: :destroy
  43. # Report relationships
  44. has_many :reports
  45. has_many :targeted_reports, class_name: 'Report', foreign_key: :target_account_id
  46. scope :remote, -> { where.not(domain: nil) }
  47. scope :local, -> { where(domain: nil) }
  48. scope :without_followers, -> { where('(select count(f.id) from follows as f where f.target_account_id = accounts.id) = 0') }
  49. scope :with_followers, -> { where('(select count(f.id) from follows as f where f.target_account_id = accounts.id) > 0') }
  50. scope :expiring, ->(time) { where(subscription_expires_at: nil).or(where('subscription_expires_at < ?', time)).remote.with_followers }
  51. scope :silenced, -> { where(silenced: true) }
  52. scope :suspended, -> { where(suspended: true) }
  53. scope :recent, -> { reorder(id: :desc) }
  54. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  55. scope :by_domain_accounts, -> { group(:domain).select(:domain, 'COUNT(*) AS accounts_count').order('accounts_count desc') }
  56. def follow!(other_account)
  57. active_relationships.where(target_account: other_account).first_or_create!(target_account: other_account)
  58. end
  59. def block!(other_account)
  60. block_relationships.where(target_account: other_account).first_or_create!(target_account: other_account)
  61. end
  62. def mute!(other_account)
  63. mute_relationships.where(target_account: other_account).first_or_create!(target_account: other_account)
  64. end
  65. def unfollow!(other_account)
  66. follow = active_relationships.find_by(target_account: other_account)
  67. follow&.destroy
  68. end
  69. def unblock!(other_account)
  70. block = block_relationships.find_by(target_account: other_account)
  71. block&.destroy
  72. end
  73. def unmute!(other_account)
  74. mute = mute_relationships.find_by(target_account: other_account)
  75. mute&.destroy
  76. end
  77. def following?(other_account)
  78. following.include?(other_account)
  79. end
  80. def blocking?(other_account)
  81. blocking.include?(other_account)
  82. end
  83. def muting?(other_account)
  84. muting.include?(other_account)
  85. end
  86. def requested?(other_account)
  87. follow_requests.where(target_account: other_account).exists?
  88. end
  89. def local?
  90. domain.nil?
  91. end
  92. def acct
  93. local? ? username : "#{username}@#{domain}"
  94. end
  95. def local_username_and_domain
  96. "#{username}@#{Rails.configuration.x.local_domain}"
  97. end
  98. def to_webfinger_s
  99. "acct:#{local_username_and_domain}"
  100. end
  101. def subscribed?
  102. !subscription_expires_at.blank?
  103. end
  104. def favourited?(status)
  105. status.proper.favourites.where(account: self).count.positive?
  106. end
  107. def reblogged?(status)
  108. status.proper.reblogs.where(account: self).count.positive?
  109. end
  110. def keypair
  111. private_key.nil? ? OpenSSL::PKey::RSA.new(public_key) : OpenSSL::PKey::RSA.new(private_key)
  112. end
  113. def subscription(webhook_url)
  114. OStatus2::Subscription.new(remote_url, secret: secret, lease_seconds: 86_400 * 30, webhook: webhook_url, hub: hub_url)
  115. end
  116. def save_with_optional_avatar!
  117. save!
  118. rescue ActiveRecord::RecordInvalid
  119. self.avatar = nil
  120. self.header = nil
  121. self[:avatar_remote_url] = ''
  122. self[:header_remote_url] = ''
  123. save!
  124. end
  125. def avatar_original_url
  126. avatar.url(:original)
  127. end
  128. def avatar_static_url
  129. avatar_content_type == 'image/gif' ? avatar.url(:static) : avatar_original_url
  130. end
  131. def header_original_url
  132. header.url(:original)
  133. end
  134. def header_static_url
  135. header_content_type == 'image/gif' ? header.url(:static) : header_original_url
  136. end
  137. def avatar_remote_url=(url)
  138. parsed_url = URI.parse(url)
  139. return if !%w(http https).include?(parsed_url.scheme) || parsed_url.host.empty? || self[:avatar_remote_url] == url
  140. self.avatar = parsed_url
  141. self[:avatar_remote_url] = url
  142. rescue OpenURI::HTTPError => e
  143. Rails.logger.debug "Error fetching remote avatar: #{e}"
  144. end
  145. def header_remote_url=(url)
  146. parsed_url = URI.parse(url)
  147. return if !%w(http https).include?(parsed_url.scheme) || parsed_url.host.empty? || self[:header_remote_url] == url
  148. self.header = parsed_url
  149. self[:header_remote_url] = url
  150. rescue OpenURI::HTTPError => e
  151. Rails.logger.debug "Error fetching remote header: #{e}"
  152. end
  153. def object_type
  154. :person
  155. end
  156. def to_param
  157. username
  158. end
  159. class << self
  160. def find_local!(username)
  161. find_remote!(username, nil)
  162. end
  163. def find_remote!(username, domain)
  164. return if username.blank?
  165. where('lower(accounts.username) = ?', username.downcase).where(domain.nil? ? { domain: nil } : 'lower(accounts.domain) = ?', domain&.downcase).take!
  166. end
  167. def find_local(username)
  168. find_local!(username)
  169. rescue ActiveRecord::RecordNotFound
  170. nil
  171. end
  172. def find_remote(username, domain)
  173. find_remote!(username, domain)
  174. rescue ActiveRecord::RecordNotFound
  175. nil
  176. end
  177. def triadic_closures(account, limit = 5)
  178. sql = <<-SQL.squish
  179. WITH first_degree AS (
  180. SELECT target_account_id
  181. FROM follows
  182. WHERE account_id = :account_id
  183. )
  184. SELECT accounts.*
  185. FROM follows
  186. INNER JOIN accounts ON follows.target_account_id = accounts.id
  187. WHERE account_id IN (SELECT * FROM first_degree) AND target_account_id NOT IN (SELECT * FROM first_degree) AND target_account_id <> :account_id
  188. GROUP BY target_account_id, accounts.id
  189. ORDER BY count(account_id) DESC
  190. LIMIT :limit
  191. SQL
  192. find_by_sql(
  193. [sql, { account_id: account.id, limit: limit }]
  194. )
  195. end
  196. def search_for(terms, limit = 10)
  197. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  198. textsearch = '(setweight(to_tsvector(\'simple\', accounts.display_name), \'A\') || setweight(to_tsvector(\'simple\', accounts.username), \'B\') || setweight(to_tsvector(\'simple\', coalesce(accounts.domain, \'\')), \'C\'))'
  199. query = 'to_tsquery(\'simple\', \'\'\' \' || ' + terms + ' || \' \'\'\' || \':*\')'
  200. sql = <<-SQL.squish
  201. SELECT
  202. accounts.*,
  203. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  204. FROM accounts
  205. WHERE #{query} @@ #{textsearch}
  206. ORDER BY rank DESC
  207. LIMIT ?
  208. SQL
  209. Account.find_by_sql([sql, limit])
  210. end
  211. def advanced_search_for(terms, account, limit = 10)
  212. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  213. textsearch = '(setweight(to_tsvector(\'simple\', accounts.display_name), \'A\') || setweight(to_tsvector(\'simple\', accounts.username), \'B\') || setweight(to_tsvector(\'simple\', coalesce(accounts.domain, \'\')), \'C\'))'
  214. query = 'to_tsquery(\'simple\', \'\'\' \' || ' + terms + ' || \' \'\'\' || \':*\')'
  215. sql = <<-SQL.squish
  216. SELECT
  217. accounts.*,
  218. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  219. FROM accounts
  220. 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 = ?)
  221. WHERE #{query} @@ #{textsearch}
  222. GROUP BY accounts.id
  223. ORDER BY rank DESC
  224. LIMIT ?
  225. SQL
  226. Account.find_by_sql([sql, account.id, account.id, limit])
  227. end
  228. def following_map(target_account_ids, account_id)
  229. follow_mapping(Follow.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  230. end
  231. def followed_by_map(target_account_ids, account_id)
  232. follow_mapping(Follow.where(account_id: target_account_ids, target_account_id: account_id), :account_id)
  233. end
  234. def blocking_map(target_account_ids, account_id)
  235. follow_mapping(Block.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  236. end
  237. def muting_map(target_account_ids, account_id)
  238. follow_mapping(Mute.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  239. end
  240. def requested_map(target_account_ids, account_id)
  241. follow_mapping(FollowRequest.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  242. end
  243. private
  244. def follow_mapping(query, field)
  245. query.pluck(field).inject({}) { |mapping, id| mapping[id] = true; mapping }
  246. end
  247. def avatar_styles(file)
  248. styles = { original: '120x120#' }
  249. styles[:static] = { format: 'png' } if file.content_type == 'image/gif'
  250. styles
  251. end
  252. def header_styles(file)
  253. styles = { original: '700x335#' }
  254. styles[:static] = { format: 'png' } if file.content_type == 'image/gif'
  255. styles
  256. end
  257. end
  258. before_create do
  259. if local?
  260. keypair = OpenSSL::PKey::RSA.new(Rails.env.test? ? 1024 : 2048)
  261. self.private_key = keypair.to_pem
  262. self.public_key = keypair.public_key.to_pem
  263. end
  264. end
  265. end