闭社主体 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.

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