The code powering m.abunchtell.com https://m.abunchtell.com
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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
pirms 7 gadiem
pirms 8 gadiem
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
pirms 7 gadiem
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
pirms 7 gadiem
pirms 8 gadiem
pirms 7 gadiem
pirms 8 gadiem
pirms 8 gadiem
pirms 7 gadiem
pirms 8 gadiem
pirms 7 gadiem
pirms 8 gadiem
pirms 8 gadiem
pirms 8 gadiem
pirms 8 gadiem
pirms 7 gadiem
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
pirms 7 gadiem
pirms 8 gadiem
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: accounts
  5. #
  6. # id :bigint(8) 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 :bigint(8)
  46. # featured_collection_url :string
  47. # fields :jsonb
  48. # actor_type :string
  49. #
  50. class Account < ApplicationRecord
  51. USERNAME_RE = /[a-z0-9_]+([a-z0-9_\.]+[a-z0-9_]+)?/i
  52. MENTION_RE = /(?<=^|[^\/[:word:]])@((#{USERNAME_RE})(?:@[a-z0-9\.\-]+[a-z0-9]+)?)/i
  53. include AccountAvatar
  54. include AccountFinderConcern
  55. include AccountHeader
  56. include AccountInteractions
  57. include Attachmentable
  58. include Paginable
  59. enum protocol: [:ostatus, :activitypub]
  60. # Local users
  61. has_one :user, inverse_of: :account
  62. validates :username, presence: true
  63. # Remote user validations
  64. validates :username, uniqueness: { scope: :domain, case_sensitive: true }, if: -> { !local? && will_save_change_to_username? }
  65. # Local user validations
  66. validates :username, format: { with: /\A[a-z0-9_]+\z/i }, length: { maximum: 30 }, if: -> { local? && will_save_change_to_username? }
  67. validates_with UniqueUsernameValidator, if: -> { local? && will_save_change_to_username? }
  68. validates_with UnreservedUsernameValidator, if: -> { local? && will_save_change_to_username? }
  69. validates :display_name, length: { maximum: 30 }, if: -> { local? && will_save_change_to_display_name? }
  70. validates :note, length: { maximum: 160 }, if: -> { local? && will_save_change_to_note? }
  71. validates :fields, length: { maximum: 4 }, if: -> { local? && will_save_change_to_fields? }
  72. # Timelines
  73. has_many :stream_entries, inverse_of: :account, dependent: :destroy
  74. has_many :statuses, inverse_of: :account, dependent: :destroy
  75. has_many :favourites, inverse_of: :account, dependent: :destroy
  76. has_many :mentions, inverse_of: :account, dependent: :destroy
  77. has_many :notifications, inverse_of: :account, dependent: :destroy
  78. # Pinned statuses
  79. has_many :status_pins, inverse_of: :account, dependent: :destroy
  80. has_many :pinned_statuses, -> { reorder('status_pins.created_at DESC') }, through: :status_pins, class_name: 'Status', source: :status
  81. # Media
  82. has_many :media_attachments, dependent: :destroy
  83. # PuSH subscriptions
  84. has_many :subscriptions, dependent: :destroy
  85. # Report relationships
  86. has_many :reports
  87. has_many :targeted_reports, class_name: 'Report', foreign_key: :target_account_id
  88. has_many :report_notes, dependent: :destroy
  89. # Moderation notes
  90. has_many :account_moderation_notes, dependent: :destroy
  91. has_many :targeted_moderation_notes, class_name: 'AccountModerationNote', foreign_key: :target_account_id, dependent: :destroy
  92. # Lists
  93. has_many :list_accounts, inverse_of: :account, dependent: :destroy
  94. has_many :lists, through: :list_accounts
  95. # Account migrations
  96. belongs_to :moved_to_account, class_name: 'Account', optional: true
  97. scope :remote, -> { where.not(domain: nil) }
  98. scope :local, -> { where(domain: nil) }
  99. scope :without_followers, -> { where(followers_count: 0) }
  100. scope :with_followers, -> { where('followers_count > 0') }
  101. scope :expiring, ->(time) { remote.where.not(subscription_expires_at: nil).where('subscription_expires_at < ?', time) }
  102. scope :partitioned, -> { order(Arel.sql('row_number() over (partition by domain)')) }
  103. scope :silenced, -> { where(silenced: true) }
  104. scope :suspended, -> { where(suspended: true) }
  105. scope :without_suspended, -> { where(suspended: false) }
  106. scope :recent, -> { reorder(id: :desc) }
  107. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  108. scope :by_domain_accounts, -> { group(:domain).select(:domain, 'COUNT(*) AS accounts_count').order('accounts_count desc') }
  109. scope :matches_username, ->(value) { where(arel_table[:username].matches("#{value}%")) }
  110. scope :matches_display_name, ->(value) { where(arel_table[:display_name].matches("#{value}%")) }
  111. scope :matches_domain, ->(value) { where(arel_table[:domain].matches("%#{value}%")) }
  112. delegate :email,
  113. :unconfirmed_email,
  114. :current_sign_in_ip,
  115. :current_sign_in_at,
  116. :confirmed?,
  117. :admin?,
  118. :moderator?,
  119. :staff?,
  120. :locale,
  121. to: :user,
  122. prefix: true,
  123. allow_nil: true
  124. delegate :filtered_languages, to: :user, prefix: false, allow_nil: true
  125. def local?
  126. domain.nil?
  127. end
  128. def moved?
  129. moved_to_account_id.present?
  130. end
  131. def bot?
  132. %w(Application Service).include? actor_type
  133. end
  134. alias bot bot?
  135. def bot=(val)
  136. self.actor_type = ActiveModel::Type::Boolean.new.cast(val) ? 'Service' : 'Person'
  137. end
  138. def acct
  139. local? ? username : "#{username}@#{domain}"
  140. end
  141. def local_username_and_domain
  142. "#{username}@#{Rails.configuration.x.local_domain}"
  143. end
  144. def to_webfinger_s
  145. "acct:#{local_username_and_domain}"
  146. end
  147. def subscribed?
  148. subscription_expires_at.present?
  149. end
  150. def possibly_stale?
  151. last_webfingered_at.nil? || last_webfingered_at <= 1.day.ago
  152. end
  153. def refresh!
  154. return if local?
  155. ResolveAccountService.new.call(acct)
  156. end
  157. def unsuspend!
  158. transaction do
  159. user&.enable! if local?
  160. update!(suspended: false)
  161. end
  162. end
  163. def memorialize!
  164. transaction do
  165. user&.disable! if local?
  166. update!(memorial: true)
  167. end
  168. end
  169. def keypair
  170. @keypair ||= OpenSSL::PKey::RSA.new(private_key || public_key)
  171. end
  172. def fields
  173. (self[:fields] || []).map { |f| Field.new(self, f) }
  174. end
  175. def fields_attributes=(attributes)
  176. fields = []
  177. if attributes.is_a?(Hash)
  178. attributes.each_value do |attr|
  179. next if attr[:name].blank?
  180. fields << attr
  181. end
  182. end
  183. self[:fields] = fields
  184. end
  185. def build_fields
  186. return if fields.size >= 4
  187. raw_fields = self[:fields] || []
  188. add_fields = 4 - raw_fields.size
  189. add_fields.times { raw_fields << { name: '', value: '' } }
  190. self.fields = raw_fields
  191. end
  192. def magic_key
  193. modulus, exponent = [keypair.public_key.n, keypair.public_key.e].map do |component|
  194. result = []
  195. until component.zero?
  196. result << [component % 256].pack('C')
  197. component >>= 8
  198. end
  199. result.reverse.join
  200. end
  201. (['RSA'] + [modulus, exponent].map { |n| Base64.urlsafe_encode64(n) }).join('.')
  202. end
  203. def subscription(webhook_url)
  204. @subscription ||= OStatus2::Subscription.new(remote_url, secret: secret, webhook: webhook_url, hub: hub_url)
  205. end
  206. def save_with_optional_media!
  207. save!
  208. rescue ActiveRecord::RecordInvalid
  209. self.avatar = nil
  210. self.header = nil
  211. self[:avatar_remote_url] = ''
  212. self[:header_remote_url] = ''
  213. save!
  214. end
  215. def object_type
  216. :person
  217. end
  218. def to_param
  219. username
  220. end
  221. def excluded_from_timeline_account_ids
  222. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  223. end
  224. def excluded_from_timeline_domains
  225. Rails.cache.fetch("exclude_domains_for:#{id}") { domain_blocks.pluck(:domain) }
  226. end
  227. def preferred_inbox_url
  228. shared_inbox_url.presence || inbox_url
  229. end
  230. class Field < ActiveModelSerializers::Model
  231. attributes :name, :value, :account, :errors
  232. def initialize(account, attr)
  233. @account = account
  234. @name = attr['name'].strip[0, 255]
  235. @value = attr['value'].strip[0, 255]
  236. @errors = {}
  237. end
  238. def to_h
  239. { name: @name, value: @value }
  240. end
  241. end
  242. class << self
  243. def readonly_attributes
  244. super - %w(statuses_count following_count followers_count)
  245. end
  246. def domains
  247. reorder(nil).pluck(Arel.sql('distinct accounts.domain'))
  248. end
  249. def inboxes
  250. urls = reorder(nil).where(protocol: :activitypub).pluck(Arel.sql("distinct coalesce(nullif(accounts.shared_inbox_url, ''), accounts.inbox_url)"))
  251. DeliveryFailureTracker.filter(urls)
  252. end
  253. def triadic_closures(account, limit: 5, offset: 0)
  254. sql = <<-SQL.squish
  255. WITH first_degree AS (
  256. SELECT target_account_id
  257. FROM follows
  258. WHERE account_id = :account_id
  259. )
  260. SELECT accounts.*
  261. FROM follows
  262. INNER JOIN accounts ON follows.target_account_id = accounts.id
  263. WHERE
  264. account_id IN (SELECT * FROM first_degree)
  265. AND target_account_id NOT IN (SELECT * FROM first_degree)
  266. AND target_account_id NOT IN (:excluded_account_ids)
  267. AND accounts.suspended = false
  268. GROUP BY target_account_id, accounts.id
  269. ORDER BY count(account_id) DESC
  270. OFFSET :offset
  271. LIMIT :limit
  272. SQL
  273. excluded_account_ids = account.excluded_from_timeline_account_ids + [account.id]
  274. find_by_sql(
  275. [sql, { account_id: account.id, excluded_account_ids: excluded_account_ids, limit: limit, offset: offset }]
  276. )
  277. end
  278. def search_for(terms, limit = 10)
  279. textsearch, query = generate_query_for_search(terms)
  280. sql = <<-SQL.squish
  281. SELECT
  282. accounts.*,
  283. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  284. FROM accounts
  285. WHERE #{query} @@ #{textsearch}
  286. AND accounts.suspended = false
  287. AND accounts.moved_to_account_id IS NULL
  288. ORDER BY rank DESC
  289. LIMIT ?
  290. SQL
  291. find_by_sql([sql, limit])
  292. end
  293. def advanced_search_for(terms, account, limit = 10, following = false)
  294. textsearch, query = generate_query_for_search(terms)
  295. if following
  296. sql = <<-SQL.squish
  297. WITH first_degree AS (
  298. SELECT target_account_id
  299. FROM follows
  300. WHERE account_id = ?
  301. )
  302. SELECT
  303. accounts.*,
  304. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  305. FROM accounts
  306. 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 = ?)
  307. WHERE accounts.id IN (SELECT * FROM first_degree)
  308. AND #{query} @@ #{textsearch}
  309. AND accounts.suspended = false
  310. AND accounts.moved_to_account_id IS NULL
  311. GROUP BY accounts.id
  312. ORDER BY rank DESC
  313. LIMIT ?
  314. SQL
  315. find_by_sql([sql, account.id, account.id, account.id, limit])
  316. else
  317. sql = <<-SQL.squish
  318. SELECT
  319. accounts.*,
  320. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  321. FROM accounts
  322. 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 = ?)
  323. WHERE #{query} @@ #{textsearch}
  324. AND accounts.suspended = false
  325. AND accounts.moved_to_account_id IS NULL
  326. GROUP BY accounts.id
  327. ORDER BY rank DESC
  328. LIMIT ?
  329. SQL
  330. find_by_sql([sql, account.id, account.id, limit])
  331. end
  332. end
  333. private
  334. def generate_query_for_search(terms)
  335. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  336. textsearch = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  337. query = "to_tsquery('simple', ''' ' || #{terms} || ' ''' || ':*')"
  338. [textsearch, query]
  339. end
  340. end
  341. def emojis
  342. @emojis ||= CustomEmoji.from_text(emojifiable_text, domain)
  343. end
  344. before_create :generate_keys
  345. before_validation :normalize_domain
  346. before_validation :prepare_contents, if: :local?
  347. private
  348. def prepare_contents
  349. display_name&.strip!
  350. note&.strip!
  351. end
  352. def generate_keys
  353. return unless local? && !Rails.env.test?
  354. keypair = OpenSSL::PKey::RSA.new(2048)
  355. self.private_key = keypair.to_pem
  356. self.public_key = keypair.public_key.to_pem
  357. end
  358. def normalize_domain
  359. return if local?
  360. self.domain = TagManager.instance.normalize_domain(domain)
  361. end
  362. def emojifiable_text
  363. [note, display_name, fields.map(&:value)].join(' ')
  364. end
  365. end