闭社主体 forked from https://github.com/tootsuite/mastodon
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.

353 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, 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. 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 favourited?(status)
  106. status.proper.favourites.where(account: self).count.positive?
  107. end
  108. def reblogged?(status)
  109. status.proper.reblogs.where(account: self).count.positive?
  110. end
  111. def keypair
  112. private_key.nil? ? OpenSSL::PKey::RSA.new(public_key) : OpenSSL::PKey::RSA.new(private_key)
  113. end
  114. def subscription(webhook_url)
  115. OStatus2::Subscription.new(remote_url, secret: secret, lease_seconds: 86_400 * 30, webhook: webhook_url, hub: hub_url)
  116. end
  117. def save_with_optional_avatar!
  118. save!
  119. rescue ActiveRecord::RecordInvalid
  120. self.avatar = nil
  121. self.header = nil
  122. self[:avatar_remote_url] = ''
  123. self[:header_remote_url] = ''
  124. save!
  125. end
  126. def avatar_original_url
  127. avatar.url(:original)
  128. end
  129. def avatar_static_url
  130. avatar_content_type == 'image/gif' ? avatar.url(:static) : avatar_original_url
  131. end
  132. def header_original_url
  133. header.url(:original)
  134. end
  135. def header_static_url
  136. header_content_type == 'image/gif' ? header.url(:static) : header_original_url
  137. end
  138. def avatar_remote_url=(url)
  139. parsed_url = URI.parse(url)
  140. return if !%w(http https).include?(parsed_url.scheme) || parsed_url.host.empty? || self[:avatar_remote_url] == url
  141. self.avatar = parsed_url
  142. self[:avatar_remote_url] = url
  143. rescue OpenURI::HTTPError => e
  144. Rails.logger.debug "Error fetching remote avatar: #{e}"
  145. end
  146. def header_remote_url=(url)
  147. parsed_url = URI.parse(url)
  148. return if !%w(http https).include?(parsed_url.scheme) || parsed_url.host.empty? || self[:header_remote_url] == url
  149. self.header = parsed_url
  150. self[:header_remote_url] = url
  151. rescue OpenURI::HTTPError => e
  152. Rails.logger.debug "Error fetching remote header: #{e}"
  153. end
  154. def object_type
  155. :person
  156. end
  157. def to_param
  158. username
  159. end
  160. class << self
  161. def find_local!(username)
  162. find_remote!(username, nil)
  163. end
  164. def find_remote!(username, domain)
  165. return if username.blank?
  166. where('lower(accounts.username) = ?', username.downcase).where(domain.nil? ? { domain: nil } : 'lower(accounts.domain) = ?', domain&.downcase).take!
  167. end
  168. def find_local(username)
  169. find_local!(username)
  170. rescue ActiveRecord::RecordNotFound
  171. nil
  172. end
  173. def find_remote(username, domain)
  174. find_remote!(username, domain)
  175. rescue ActiveRecord::RecordNotFound
  176. nil
  177. end
  178. def triadic_closures(account, limit = 5)
  179. sql = <<-SQL.squish
  180. WITH first_degree AS (
  181. SELECT target_account_id
  182. FROM follows
  183. WHERE account_id = :account_id
  184. )
  185. SELECT accounts.*
  186. FROM follows
  187. INNER JOIN accounts ON follows.target_account_id = accounts.id
  188. WHERE account_id IN (SELECT * FROM first_degree) AND target_account_id NOT IN (SELECT * FROM first_degree) AND target_account_id <> :account_id
  189. GROUP BY target_account_id, accounts.id
  190. ORDER BY count(account_id) DESC
  191. LIMIT :limit
  192. SQL
  193. find_by_sql(
  194. [sql, { account_id: account.id, limit: limit }]
  195. )
  196. end
  197. def search_for(terms, limit = 10)
  198. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  199. textsearch = '(setweight(to_tsvector(\'simple\', accounts.display_name), \'A\') || setweight(to_tsvector(\'simple\', accounts.username), \'B\') || setweight(to_tsvector(\'simple\', coalesce(accounts.domain, \'\')), \'C\'))'
  200. query = 'to_tsquery(\'simple\', \'\'\' \' || ' + terms + ' || \' \'\'\' || \':*\')'
  201. sql = <<-SQL.squish
  202. SELECT
  203. accounts.*,
  204. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  205. FROM accounts
  206. WHERE #{query} @@ #{textsearch}
  207. ORDER BY rank DESC
  208. LIMIT ?
  209. SQL
  210. Account.find_by_sql([sql, limit])
  211. end
  212. def advanced_search_for(terms, account, limit = 10)
  213. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  214. textsearch = '(setweight(to_tsvector(\'simple\', accounts.display_name), \'A\') || setweight(to_tsvector(\'simple\', accounts.username), \'B\') || setweight(to_tsvector(\'simple\', coalesce(accounts.domain, \'\')), \'C\'))'
  215. query = 'to_tsquery(\'simple\', \'\'\' \' || ' + terms + ' || \' \'\'\' || \':*\')'
  216. sql = <<-SQL.squish
  217. SELECT
  218. accounts.*,
  219. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  220. FROM accounts
  221. 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 = ?)
  222. WHERE #{query} @@ #{textsearch}
  223. GROUP BY accounts.id
  224. ORDER BY rank DESC
  225. LIMIT ?
  226. SQL
  227. Account.find_by_sql([sql, account.id, account.id, limit])
  228. end
  229. def following_map(target_account_ids, account_id)
  230. follow_mapping(Follow.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  231. end
  232. def followed_by_map(target_account_ids, account_id)
  233. follow_mapping(Follow.where(account_id: target_account_ids, target_account_id: account_id), :account_id)
  234. end
  235. def blocking_map(target_account_ids, account_id)
  236. follow_mapping(Block.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  237. end
  238. def muting_map(target_account_ids, account_id)
  239. follow_mapping(Mute.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  240. end
  241. def requested_map(target_account_ids, account_id)
  242. follow_mapping(FollowRequest.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  243. end
  244. private
  245. def follow_mapping(query, field)
  246. query.pluck(field).inject({}) { |mapping, id| mapping[id] = true; mapping }
  247. end
  248. def avatar_styles(file)
  249. styles = { original: '120x120#' }
  250. styles[:static] = { format: 'png' } if file.content_type == 'image/gif'
  251. styles
  252. end
  253. def header_styles(file)
  254. styles = { original: '700x335#' }
  255. styles[:static] = { format: 'png' } if file.content_type == 'image/gif'
  256. styles
  257. end
  258. end
  259. before_create do
  260. if local?
  261. keypair = OpenSSL::PKey::RSA.new(Rails.env.test? ? 1024 : 2048)
  262. self.private_key = keypair.to_pem
  263. self.public_key = keypair.public_key.to_pem
  264. end
  265. end
  266. private
  267. def set_file_extensions
  268. unless avatar.blank?
  269. extension = Paperclip::Interpolations.content_type_extension(avatar, :original)
  270. basename = Paperclip::Interpolations.basename(avatar, :original)
  271. avatar.instance_write :file_name, [basename, extension].delete_if(&:empty?).join('.')
  272. end
  273. unless header.blank?
  274. extension = Paperclip::Interpolations.content_type_extension(header, :original)
  275. basename = Paperclip::Interpolations.basename(header, :original)
  276. header.instance_write :file_name, [basename, extension].delete_if(&:empty?).join('.')
  277. end
  278. end
  279. end