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.
 
 
 
 

295 lines
10 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: { original: '120x120#' }, 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: { original: '700x335#' }, 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. scope :remote, -> { where.not(domain: nil) }
  44. scope :local, -> { where(domain: nil) }
  45. scope :without_followers, -> { where('(select count(f.id) from follows as f where f.target_account_id = accounts.id) = 0') }
  46. scope :with_followers, -> { where('(select count(f.id) from follows as f where f.target_account_id = accounts.id) > 0') }
  47. scope :expiring, ->(time) { where(subscription_expires_at: nil).or(where('subscription_expires_at < ?', time)).remote.with_followers }
  48. scope :silenced, -> { where(silenced: true) }
  49. scope :suspended, -> { where(suspended: true) }
  50. scope :recent, -> { reorder(id: :desc) }
  51. scope :alphabetic, -> { order(domain: :asc, username: :asc) }
  52. def follow!(other_account)
  53. active_relationships.where(target_account: other_account).first_or_create!(target_account: other_account)
  54. end
  55. def block!(other_account)
  56. block_relationships.where(target_account: other_account).first_or_create!(target_account: other_account)
  57. end
  58. def mute!(other_account)
  59. mute_relationships.where(target_account: other_account).first_or_create!(target_account: other_account)
  60. end
  61. def unfollow!(other_account)
  62. follow = active_relationships.find_by(target_account: other_account)
  63. follow&.destroy
  64. end
  65. def unblock!(other_account)
  66. block = block_relationships.find_by(target_account: other_account)
  67. block&.destroy
  68. end
  69. def unmute!(other_account)
  70. mute = mute_relationships.find_by(target_account: other_account)
  71. mute&.destroy
  72. end
  73. def following?(other_account)
  74. following.include?(other_account)
  75. end
  76. def blocking?(other_account)
  77. blocking.include?(other_account)
  78. end
  79. def muting?(other_account)
  80. muting.include?(other_account)
  81. end
  82. def requested?(other_account)
  83. follow_requests.where(target_account: other_account).exists?
  84. end
  85. def followers_domains
  86. followers.reorder('').select('DISTINCT accounts.domain').map(&:domain)
  87. end
  88. def local?
  89. domain.nil?
  90. end
  91. def acct
  92. local? ? username : "#{username}@#{domain}"
  93. end
  94. def subscribed?
  95. !subscription_expires_at.blank?
  96. end
  97. def favourited?(status)
  98. (status.reblog? ? status.reblog : status).favourites.where(account: self).count.positive?
  99. end
  100. def reblogged?(status)
  101. (status.reblog? ? status.reblog : status).reblogs.where(account: self).count.positive?
  102. end
  103. def keypair
  104. private_key.nil? ? OpenSSL::PKey::RSA.new(public_key) : OpenSSL::PKey::RSA.new(private_key)
  105. end
  106. def subscription(webhook_url)
  107. OStatus2::Subscription.new(remote_url, secret: secret, lease_seconds: 86_400 * 30, webhook: webhook_url, hub: hub_url)
  108. end
  109. def save_with_optional_avatar!
  110. save!
  111. rescue ActiveRecord::RecordInvalid
  112. self.avatar = nil
  113. self.header = nil
  114. self[:avatar_remote_url] = ''
  115. self[:header_remote_url] = ''
  116. save!
  117. end
  118. def avatar_remote_url=(url)
  119. parsed_url = URI.parse(url)
  120. return if !%w(http https).include?(parsed_url.scheme) || parsed_url.host.empty? || self[:avatar_remote_url] == url
  121. self.avatar = parsed_url
  122. self[:avatar_remote_url] = url
  123. rescue OpenURI::HTTPError => e
  124. Rails.logger.debug "Error fetching remote avatar: #{e}"
  125. end
  126. def header_remote_url=(url)
  127. parsed_url = URI.parse(url)
  128. return if !%w(http https).include?(parsed_url.scheme) || parsed_url.host.empty? || self[:header_remote_url] == url
  129. self.header = parsed_url
  130. self[:header_remote_url] = url
  131. rescue OpenURI::HTTPError => e
  132. Rails.logger.debug "Error fetching remote header: #{e}"
  133. end
  134. def object_type
  135. :person
  136. end
  137. def to_param
  138. username
  139. end
  140. class << self
  141. def find_local!(username)
  142. find_remote!(username, nil)
  143. end
  144. def find_remote!(username, domain)
  145. return if username.blank?
  146. where(arel_table[:username].matches(username.gsub(/[%_]/, '\\\\\0'))).where(domain.nil? ? { domain: nil } : arel_table[:domain].matches(domain.gsub(/[%_]/, '\\\\\0'))).take!
  147. end
  148. def find_local(username)
  149. find_local!(username)
  150. rescue ActiveRecord::RecordNotFound
  151. nil
  152. end
  153. def find_remote(username, domain)
  154. find_remote!(username, domain)
  155. rescue ActiveRecord::RecordNotFound
  156. nil
  157. end
  158. def triadic_closures(account, limit = 5)
  159. sql = <<SQL
  160. WITH first_degree AS (
  161. SELECT target_account_id
  162. FROM follows
  163. WHERE account_id = ?
  164. )
  165. SELECT accounts.*
  166. FROM follows
  167. INNER JOIN accounts ON follows.target_account_id = accounts.id
  168. WHERE account_id IN (SELECT * FROM first_degree) AND target_account_id NOT IN (SELECT * FROM first_degree) AND target_account_id <> ?
  169. GROUP BY target_account_id, accounts.id
  170. ORDER BY count(account_id) DESC
  171. LIMIT ?
  172. SQL
  173. Account.find_by_sql([sql, account.id, account.id, limit])
  174. end
  175. def search_for(terms, limit = 10)
  176. textsearch = '(setweight(to_tsvector(\'simple\', accounts.display_name), \'A\') || setweight(to_tsvector(\'simple\', accounts.username), \'B\') || setweight(to_tsvector(\'simple\', coalesce(accounts.domain, \'\')), \'C\'))'
  177. query = 'to_tsquery(\'simple\', \'\'\' \' || ? || \' \'\'\' || \':*\')'
  178. sql = <<SQL
  179. SELECT
  180. accounts.*,
  181. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  182. FROM accounts
  183. WHERE #{query} @@ #{textsearch}
  184. ORDER BY rank DESC
  185. LIMIT ?
  186. SQL
  187. Account.find_by_sql([sql, terms, terms, limit])
  188. end
  189. def advanced_search_for(terms, account, limit = 10)
  190. textsearch = '(setweight(to_tsvector(\'simple\', accounts.display_name), \'A\') || setweight(to_tsvector(\'simple\', accounts.username), \'B\') || setweight(to_tsvector(\'simple\', coalesce(accounts.domain, \'\')), \'C\'))'
  191. query = 'to_tsquery(\'simple\', \'\'\' \' || ? || \' \'\'\' || \':*\')'
  192. sql = <<SQL
  193. SELECT
  194. accounts.*,
  195. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  196. FROM accounts
  197. 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 = ?)
  198. WHERE #{query} @@ #{textsearch}
  199. GROUP BY accounts.id
  200. ORDER BY rank DESC
  201. LIMIT ?
  202. SQL
  203. Account.find_by_sql([sql, terms, account.id, account.id, terms, limit])
  204. end
  205. def following_map(target_account_ids, account_id)
  206. follow_mapping(Follow.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  207. end
  208. def followed_by_map(target_account_ids, account_id)
  209. follow_mapping(Follow.where(account_id: target_account_ids, target_account_id: account_id), :account_id)
  210. end
  211. def blocking_map(target_account_ids, account_id)
  212. follow_mapping(Block.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  213. end
  214. def muting_map(target_account_ids, account_id)
  215. follow_mapping(Mute.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  216. end
  217. def requested_map(target_account_ids, account_id)
  218. follow_mapping(FollowRequest.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  219. end
  220. private
  221. def follow_mapping(query, field)
  222. query.pluck(field).inject({}) { |mapping, id| mapping[id] = true; mapping }
  223. end
  224. end
  225. before_create do
  226. if local?
  227. keypair = OpenSSL::PKey::RSA.new(Rails.env.test? ? 1024 : 2048)
  228. self.private_key = keypair.to_pem
  229. self.public_key = keypair.public_key.to_pem
  230. end
  231. end
  232. end