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.

278 lines
8.8 KiB

Account domain blocks (#2381) * Add <ostatus:conversation /> tag to Atom input/output Only uses ref attribute (not href) because href would be the alternate link that's always included also. Creates new conversation for every non-reply status. Carries over conversation for every reply. Keeps remote URIs verbatim, generates local URIs on the fly like the rest of them. * Conversation muting - prevents notifications that reference a conversation (including replies, favourites, reblogs) from being created. API endpoints /api/v1/statuses/:id/mute and /api/v1/statuses/:id/unmute Currently no way to tell when a status/conversation is muted, so the web UI only has a "disable notifications" button, doesn't work as a toggle * Display "Dismiss notifications" on all statuses in notifications column, not just own * Add "muted" as a boolean attribute on statuses JSON For now always false on contained reblogs, since it's only relevant for statuses returned from the notifications endpoint, which are not nested Remove "Disable notifications" from detailed status view, since it's only relevant in the notifications column * Up max class length * Remove pending test for conversation mute * Add tests, clean up * Rename to "mute conversation" and "unmute conversation" * Raise validation error when trying to mute/unmute status without conversation * Adding account domain blocks that filter notifications and public timelines * Add tests for domain blocks in notifications, public timelines Filter reblogs of blocked domains from home * Add API for listing and creating account domain blocks * API for creating/deleting domain blocks, tests for Status#ancestors and Status#descendants, filter domain blocks from them * Filter domains in streaming API * Update account_domain_block_spec.rb
7 years ago
8 years ago
8 years ago
8 years ago
Account domain blocks (#2381) * Add <ostatus:conversation /> tag to Atom input/output Only uses ref attribute (not href) because href would be the alternate link that's always included also. Creates new conversation for every non-reply status. Carries over conversation for every reply. Keeps remote URIs verbatim, generates local URIs on the fly like the rest of them. * Conversation muting - prevents notifications that reference a conversation (including replies, favourites, reblogs) from being created. API endpoints /api/v1/statuses/:id/mute and /api/v1/statuses/:id/unmute Currently no way to tell when a status/conversation is muted, so the web UI only has a "disable notifications" button, doesn't work as a toggle * Display "Dismiss notifications" on all statuses in notifications column, not just own * Add "muted" as a boolean attribute on statuses JSON For now always false on contained reblogs, since it's only relevant for statuses returned from the notifications endpoint, which are not nested Remove "Disable notifications" from detailed status view, since it's only relevant in the notifications column * Up max class length * Remove pending test for conversation mute * Add tests, clean up * Rename to "mute conversation" and "unmute conversation" * Raise validation error when trying to mute/unmute status without conversation * Adding account domain blocks that filter notifications and public timelines * Add tests for domain blocks in notifications, public timelines Filter reblogs of blocked domains from home * Add API for listing and creating account domain blocks * API for creating/deleting domain blocks, tests for Status#ancestors and Status#descendants, filter domain blocks from them * Filter domains in streaming API * Update account_domain_block_spec.rb
7 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 AccountInteractions
  45. include Attachmentable
  46. include Remotable
  47. include Targetable
  48. # Local users
  49. has_one :user, inverse_of: :account
  50. validates :username, presence: true
  51. validates :username, uniqueness: { scope: :domain, case_sensitive: true }, unless: 'local?'
  52. # Local user validations
  53. with_options if: 'local?' do
  54. validates :username, format: { with: /\A[a-z0-9_]+\z/i }, uniqueness: { scope: :domain, case_sensitive: false }, length: { maximum: 30 }
  55. validates :display_name, length: { maximum: 30 }
  56. validates :note, length: { maximum: 160 }
  57. end
  58. # Timelines
  59. has_many :stream_entries, inverse_of: :account, dependent: :destroy
  60. has_many :statuses, inverse_of: :account, dependent: :destroy
  61. has_many :favourites, inverse_of: :account, dependent: :destroy
  62. has_many :mentions, inverse_of: :account, dependent: :destroy
  63. has_many :notifications, inverse_of: :account, dependent: :destroy
  64. # Media
  65. has_many :media_attachments, dependent: :destroy
  66. # PuSH subscriptions
  67. has_many :subscriptions, dependent: :destroy
  68. # Report relationships
  69. has_many :reports
  70. has_many :targeted_reports, class_name: 'Report', foreign_key: :target_account_id
  71. scope :remote, -> { where.not(domain: nil) }
  72. scope :local, -> { where(domain: nil) }
  73. scope :without_followers, -> { where(followers_count: 0) }
  74. scope :with_followers, -> { where('followers_count > 0') }
  75. scope :expiring, ->(time) { where(subscription_expires_at: nil).or(where('subscription_expires_at < ?', time)).remote.with_followers }
  76. scope :partitioned, -> { order('row_number() over (partition by domain)') }
  77. scope :silenced, -> { where(silenced: true) }
  78. scope :suspended, -> { where(suspended: true) }
  79. scope :recent, -> { reorder(id: :desc) }
  80. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  81. scope :by_domain_accounts, -> { group(:domain).select(:domain, 'COUNT(*) AS accounts_count').order('accounts_count desc') }
  82. delegate :email,
  83. :current_sign_in_ip,
  84. :current_sign_in_at,
  85. :confirmed?,
  86. :locale,
  87. to: :user,
  88. prefix: true,
  89. allow_nil: true
  90. delegate :allowed_languages, to: :user, prefix: false, allow_nil: true
  91. def local?
  92. domain.nil?
  93. end
  94. def acct
  95. local? ? username : "#{username}@#{domain}"
  96. end
  97. def local_username_and_domain
  98. "#{username}@#{Rails.configuration.x.local_domain}"
  99. end
  100. def to_webfinger_s
  101. "acct:#{local_username_and_domain}"
  102. end
  103. def subscribed?
  104. subscription_expires_at.present?
  105. end
  106. def followers_domains
  107. followers.reorder(nil).pluck('distinct accounts.domain')
  108. end
  109. def keypair
  110. OpenSSL::PKey::RSA.new(private_key || public_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_media!
  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 object_type
  125. :person
  126. end
  127. def to_param
  128. username
  129. end
  130. def excluded_from_timeline_account_ids
  131. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  132. end
  133. def excluded_from_timeline_domains
  134. Rails.cache.fetch("exclude_domains_for:#{id}") { domain_blocks.pluck(:domain) }
  135. end
  136. class << self
  137. def find_local!(username)
  138. find_remote!(username, nil)
  139. end
  140. def find_remote!(username, domain)
  141. return if username.blank?
  142. where('lower(accounts.username) = ?', username.downcase).where(domain.nil? ? { domain: nil } : 'lower(accounts.domain) = ?', domain&.downcase).take!
  143. end
  144. def find_local(username)
  145. find_local!(username)
  146. rescue ActiveRecord::RecordNotFound
  147. nil
  148. end
  149. def find_remote(username, domain)
  150. find_remote!(username, domain)
  151. rescue ActiveRecord::RecordNotFound
  152. nil
  153. end
  154. def triadic_closures(account, limit: 5, offset: 0)
  155. sql = <<-SQL.squish
  156. WITH first_degree AS (
  157. SELECT target_account_id
  158. FROM follows
  159. WHERE account_id = :account_id
  160. )
  161. SELECT accounts.*
  162. FROM follows
  163. INNER JOIN accounts ON follows.target_account_id = accounts.id
  164. WHERE
  165. account_id IN (SELECT * FROM first_degree)
  166. AND target_account_id NOT IN (SELECT * FROM first_degree)
  167. AND target_account_id NOT IN (:excluded_account_ids)
  168. GROUP BY target_account_id, accounts.id
  169. ORDER BY count(account_id) DESC
  170. OFFSET :offset
  171. LIMIT :limit
  172. SQL
  173. excluded_account_ids = account.excluded_from_timeline_account_ids + [account.id]
  174. find_by_sql(
  175. [sql, { account_id: account.id, excluded_account_ids: excluded_account_ids, limit: limit, offset: offset }]
  176. )
  177. end
  178. def search_for(terms, limit = 10)
  179. textsearch, query = generate_query_for_search(terms)
  180. sql = <<-SQL.squish
  181. SELECT
  182. accounts.*,
  183. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  184. FROM accounts
  185. WHERE #{query} @@ #{textsearch}
  186. ORDER BY rank DESC
  187. LIMIT ?
  188. SQL
  189. find_by_sql([sql, limit])
  190. end
  191. def advanced_search_for(terms, account, limit = 10)
  192. textsearch, query = generate_query_for_search(terms)
  193. sql = <<-SQL.squish
  194. SELECT
  195. accounts.*,
  196. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  197. FROM accounts
  198. 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 = ?)
  199. WHERE #{query} @@ #{textsearch}
  200. GROUP BY accounts.id
  201. ORDER BY rank DESC
  202. LIMIT ?
  203. SQL
  204. find_by_sql([sql, account.id, account.id, limit])
  205. end
  206. private
  207. def generate_query_for_search(terms)
  208. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  209. textsearch = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  210. query = "to_tsquery('simple', ''' ' || #{terms} || ' ''' || ':*')"
  211. [textsearch, query]
  212. end
  213. def follow_mapping(query, field)
  214. query.pluck(field).each_with_object({}) { |id, mapping| mapping[id] = true }
  215. end
  216. end
  217. before_create :generate_keys
  218. before_validation :normalize_domain
  219. private
  220. def generate_keys
  221. return unless local?
  222. keypair = OpenSSL::PKey::RSA.new(Rails.env.test? ? 1024 : 2048)
  223. self.private_key = keypair.to_pem
  224. self.public_key = keypair.public_key.to_pem
  225. end
  226. def normalize_domain
  227. return if local?
  228. self.domain = TagManager.instance.normalize_domain(domain)
  229. end
  230. end