The code powering m.abunchtell.com https://m.abunchtell.com
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

account.rb 12 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 yıl önce
Fix Account model deprecation warnings (#3689) ``` DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:60) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:60) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:60) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:61) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:62) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:63) ``` Here's PR describing changes to Dirty API https://github.com/rails/rails/pull/25337
7 yıl önce
Fix Account model deprecation warnings (#3689) ``` DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:60) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:60) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:60) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:61) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:62) DEPRECATION WARNING: The behavior of `attribute_changed?` inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method after `save` returned (e.g. the opposite of what it returns now). To maintain the current behavior, use `saved_change_to_attribute?` instead. (called from block in <class:Account> at /Users/rene/Workspace/personal/ruby/mastodon/app/models/account.rb:63) ``` Here's PR describing changes to Dirty API https://github.com/rails/rails/pull/25337
7 yıl önce
8 yıl önce
8 yıl önce
8 yıl önce
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 yıl önce
8 yıl önce
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. # inbox_url :string default(""), not null
  40. # outbox_url :string default(""), not null
  41. # shared_inbox_url :string default(""), not null
  42. # followers_url :string default(""), not null
  43. # protocol :integer default("ostatus"), not null
  44. # memorial :boolean default(FALSE), not null
  45. # moved_to_account_id :integer
  46. # featured_collection_url :string
  47. #
  48. class Account < ApplicationRecord
  49. MENTION_RE = /(?<=^|[^\/[:word:]])@(([a-z0-9_]+)(?:@[a-z0-9\.\-]+[a-z0-9]+)?)/i
  50. include AccountAvatar
  51. include AccountFinderConcern
  52. include AccountHeader
  53. include AccountInteractions
  54. include Attachmentable
  55. include Remotable
  56. include Paginable
  57. enum protocol: [:ostatus, :activitypub]
  58. # Local users
  59. has_one :user, inverse_of: :account
  60. validates :username, presence: true
  61. # Remote user validations
  62. validates :username, uniqueness: { scope: :domain, case_sensitive: true }, if: -> { !local? && will_save_change_to_username? }
  63. # Local user validations
  64. validates :username, format: { with: /\A[a-z0-9_]+\z/i }, uniqueness: { scope: :domain, case_sensitive: false }, length: { maximum: 30 }, if: -> { local? && will_save_change_to_username? }
  65. validates_with UnreservedUsernameValidator, if: -> { local? && will_save_change_to_username? }
  66. validates :display_name, length: { maximum: 30 }, if: -> { local? && will_save_change_to_display_name? }
  67. validates :note, length: { maximum: 160 }, if: -> { local? && will_save_change_to_note? }
  68. # Timelines
  69. has_many :stream_entries, inverse_of: :account, dependent: :destroy
  70. has_many :statuses, inverse_of: :account, dependent: :destroy
  71. has_many :favourites, inverse_of: :account, dependent: :destroy
  72. has_many :mentions, inverse_of: :account, dependent: :destroy
  73. has_many :notifications, inverse_of: :account, dependent: :destroy
  74. # Pinned statuses
  75. has_many :status_pins, inverse_of: :account, dependent: :destroy
  76. has_many :pinned_statuses, -> { reorder('status_pins.created_at DESC') }, through: :status_pins, class_name: 'Status', source: :status
  77. # Media
  78. has_many :media_attachments, dependent: :destroy
  79. # PuSH subscriptions
  80. has_many :subscriptions, dependent: :destroy
  81. # Report relationships
  82. has_many :reports
  83. has_many :targeted_reports, class_name: 'Report', foreign_key: :target_account_id
  84. # Moderation notes
  85. has_many :account_moderation_notes, dependent: :destroy
  86. has_many :targeted_moderation_notes, class_name: 'AccountModerationNote', foreign_key: :target_account_id, dependent: :destroy
  87. # Lists
  88. has_many :list_accounts, inverse_of: :account, dependent: :destroy
  89. has_many :lists, through: :list_accounts
  90. # Account migrations
  91. belongs_to :moved_to_account, class_name: 'Account', optional: true
  92. scope :remote, -> { where.not(domain: nil) }
  93. scope :local, -> { where(domain: nil) }
  94. scope :without_followers, -> { where(followers_count: 0) }
  95. scope :with_followers, -> { where('followers_count > 0') }
  96. scope :expiring, ->(time) { remote.where.not(subscription_expires_at: nil).where('subscription_expires_at < ?', time) }
  97. scope :partitioned, -> { order('row_number() over (partition by domain)') }
  98. scope :silenced, -> { where(silenced: true) }
  99. scope :suspended, -> { where(suspended: true) }
  100. scope :recent, -> { reorder(id: :desc) }
  101. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  102. scope :by_domain_accounts, -> { group(:domain).select(:domain, 'COUNT(*) AS accounts_count').order('accounts_count desc') }
  103. scope :matches_username, ->(value) { where(arel_table[:username].matches("#{value}%")) }
  104. scope :matches_display_name, ->(value) { where(arel_table[:display_name].matches("#{value}%")) }
  105. scope :matches_domain, ->(value) { where(arel_table[:domain].matches("%#{value}%")) }
  106. delegate :email,
  107. :current_sign_in_ip,
  108. :current_sign_in_at,
  109. :confirmed?,
  110. :admin?,
  111. :moderator?,
  112. :staff?,
  113. :locale,
  114. to: :user,
  115. prefix: true,
  116. allow_nil: true
  117. delegate :filtered_languages, to: :user, prefix: false, allow_nil: true
  118. def local?
  119. domain.nil?
  120. end
  121. def moved?
  122. moved_to_account_id.present?
  123. end
  124. def acct
  125. local? ? username : "#{username}@#{domain}"
  126. end
  127. def local_username_and_domain
  128. "#{username}@#{Rails.configuration.x.local_domain}"
  129. end
  130. def to_webfinger_s
  131. "acct:#{local_username_and_domain}"
  132. end
  133. def subscribed?
  134. subscription_expires_at.present?
  135. end
  136. def possibly_stale?
  137. last_webfingered_at.nil? || last_webfingered_at <= 1.day.ago
  138. end
  139. def refresh!
  140. return if local?
  141. ResolveAccountService.new.call(acct)
  142. end
  143. def unsuspend!
  144. transaction do
  145. user&.enable! if local?
  146. update!(suspended: false)
  147. end
  148. end
  149. def memorialize!
  150. transaction do
  151. user&.disable! if local?
  152. update!(memorial: true)
  153. end
  154. end
  155. def keypair
  156. @keypair ||= OpenSSL::PKey::RSA.new(private_key || public_key)
  157. end
  158. def magic_key
  159. modulus, exponent = [keypair.public_key.n, keypair.public_key.e].map do |component|
  160. result = []
  161. until component.zero?
  162. result << [component % 256].pack('C')
  163. component >>= 8
  164. end
  165. result.reverse.join
  166. end
  167. (['RSA'] + [modulus, exponent].map { |n| Base64.urlsafe_encode64(n) }).join('.')
  168. end
  169. def subscription(webhook_url)
  170. @subscription ||= OStatus2::Subscription.new(remote_url, secret: secret, webhook: webhook_url, hub: hub_url)
  171. end
  172. def save_with_optional_media!
  173. save!
  174. rescue ActiveRecord::RecordInvalid
  175. self.avatar = nil
  176. self.header = nil
  177. self[:avatar_remote_url] = ''
  178. self[:header_remote_url] = ''
  179. save!
  180. end
  181. def object_type
  182. :person
  183. end
  184. def to_param
  185. username
  186. end
  187. def excluded_from_timeline_account_ids
  188. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  189. end
  190. def excluded_from_timeline_domains
  191. Rails.cache.fetch("exclude_domains_for:#{id}") { domain_blocks.pluck(:domain) }
  192. end
  193. def preferred_inbox_url
  194. shared_inbox_url.presence || inbox_url
  195. end
  196. class << self
  197. def readonly_attributes
  198. super - %w(statuses_count following_count followers_count)
  199. end
  200. def domains
  201. reorder(nil).pluck('distinct accounts.domain')
  202. end
  203. def inboxes
  204. urls = reorder(nil).where(protocol: :activitypub).pluck("distinct coalesce(nullif(accounts.shared_inbox_url, ''), accounts.inbox_url)")
  205. DeliveryFailureTracker.filter(urls)
  206. end
  207. def triadic_closures(account, limit: 5, offset: 0)
  208. sql = <<-SQL.squish
  209. WITH first_degree AS (
  210. SELECT target_account_id
  211. FROM follows
  212. WHERE account_id = :account_id
  213. )
  214. SELECT accounts.*
  215. FROM follows
  216. INNER JOIN accounts ON follows.target_account_id = accounts.id
  217. WHERE
  218. account_id IN (SELECT * FROM first_degree)
  219. AND target_account_id NOT IN (SELECT * FROM first_degree)
  220. AND target_account_id NOT IN (:excluded_account_ids)
  221. AND accounts.suspended = false
  222. GROUP BY target_account_id, accounts.id
  223. ORDER BY count(account_id) DESC
  224. OFFSET :offset
  225. LIMIT :limit
  226. SQL
  227. excluded_account_ids = account.excluded_from_timeline_account_ids + [account.id]
  228. find_by_sql(
  229. [sql, { account_id: account.id, excluded_account_ids: excluded_account_ids, limit: limit, offset: offset }]
  230. )
  231. end
  232. def search_for(terms, limit = 10)
  233. textsearch, query = generate_query_for_search(terms)
  234. sql = <<-SQL.squish
  235. SELECT
  236. accounts.*,
  237. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  238. FROM accounts
  239. WHERE #{query} @@ #{textsearch}
  240. AND accounts.suspended = false
  241. AND accounts.moved_to_account_id IS NULL
  242. ORDER BY rank DESC
  243. LIMIT ?
  244. SQL
  245. find_by_sql([sql, limit])
  246. end
  247. def advanced_search_for(terms, account, limit = 10, following = false)
  248. textsearch, query = generate_query_for_search(terms)
  249. if following
  250. sql = <<-SQL.squish
  251. WITH first_degree AS (
  252. SELECT target_account_id
  253. FROM follows
  254. WHERE account_id = ?
  255. )
  256. SELECT
  257. accounts.*,
  258. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  259. FROM accounts
  260. 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 = ?)
  261. WHERE accounts.id IN (SELECT * FROM first_degree)
  262. AND #{query} @@ #{textsearch}
  263. AND accounts.suspended = false
  264. AND accounts.moved_to_account_id IS NULL
  265. GROUP BY accounts.id
  266. ORDER BY rank DESC
  267. LIMIT ?
  268. SQL
  269. find_by_sql([sql, account.id, account.id, account.id, limit])
  270. else
  271. sql = <<-SQL.squish
  272. SELECT
  273. accounts.*,
  274. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  275. FROM accounts
  276. 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 = ?)
  277. WHERE #{query} @@ #{textsearch}
  278. AND accounts.suspended = false
  279. AND accounts.moved_to_account_id IS NULL
  280. GROUP BY accounts.id
  281. ORDER BY rank DESC
  282. LIMIT ?
  283. SQL
  284. find_by_sql([sql, account.id, account.id, limit])
  285. end
  286. end
  287. private
  288. def generate_query_for_search(terms)
  289. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  290. textsearch = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  291. query = "to_tsquery('simple', ''' ' || #{terms} || ' ''' || ':*')"
  292. [textsearch, query]
  293. end
  294. end
  295. before_create :generate_keys
  296. before_validation :normalize_domain
  297. before_validation :prepare_contents, if: :local?
  298. private
  299. def prepare_contents
  300. display_name&.strip!
  301. note&.strip!
  302. end
  303. def generate_keys
  304. return unless local?
  305. keypair = OpenSSL::PKey::RSA.new(Rails.env.test? ? 512 : 2048)
  306. self.private_key = keypair.to_pem
  307. self.public_key = keypair.public_key.to_pem
  308. end
  309. def normalize_domain
  310. return if local?
  311. self.domain = TagManager.instance.normalize_domain(domain)
  312. end
  313. end