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.
 
 
 
 

356 satır
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 = /(?:^|[^\/\w])@([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. to: :user,
  99. prefix: true,
  100. allow_nil: true
  101. delegate :allowed_languages, to: :user, prefix: false, allow_nil: true
  102. def follow!(other_account)
  103. active_relationships.find_or_create_by!(target_account: other_account)
  104. end
  105. def block!(other_account)
  106. block_relationships.find_or_create_by!(target_account: other_account)
  107. end
  108. def mute!(other_account)
  109. mute_relationships.find_or_create_by!(target_account: other_account)
  110. end
  111. def unfollow!(other_account)
  112. follow = active_relationships.find_by(target_account: other_account)
  113. follow&.destroy
  114. end
  115. def unblock!(other_account)
  116. block = block_relationships.find_by(target_account: other_account)
  117. block&.destroy
  118. end
  119. def unmute!(other_account)
  120. mute = mute_relationships.find_by(target_account: other_account)
  121. mute&.destroy
  122. end
  123. def following?(other_account)
  124. following.include?(other_account)
  125. end
  126. def blocking?(other_account)
  127. blocking.include?(other_account)
  128. end
  129. def muting?(other_account)
  130. muting.include?(other_account)
  131. end
  132. def requested?(other_account)
  133. follow_requests.where(target_account: other_account).exists?
  134. end
  135. def local?
  136. domain.nil?
  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 followers_domains
  151. followers.reorder(nil).pluck('distinct accounts.domain')
  152. end
  153. def favourited?(status)
  154. status.proper.favourites.where(account: self).exists?
  155. end
  156. def reblogged?(status)
  157. status.proper.reblogs.where(account: self).exists?
  158. end
  159. def keypair
  160. OpenSSL::PKey::RSA.new(private_key || public_key)
  161. end
  162. def subscription(webhook_url)
  163. OStatus2::Subscription.new(remote_url, secret: secret, lease_seconds: 86_400 * 30, webhook: webhook_url, hub: hub_url)
  164. end
  165. def save_with_optional_media!
  166. save!
  167. rescue ActiveRecord::RecordInvalid
  168. self.avatar = nil
  169. self.header = nil
  170. self[:avatar_remote_url] = ''
  171. self[:header_remote_url] = ''
  172. save!
  173. end
  174. def object_type
  175. :person
  176. end
  177. def to_param
  178. username
  179. end
  180. def excluded_from_timeline_account_ids
  181. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  182. end
  183. class << self
  184. def find_local!(username)
  185. find_remote!(username, nil)
  186. end
  187. def find_remote!(username, domain)
  188. return if username.blank?
  189. where('lower(accounts.username) = ?', username.downcase).where(domain.nil? ? { domain: nil } : 'lower(accounts.domain) = ?', domain&.downcase).take!
  190. end
  191. def find_local(username)
  192. find_local!(username)
  193. rescue ActiveRecord::RecordNotFound
  194. nil
  195. end
  196. def find_remote(username, domain)
  197. find_remote!(username, domain)
  198. rescue ActiveRecord::RecordNotFound
  199. nil
  200. end
  201. def triadic_closures(account, limit = 5)
  202. sql = <<-SQL.squish
  203. WITH first_degree AS (
  204. SELECT target_account_id
  205. FROM follows
  206. WHERE account_id = :account_id
  207. )
  208. SELECT accounts.*
  209. FROM follows
  210. INNER JOIN accounts ON follows.target_account_id = accounts.id
  211. WHERE account_id IN (SELECT * FROM first_degree) AND target_account_id NOT IN (SELECT * FROM first_degree) AND target_account_id <> :account_id
  212. GROUP BY target_account_id, accounts.id
  213. ORDER BY count(account_id) DESC
  214. LIMIT :limit
  215. SQL
  216. find_by_sql(
  217. [sql, { account_id: account.id, limit: limit }]
  218. )
  219. end
  220. def search_for(terms, limit = 10)
  221. textsearch, query = generate_query_for_search(terms)
  222. sql = <<-SQL.squish
  223. SELECT
  224. accounts.*,
  225. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  226. FROM accounts
  227. WHERE #{query} @@ #{textsearch}
  228. ORDER BY rank DESC
  229. LIMIT ?
  230. SQL
  231. find_by_sql([sql, limit])
  232. end
  233. def advanced_search_for(terms, account, limit = 10)
  234. textsearch, query = generate_query_for_search(terms)
  235. sql = <<-SQL.squish
  236. SELECT
  237. accounts.*,
  238. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  239. FROM accounts
  240. 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 = ?)
  241. WHERE #{query} @@ #{textsearch}
  242. GROUP BY accounts.id
  243. ORDER BY rank DESC
  244. LIMIT ?
  245. SQL
  246. find_by_sql([sql, account.id, account.id, limit])
  247. end
  248. def following_map(target_account_ids, account_id)
  249. follow_mapping(Follow.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  250. end
  251. def followed_by_map(target_account_ids, account_id)
  252. follow_mapping(Follow.where(account_id: target_account_ids, target_account_id: account_id), :account_id)
  253. end
  254. def blocking_map(target_account_ids, account_id)
  255. follow_mapping(Block.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  256. end
  257. def muting_map(target_account_ids, account_id)
  258. follow_mapping(Mute.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  259. end
  260. def requested_map(target_account_ids, account_id)
  261. follow_mapping(FollowRequest.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  262. end
  263. private
  264. def generate_query_for_search(terms)
  265. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  266. textsearch = "(setweight(to_tsvector('simple', accounts.display_name), 'A') || setweight(to_tsvector('simple', accounts.username), 'B') || setweight(to_tsvector('simple', coalesce(accounts.domain, '')), 'C'))"
  267. query = "to_tsquery('simple', ''' ' || #{terms} || ' ''' || ':*')"
  268. [textsearch, query]
  269. end
  270. def follow_mapping(query, field)
  271. query.pluck(field).each_with_object({}) { |id, mapping| mapping[id] = true }
  272. end
  273. end
  274. before_create :generate_keys
  275. before_validation :normalize_domain
  276. private
  277. def generate_keys
  278. return unless local?
  279. keypair = OpenSSL::PKey::RSA.new(Rails.env.test? ? 1024 : 2048)
  280. self.private_key = keypair.to_pem
  281. self.public_key = keypair.public_key.to_pem
  282. end
  283. def normalize_domain
  284. return if local?
  285. self.domain = TagManager.instance.normalize_domain(domain)
  286. end
  287. end