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

356 lines
12 KiB

8 years ago
8 years ago
8 years ago
8 years ago
  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. MENTION_RE = /(?:^|[^\/[:word:]])@([a-z0-9_]+(?:@[a-z0-9\.\-]+[a-z0-9]+)?)/i
  42. include AccountAvatar
  43. include AccountHeader
  44. include Attachmentable
  45. include Targetable
  46. # Local users
  47. has_one :user, inverse_of: :account
  48. validates :username, presence: true
  49. validates :username, uniqueness: { scope: :domain, case_sensitive: true }, unless: 'local?'
  50. # Local user validations
  51. with_options if: 'local?' do
  52. validates :username, format: { with: /\A[a-z0-9_]+\z/i }, uniqueness: { scope: :domain, case_sensitive: false }, length: { maximum: 30 }
  53. validates :display_name, length: { maximum: 30 }
  54. validates :note, length: { maximum: 160 }
  55. end
  56. # Timelines
  57. has_many :stream_entries, inverse_of: :account, dependent: :destroy
  58. has_many :statuses, inverse_of: :account, dependent: :destroy
  59. has_many :favourites, inverse_of: :account, dependent: :destroy
  60. has_many :mentions, inverse_of: :account, dependent: :destroy
  61. has_many :notifications, inverse_of: :account, dependent: :destroy
  62. # Follow relations
  63. has_many :follow_requests, dependent: :destroy
  64. has_many :active_relationships, class_name: 'Follow', foreign_key: 'account_id', dependent: :destroy
  65. has_many :passive_relationships, class_name: 'Follow', foreign_key: 'target_account_id', dependent: :destroy
  66. has_many :following, -> { order('follows.id desc') }, through: :active_relationships, source: :target_account
  67. has_many :followers, -> { order('follows.id desc') }, through: :passive_relationships, source: :account
  68. # Block relationships
  69. has_many :block_relationships, class_name: 'Block', foreign_key: 'account_id', dependent: :destroy
  70. has_many :blocking, -> { order('blocks.id desc') }, through: :block_relationships, source: :target_account
  71. has_many :blocked_by_relationships, class_name: 'Block', foreign_key: :target_account_id, dependent: :destroy
  72. has_many :blocked_by, -> { order('blocks.id desc') }, through: :blocked_by_relationships, source: :account
  73. # Mute relationships
  74. has_many :mute_relationships, class_name: 'Mute', foreign_key: 'account_id', dependent: :destroy
  75. has_many :muting, -> { order('mutes.id desc') }, through: :mute_relationships, source: :target_account
  76. # Media
  77. has_many :media_attachments, dependent: :destroy
  78. # PuSH subscriptions
  79. has_many :subscriptions, dependent: :destroy
  80. # Report relationships
  81. has_many :reports
  82. has_many :targeted_reports, class_name: 'Report', foreign_key: :target_account_id
  83. scope :remote, -> { where.not(domain: nil) }
  84. scope :local, -> { where(domain: nil) }
  85. scope :without_followers, -> { where(followers_count: 0) }
  86. scope :with_followers, -> { where('followers_count > 0') }
  87. scope :expiring, ->(time) { where(subscription_expires_at: nil).or(where('subscription_expires_at < ?', time)).remote.with_followers }
  88. scope :partitioned, -> { order('row_number() over (partition by domain)') }
  89. scope :silenced, -> { where(silenced: true) }
  90. scope :suspended, -> { where(suspended: true) }
  91. scope :recent, -> { reorder(id: :desc) }
  92. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  93. scope :by_domain_accounts, -> { group(:domain).select(:domain, 'COUNT(*) AS accounts_count').order('accounts_count desc') }
  94. delegate :email,
  95. :current_sign_in_ip,
  96. :current_sign_in_at,
  97. :confirmed?,
  98. :locale,
  99. to: :user,
  100. prefix: true,
  101. allow_nil: true
  102. delegate :allowed_languages, to: :user, prefix: false, allow_nil: true
  103. def follow!(other_account)
  104. active_relationships.find_or_create_by!(target_account: other_account)
  105. end
  106. def block!(other_account)
  107. block_relationships.find_or_create_by!(target_account: other_account)
  108. end
  109. def mute!(other_account)
  110. mute_relationships.find_or_create_by!(target_account: other_account)
  111. end
  112. def unfollow!(other_account)
  113. follow = active_relationships.find_by(target_account: other_account)
  114. follow&.destroy
  115. end
  116. def unblock!(other_account)
  117. block = block_relationships.find_by(target_account: other_account)
  118. block&.destroy
  119. end
  120. def unmute!(other_account)
  121. mute = mute_relationships.find_by(target_account: other_account)
  122. mute&.destroy
  123. end
  124. def following?(other_account)
  125. following.include?(other_account)
  126. end
  127. def blocking?(other_account)
  128. blocking.include?(other_account)
  129. end
  130. def muting?(other_account)
  131. muting.include?(other_account)
  132. end
  133. def requested?(other_account)
  134. follow_requests.where(target_account: other_account).exists?
  135. end
  136. def local?
  137. domain.nil?
  138. end
  139. def acct
  140. local? ? username : "#{username}@#{domain}"
  141. end
  142. def local_username_and_domain
  143. "#{username}@#{Rails.configuration.x.local_domain}"
  144. end
  145. def to_webfinger_s
  146. "acct:#{local_username_and_domain}"
  147. end
  148. def subscribed?
  149. subscription_expires_at.present?
  150. end
  151. def followers_domains
  152. followers.reorder(nil).pluck('distinct accounts.domain')
  153. end
  154. def favourited?(status)
  155. status.proper.favourites.where(account: self).exists?
  156. end
  157. def reblogged?(status)
  158. status.proper.reblogs.where(account: self).exists?
  159. end
  160. def keypair
  161. OpenSSL::PKey::RSA.new(private_key || public_key)
  162. end
  163. def subscription(webhook_url)
  164. OStatus2::Subscription.new(remote_url, secret: secret, lease_seconds: 86_400 * 30, webhook: webhook_url, hub: hub_url)
  165. end
  166. def save_with_optional_media!
  167. save!
  168. rescue ActiveRecord::RecordInvalid
  169. self.avatar = nil
  170. self.header = nil
  171. self[:avatar_remote_url] = ''
  172. self[:header_remote_url] = ''
  173. save!
  174. end
  175. def object_type
  176. :person
  177. end
  178. def to_param
  179. username
  180. end
  181. def excluded_from_timeline_account_ids
  182. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  183. end
  184. class << self
  185. def find_local!(username)
  186. find_remote!(username, nil)
  187. end
  188. def find_remote!(username, domain)
  189. return if username.blank?
  190. where('lower(accounts.username) = ?', username.downcase).where(domain.nil? ? { domain: nil } : 'lower(accounts.domain) = ?', domain&.downcase).take!
  191. end
  192. def find_local(username)
  193. find_local!(username)
  194. rescue ActiveRecord::RecordNotFound
  195. nil
  196. end
  197. def find_remote(username, domain)
  198. find_remote!(username, domain)
  199. rescue ActiveRecord::RecordNotFound
  200. nil
  201. end
  202. def triadic_closures(account, limit = 5)
  203. sql = <<-SQL.squish
  204. WITH first_degree AS (
  205. SELECT target_account_id
  206. FROM follows
  207. WHERE account_id = :account_id
  208. )
  209. SELECT accounts.*
  210. FROM follows
  211. INNER JOIN accounts ON follows.target_account_id = accounts.id
  212. WHERE account_id IN (SELECT * FROM first_degree) AND target_account_id NOT IN (SELECT * FROM first_degree) AND target_account_id <> :account_id
  213. GROUP BY target_account_id, accounts.id
  214. ORDER BY count(account_id) DESC
  215. LIMIT :limit
  216. SQL
  217. find_by_sql(
  218. [sql, { account_id: account.id, limit: limit }]
  219. )
  220. end
  221. def search_for(terms, limit = 10)
  222. textsearch, query = generate_query_for_search(terms)
  223. sql = <<-SQL.squish
  224. SELECT
  225. accounts.*,
  226. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  227. FROM accounts
  228. WHERE #{query} @@ #{textsearch}
  229. ORDER BY rank DESC
  230. LIMIT ?
  231. SQL
  232. find_by_sql([sql, limit])
  233. end
  234. def advanced_search_for(terms, account, limit = 10)
  235. textsearch, query = generate_query_for_search(terms)
  236. sql = <<-SQL.squish
  237. SELECT
  238. accounts.*,
  239. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  240. FROM accounts
  241. 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 = ?)
  242. WHERE #{query} @@ #{textsearch}
  243. GROUP BY accounts.id
  244. ORDER BY rank DESC
  245. LIMIT ?
  246. SQL
  247. find_by_sql([sql, account.id, account.id, limit])
  248. end
  249. def following_map(target_account_ids, account_id)
  250. follow_mapping(Follow.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  251. end
  252. def followed_by_map(target_account_ids, account_id)
  253. follow_mapping(Follow.where(account_id: target_account_ids, target_account_id: account_id), :account_id)
  254. end
  255. def blocking_map(target_account_ids, account_id)
  256. follow_mapping(Block.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  257. end
  258. def muting_map(target_account_ids, account_id)
  259. follow_mapping(Mute.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  260. end
  261. def requested_map(target_account_ids, account_id)
  262. follow_mapping(FollowRequest.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  263. end
  264. private
  265. def generate_query_for_search(terms)
  266. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  267. textsearch = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  268. query = "to_tsquery('simple', ''' ' || #{terms} || ' ''' || ':*')"
  269. [textsearch, query]
  270. end
  271. def follow_mapping(query, field)
  272. query.pluck(field).each_with_object({}) { |id, mapping| mapping[id] = true }
  273. end
  274. end
  275. before_create :generate_keys
  276. before_validation :normalize_domain
  277. private
  278. def generate_keys
  279. return unless local?
  280. keypair = OpenSSL::PKey::RSA.new(Rails.env.test? ? 1024 : 2048)
  281. self.private_key = keypair.to_pem
  282. self.public_key = keypair.public_key.to_pem
  283. end
  284. def normalize_domain
  285. return if local?
  286. self.domain = TagManager.instance.normalize_domain(domain)
  287. end
  288. end