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.
 
 
 
 

369 lines
12 KiB

  1. # frozen_string_literal: true
  2. class Account < ApplicationRecord
  3. include Targetable
  4. MENTION_RE = /(?:^|[^\/\w])@([a-z0-9_]+(?:@[a-z0-9\.\-]+[a-z0-9]+)?)/i
  5. IMAGE_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif'].freeze
  6. # Local users
  7. has_one :user, inverse_of: :account
  8. validates :username, presence: true, format: { with: /\A[a-z0-9_]+\z/i }, uniqueness: { scope: :domain, case_sensitive: false }, length: { maximum: 30 }, if: 'local?'
  9. validates :username, presence: true, uniqueness: { scope: :domain, case_sensitive: true }, unless: 'local?'
  10. # Avatar upload
  11. has_attached_file :avatar, styles: ->(f) { avatar_styles(f) }, convert_options: { all: '-quality 80 -strip' }
  12. validates_attachment_content_type :avatar, content_type: IMAGE_MIME_TYPES
  13. validates_attachment_size :avatar, less_than: 2.megabytes
  14. # Header upload
  15. has_attached_file :header, styles: ->(f) { header_styles(f) }, convert_options: { all: '-quality 80 -strip' }
  16. validates_attachment_content_type :header, content_type: IMAGE_MIME_TYPES
  17. validates_attachment_size :header, less_than: 2.megabytes
  18. include Attachmentable
  19. # Local user profile validations
  20. validates :display_name, length: { maximum: 30 }, if: 'local?'
  21. validates :note, length: { maximum: 160 }, if: 'local?'
  22. # Timelines
  23. has_many :stream_entries, inverse_of: :account, dependent: :destroy
  24. has_many :statuses, inverse_of: :account, dependent: :destroy
  25. has_many :favourites, inverse_of: :account, dependent: :destroy
  26. has_many :mentions, inverse_of: :account, dependent: :destroy
  27. has_many :notifications, inverse_of: :account, dependent: :destroy
  28. # Follow relations
  29. has_many :follow_requests, dependent: :destroy
  30. has_many :active_relationships, class_name: 'Follow', foreign_key: 'account_id', dependent: :destroy
  31. has_many :passive_relationships, class_name: 'Follow', foreign_key: 'target_account_id', dependent: :destroy
  32. has_many :following, -> { order('follows.id desc') }, through: :active_relationships, source: :target_account
  33. has_many :followers, -> { order('follows.id desc') }, through: :passive_relationships, source: :account
  34. # Block relationships
  35. has_many :block_relationships, class_name: 'Block', foreign_key: 'account_id', dependent: :destroy
  36. has_many :blocking, -> { order('blocks.id desc') }, through: :block_relationships, source: :target_account
  37. has_many :blocked_by_relationships, class_name: 'Block', foreign_key: :target_account_id, dependent: :destroy
  38. has_many :blocked_by, -> { order('blocks.id desc') }, through: :blocked_by_relationships, source: :account
  39. # Mute relationships
  40. has_many :mute_relationships, class_name: 'Mute', foreign_key: 'account_id', dependent: :destroy
  41. has_many :muting, -> { order('mutes.id desc') }, through: :mute_relationships, source: :target_account
  42. # Media
  43. has_many :media_attachments, dependent: :destroy
  44. # PuSH subscriptions
  45. has_many :subscriptions, dependent: :destroy
  46. # Report relationships
  47. has_many :reports
  48. has_many :targeted_reports, class_name: 'Report', foreign_key: :target_account_id
  49. scope :remote, -> { where.not(domain: nil) }
  50. scope :local, -> { where(domain: nil) }
  51. scope :without_followers, -> { where('(select count(f.id) from follows as f where f.target_account_id = accounts.id) = 0') }
  52. scope :with_followers, -> { where('(select count(f.id) from follows as f where f.target_account_id = accounts.id) > 0') }
  53. scope :expiring, ->(time) { where(subscription_expires_at: nil).or(where('subscription_expires_at < ?', time)).remote.with_followers }
  54. scope :silenced, -> { where(silenced: true) }
  55. scope :suspended, -> { where(suspended: true) }
  56. scope :recent, -> { reorder(id: :desc) }
  57. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  58. scope :by_domain_accounts, -> { group(:domain).select(:domain, 'COUNT(*) AS accounts_count').order('accounts_count desc') }
  59. delegate :email,
  60. :current_sign_in_ip,
  61. :current_sign_in_at,
  62. :confirmed?,
  63. to: :user,
  64. prefix: true,
  65. allow_nil: true
  66. delegate :allowed_languages, to: :user, prefix: false, allow_nil: true
  67. def follow!(other_account)
  68. active_relationships.where(target_account: other_account).first_or_create!(target_account: other_account)
  69. end
  70. def block!(other_account)
  71. block_relationships.where(target_account: other_account).first_or_create!(target_account: other_account)
  72. end
  73. def mute!(other_account)
  74. mute_relationships.where(target_account: other_account).first_or_create!(target_account: other_account)
  75. end
  76. def unfollow!(other_account)
  77. follow = active_relationships.find_by(target_account: other_account)
  78. follow&.destroy
  79. end
  80. def unblock!(other_account)
  81. block = block_relationships.find_by(target_account: other_account)
  82. block&.destroy
  83. end
  84. def unmute!(other_account)
  85. mute = mute_relationships.find_by(target_account: other_account)
  86. mute&.destroy
  87. end
  88. def following?(other_account)
  89. following.include?(other_account)
  90. end
  91. def blocking?(other_account)
  92. blocking.include?(other_account)
  93. end
  94. def muting?(other_account)
  95. muting.include?(other_account)
  96. end
  97. def requested?(other_account)
  98. follow_requests.where(target_account: other_account).exists?
  99. end
  100. def local?
  101. domain.nil?
  102. end
  103. def acct
  104. local? ? username : "#{username}@#{domain}"
  105. end
  106. def local_username_and_domain
  107. "#{username}@#{Rails.configuration.x.local_domain}"
  108. end
  109. def to_webfinger_s
  110. "acct:#{local_username_and_domain}"
  111. end
  112. def subscribed?
  113. !subscription_expires_at.blank?
  114. end
  115. def followers_domains
  116. followers.reorder(nil).pluck('distinct accounts.domain')
  117. end
  118. def favourited?(status)
  119. status.proper.favourites.where(account: self).count.positive?
  120. end
  121. def reblogged?(status)
  122. status.proper.reblogs.where(account: self).count.positive?
  123. end
  124. def keypair
  125. private_key.nil? ? OpenSSL::PKey::RSA.new(public_key) : OpenSSL::PKey::RSA.new(private_key)
  126. end
  127. def subscription(webhook_url)
  128. OStatus2::Subscription.new(remote_url, secret: secret, lease_seconds: 86_400 * 30, webhook: webhook_url, hub: hub_url)
  129. end
  130. def save_with_optional_avatar!
  131. save!
  132. rescue ActiveRecord::RecordInvalid
  133. self.avatar = nil
  134. self.header = nil
  135. self[:avatar_remote_url] = ''
  136. self[:header_remote_url] = ''
  137. save!
  138. end
  139. def avatar_original_url
  140. avatar.url(:original)
  141. end
  142. def avatar_static_url
  143. avatar_content_type == 'image/gif' ? avatar.url(:static) : avatar_original_url
  144. end
  145. def header_original_url
  146. header.url(:original)
  147. end
  148. def header_static_url
  149. header_content_type == 'image/gif' ? header.url(:static) : header_original_url
  150. end
  151. def avatar_remote_url=(url)
  152. parsed_url = Addressable::URI.parse(url).normalize
  153. return if !%w(http https).include?(parsed_url.scheme) || parsed_url.host.empty? || self[:avatar_remote_url] == url
  154. self.avatar = URI.parse(parsed_url.to_s)
  155. self[:avatar_remote_url] = url
  156. rescue OpenURI::HTTPError => e
  157. Rails.logger.debug "Error fetching remote avatar: #{e}"
  158. end
  159. def header_remote_url=(url)
  160. parsed_url = Addressable::URI.parse(url).normalize
  161. return if !%w(http https).include?(parsed_url.scheme) || parsed_url.host.empty? || self[:header_remote_url] == url
  162. self.header = URI.parse(parsed_url.to_s)
  163. self[:header_remote_url] = url
  164. rescue OpenURI::HTTPError => e
  165. Rails.logger.debug "Error fetching remote header: #{e}"
  166. end
  167. def object_type
  168. :person
  169. end
  170. def to_param
  171. username
  172. end
  173. def excluded_from_timeline_account_ids
  174. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  175. end
  176. class << self
  177. def find_local!(username)
  178. find_remote!(username, nil)
  179. end
  180. def find_remote!(username, domain)
  181. return if username.blank?
  182. where('lower(accounts.username) = ?', username.downcase).where(domain.nil? ? { domain: nil } : 'lower(accounts.domain) = ?', domain&.downcase).take!
  183. end
  184. def find_local(username)
  185. find_local!(username)
  186. rescue ActiveRecord::RecordNotFound
  187. nil
  188. end
  189. def find_remote(username, domain)
  190. find_remote!(username, domain)
  191. rescue ActiveRecord::RecordNotFound
  192. nil
  193. end
  194. def triadic_closures(account, limit = 5)
  195. sql = <<-SQL.squish
  196. WITH first_degree AS (
  197. SELECT target_account_id
  198. FROM follows
  199. WHERE account_id = :account_id
  200. )
  201. SELECT accounts.*
  202. FROM follows
  203. INNER JOIN accounts ON follows.target_account_id = accounts.id
  204. WHERE account_id IN (SELECT * FROM first_degree) AND target_account_id NOT IN (SELECT * FROM first_degree) AND target_account_id <> :account_id
  205. GROUP BY target_account_id, accounts.id
  206. ORDER BY count(account_id) DESC
  207. LIMIT :limit
  208. SQL
  209. find_by_sql(
  210. [sql, { account_id: account.id, limit: limit }]
  211. )
  212. end
  213. def search_for(terms, limit = 10)
  214. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  215. textsearch = '(setweight(to_tsvector(\'simple\', accounts.display_name), \'A\') || setweight(to_tsvector(\'simple\', accounts.username), \'B\') || setweight(to_tsvector(\'simple\', coalesce(accounts.domain, \'\')), \'C\'))'
  216. query = 'to_tsquery(\'simple\', \'\'\' \' || ' + terms + ' || \' \'\'\' || \':*\')'
  217. sql = <<-SQL.squish
  218. SELECT
  219. accounts.*,
  220. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  221. FROM accounts
  222. WHERE #{query} @@ #{textsearch}
  223. ORDER BY rank DESC
  224. LIMIT ?
  225. SQL
  226. Account.find_by_sql([sql, limit])
  227. end
  228. def advanced_search_for(terms, account, limit = 10)
  229. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  230. textsearch = '(setweight(to_tsvector(\'simple\', accounts.display_name), \'A\') || setweight(to_tsvector(\'simple\', accounts.username), \'B\') || setweight(to_tsvector(\'simple\', coalesce(accounts.domain, \'\')), \'C\'))'
  231. query = 'to_tsquery(\'simple\', \'\'\' \' || ' + terms + ' || \' \'\'\' || \':*\')'
  232. sql = <<-SQL.squish
  233. SELECT
  234. accounts.*,
  235. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  236. FROM accounts
  237. 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 = ?)
  238. WHERE #{query} @@ #{textsearch}
  239. GROUP BY accounts.id
  240. ORDER BY rank DESC
  241. LIMIT ?
  242. SQL
  243. Account.find_by_sql([sql, account.id, account.id, limit])
  244. end
  245. def following_map(target_account_ids, account_id)
  246. follow_mapping(Follow.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  247. end
  248. def followed_by_map(target_account_ids, account_id)
  249. follow_mapping(Follow.where(account_id: target_account_ids, target_account_id: account_id), :account_id)
  250. end
  251. def blocking_map(target_account_ids, account_id)
  252. follow_mapping(Block.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  253. end
  254. def muting_map(target_account_ids, account_id)
  255. follow_mapping(Mute.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  256. end
  257. def requested_map(target_account_ids, account_id)
  258. follow_mapping(FollowRequest.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  259. end
  260. private
  261. def follow_mapping(query, field)
  262. query.pluck(field).each_with_object({}) { |id, mapping| mapping[id] = true }
  263. end
  264. def avatar_styles(file)
  265. styles = { original: '120x120#' }
  266. styles[:static] = { format: 'png' } if file.content_type == 'image/gif'
  267. styles
  268. end
  269. def header_styles(file)
  270. styles = { original: '700x335#' }
  271. styles[:static] = { format: 'png' } if file.content_type == 'image/gif'
  272. styles
  273. end
  274. end
  275. before_create :generate_keys
  276. before_validation :normalize_domain
  277. private
  278. def generate_keys
  279. return unless local?
  280. keypair = OpenSSL::PKey::RSA.new(Rails.env.test? ? 1024 : 2048)
  281. self.private_key = keypair.to_pem
  282. self.public_key = keypair.public_key.to_pem
  283. end
  284. def normalize_domain
  285. return if local?
  286. self.domain = TagManager.instance.normalize_domain(domain)
  287. end
  288. end