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.

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