The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

371 lines
12 KiB

  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. has_many :conversation_mutes
  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. scope :remote, -> { where.not(domain: nil) }
  85. scope :local, -> { where(domain: nil) }
  86. scope :without_followers, -> { where(followers_count: 0) }
  87. scope :with_followers, -> { where('followers_count > 0') }
  88. scope :expiring, ->(time) { where(subscription_expires_at: nil).or(where('subscription_expires_at < ?', time)).remote.with_followers }
  89. scope :partitioned, -> { order('row_number() over (partition by domain)') }
  90. scope :silenced, -> { where(silenced: true) }
  91. scope :suspended, -> { where(suspended: true) }
  92. scope :recent, -> { reorder(id: :desc) }
  93. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  94. scope :by_domain_accounts, -> { group(:domain).select(:domain, 'COUNT(*) AS accounts_count').order('accounts_count desc') }
  95. delegate :email,
  96. :current_sign_in_ip,
  97. :current_sign_in_at,
  98. :confirmed?,
  99. :locale,
  100. to: :user,
  101. prefix: true,
  102. allow_nil: true
  103. delegate :allowed_languages, to: :user, prefix: false, allow_nil: true
  104. def follow!(other_account)
  105. active_relationships.find_or_create_by!(target_account: other_account)
  106. end
  107. def block!(other_account)
  108. block_relationships.find_or_create_by!(target_account: other_account)
  109. end
  110. def mute!(other_account)
  111. mute_relationships.find_or_create_by!(target_account: other_account)
  112. end
  113. def mute_conversation!(conversation)
  114. conversation_mutes.find_or_create_by!(conversation: conversation)
  115. end
  116. def unfollow!(other_account)
  117. follow = active_relationships.find_by(target_account: other_account)
  118. follow&.destroy
  119. end
  120. def unblock!(other_account)
  121. block = block_relationships.find_by(target_account: other_account)
  122. block&.destroy
  123. end
  124. def unmute!(other_account)
  125. mute = mute_relationships.find_by(target_account: other_account)
  126. mute&.destroy
  127. end
  128. def unmute_conversation!(conversation)
  129. mute = conversation_mutes.find_by(conversation: conversation)
  130. mute&.destroy!
  131. end
  132. def following?(other_account)
  133. following.include?(other_account)
  134. end
  135. def blocking?(other_account)
  136. blocking.include?(other_account)
  137. end
  138. def muting?(other_account)
  139. muting.include?(other_account)
  140. end
  141. def muting_conversation?(conversation)
  142. conversation_mutes.where(conversation: conversation).exists?
  143. end
  144. def requested?(other_account)
  145. follow_requests.where(target_account: other_account).exists?
  146. end
  147. def local?
  148. domain.nil?
  149. end
  150. def acct
  151. local? ? username : "#{username}@#{domain}"
  152. end
  153. def local_username_and_domain
  154. "#{username}@#{Rails.configuration.x.local_domain}"
  155. end
  156. def to_webfinger_s
  157. "acct:#{local_username_and_domain}"
  158. end
  159. def subscribed?
  160. subscription_expires_at.present?
  161. end
  162. def followers_domains
  163. followers.reorder(nil).pluck('distinct accounts.domain')
  164. end
  165. def favourited?(status)
  166. status.proper.favourites.where(account: self).exists?
  167. end
  168. def reblogged?(status)
  169. status.proper.reblogs.where(account: self).exists?
  170. end
  171. def keypair
  172. OpenSSL::PKey::RSA.new(private_key || public_key)
  173. end
  174. def subscription(webhook_url)
  175. OStatus2::Subscription.new(remote_url, secret: secret, lease_seconds: 86_400 * 30, webhook: webhook_url, hub: hub_url)
  176. end
  177. def save_with_optional_media!
  178. save!
  179. rescue ActiveRecord::RecordInvalid
  180. self.avatar = nil
  181. self.header = nil
  182. self[:avatar_remote_url] = ''
  183. self[:header_remote_url] = ''
  184. save!
  185. end
  186. def object_type
  187. :person
  188. end
  189. def to_param
  190. username
  191. end
  192. def excluded_from_timeline_account_ids
  193. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  194. end
  195. class << self
  196. def find_local!(username)
  197. find_remote!(username, nil)
  198. end
  199. def find_remote!(username, domain)
  200. return if username.blank?
  201. where('lower(accounts.username) = ?', username.downcase).where(domain.nil? ? { domain: nil } : 'lower(accounts.domain) = ?', domain&.downcase).take!
  202. end
  203. def find_local(username)
  204. find_local!(username)
  205. rescue ActiveRecord::RecordNotFound
  206. nil
  207. end
  208. def find_remote(username, domain)
  209. find_remote!(username, domain)
  210. rescue ActiveRecord::RecordNotFound
  211. nil
  212. end
  213. def triadic_closures(account, limit = 5)
  214. sql = <<-SQL.squish
  215. WITH first_degree AS (
  216. SELECT target_account_id
  217. FROM follows
  218. WHERE account_id = :account_id
  219. )
  220. SELECT accounts.*
  221. FROM follows
  222. INNER JOIN accounts ON follows.target_account_id = accounts.id
  223. WHERE account_id IN (SELECT * FROM first_degree) AND target_account_id NOT IN (SELECT * FROM first_degree) AND target_account_id <> :account_id
  224. GROUP BY target_account_id, accounts.id
  225. ORDER BY count(account_id) DESC
  226. LIMIT :limit
  227. SQL
  228. find_by_sql(
  229. [sql, { account_id: account.id, limit: limit }]
  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. ORDER BY rank DESC
  241. LIMIT ?
  242. SQL
  243. find_by_sql([sql, limit])
  244. end
  245. def advanced_search_for(terms, account, limit = 10)
  246. textsearch, query = generate_query_for_search(terms)
  247. sql = <<-SQL.squish
  248. SELECT
  249. accounts.*,
  250. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  251. FROM accounts
  252. 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 = ?)
  253. WHERE #{query} @@ #{textsearch}
  254. GROUP BY accounts.id
  255. ORDER BY rank DESC
  256. LIMIT ?
  257. SQL
  258. find_by_sql([sql, account.id, account.id, limit])
  259. end
  260. def following_map(target_account_ids, account_id)
  261. follow_mapping(Follow.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  262. end
  263. def followed_by_map(target_account_ids, account_id)
  264. follow_mapping(Follow.where(account_id: target_account_ids, target_account_id: account_id), :account_id)
  265. end
  266. def blocking_map(target_account_ids, account_id)
  267. follow_mapping(Block.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  268. end
  269. def muting_map(target_account_ids, account_id)
  270. follow_mapping(Mute.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  271. end
  272. def requested_map(target_account_ids, account_id)
  273. follow_mapping(FollowRequest.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  274. end
  275. private
  276. def generate_query_for_search(terms)
  277. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  278. textsearch = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  279. query = "to_tsquery('simple', ''' ' || #{terms} || ' ''' || ':*')"
  280. [textsearch, query]
  281. end
  282. def follow_mapping(query, field)
  283. query.pluck(field).each_with_object({}) { |id, mapping| mapping[id] = true }
  284. end
  285. end
  286. before_create :generate_keys
  287. before_validation :normalize_domain
  288. private
  289. def generate_keys
  290. return unless local?
  291. keypair = OpenSSL::PKey::RSA.new(Rails.env.test? ? 1024 : 2048)
  292. self.private_key = keypair.to_pem
  293. self.public_key = keypair.public_key.to_pem
  294. end
  295. def normalize_domain
  296. return if local?
  297. self.domain = TagManager.instance.normalize_domain(domain)
  298. end
  299. end