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.

281 lines
9.8 KiB

8 years ago
8 years ago
8 years ago
8 years ago
  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[:avatar_remote_url] = ''
  114. save!
  115. end
  116. def avatar_remote_url=(url)
  117. parsed_url = URI.parse(url)
  118. return if !%w(http https).include?(parsed_url.scheme) || parsed_url.host.empty? || self[:avatar_remote_url] == url
  119. self.avatar = parsed_url
  120. self[:avatar_remote_url] = url
  121. rescue OpenURI::HTTPError => e
  122. Rails.logger.debug "Error fetching remote avatar: #{e}"
  123. end
  124. def object_type
  125. :person
  126. end
  127. def to_param
  128. username
  129. end
  130. class << self
  131. def find_local!(username)
  132. find_remote!(username, nil)
  133. end
  134. def find_remote!(username, domain)
  135. return if username.blank?
  136. where(arel_table[:username].matches(username.gsub(/[%_]/, '\\\\\0'))).where(domain.nil? ? { domain: nil } : arel_table[:domain].matches(domain.gsub(/[%_]/, '\\\\\0'))).take!
  137. end
  138. def find_local(username)
  139. find_local!(username)
  140. rescue ActiveRecord::RecordNotFound
  141. nil
  142. end
  143. def find_remote(username, domain)
  144. find_remote!(username, domain)
  145. rescue ActiveRecord::RecordNotFound
  146. nil
  147. end
  148. def triadic_closures(account, limit = 5)
  149. sql = <<SQL
  150. WITH first_degree AS (
  151. SELECT target_account_id
  152. FROM follows
  153. WHERE account_id = ?
  154. )
  155. SELECT accounts.*
  156. FROM follows
  157. INNER JOIN accounts ON follows.target_account_id = accounts.id
  158. WHERE account_id IN (SELECT * FROM first_degree) AND target_account_id NOT IN (SELECT * FROM first_degree) AND target_account_id <> ?
  159. GROUP BY target_account_id, accounts.id
  160. ORDER BY count(account_id) DESC
  161. LIMIT ?
  162. SQL
  163. Account.find_by_sql([sql, account.id, account.id, limit])
  164. end
  165. def search_for(terms, limit = 10)
  166. textsearch = '(setweight(to_tsvector(\'simple\', accounts.display_name), \'A\') || setweight(to_tsvector(\'simple\', accounts.username), \'B\') || setweight(to_tsvector(\'simple\', coalesce(accounts.domain, \'\')), \'C\'))'
  167. query = 'to_tsquery(\'simple\', \'\'\' \' || ? || \' \'\'\' || \':*\')'
  168. sql = <<SQL
  169. SELECT
  170. accounts.*,
  171. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  172. FROM accounts
  173. WHERE #{query} @@ #{textsearch}
  174. ORDER BY rank DESC
  175. LIMIT ?
  176. SQL
  177. Account.find_by_sql([sql, terms, terms, limit])
  178. end
  179. def advanced_search_for(terms, account, limit = 10)
  180. textsearch = '(setweight(to_tsvector(\'simple\', accounts.display_name), \'A\') || setweight(to_tsvector(\'simple\', accounts.username), \'B\') || setweight(to_tsvector(\'simple\', coalesce(accounts.domain, \'\')), \'C\'))'
  181. query = 'to_tsquery(\'simple\', \'\'\' \' || ? || \' \'\'\' || \':*\')'
  182. sql = <<SQL
  183. SELECT
  184. accounts.*,
  185. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  186. FROM accounts
  187. 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 = ?)
  188. WHERE #{query} @@ #{textsearch}
  189. GROUP BY accounts.id
  190. ORDER BY rank DESC
  191. LIMIT ?
  192. SQL
  193. Account.find_by_sql([sql, terms, account.id, account.id, terms, limit])
  194. end
  195. def following_map(target_account_ids, account_id)
  196. follow_mapping(Follow.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  197. end
  198. def followed_by_map(target_account_ids, account_id)
  199. follow_mapping(Follow.where(account_id: target_account_ids, target_account_id: account_id), :account_id)
  200. end
  201. def blocking_map(target_account_ids, account_id)
  202. follow_mapping(Block.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  203. end
  204. def muting_map(target_account_ids, account_id)
  205. follow_mapping(Mute.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  206. end
  207. def requested_map(target_account_ids, account_id)
  208. follow_mapping(FollowRequest.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  209. end
  210. private
  211. def follow_mapping(query, field)
  212. query.pluck(field).inject({}) { |mapping, id| mapping[id] = true; mapping }
  213. end
  214. end
  215. before_create do
  216. if local?
  217. keypair = OpenSSL::PKey::RSA.new(Rails.env.test? ? 1024 : 2048)
  218. self.private_key = keypair.to_pem
  219. self.public_key = keypair.public_key.to_pem
  220. end
  221. end
  222. end