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.
 
 
 
 

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