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.

366 lines
12 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 }, 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. def follow!(other_account)
  67. active_relationships.where(target_account: other_account).first_or_create!(target_account: other_account)
  68. end
  69. def block!(other_account)
  70. block_relationships.where(target_account: other_account).first_or_create!(target_account: other_account)
  71. end
  72. def mute!(other_account)
  73. mute_relationships.where(target_account: other_account).first_or_create!(target_account: other_account)
  74. end
  75. def unfollow!(other_account)
  76. follow = active_relationships.find_by(target_account: other_account)
  77. follow&.destroy
  78. end
  79. def unblock!(other_account)
  80. block = block_relationships.find_by(target_account: other_account)
  81. block&.destroy
  82. end
  83. def unmute!(other_account)
  84. mute = mute_relationships.find_by(target_account: other_account)
  85. mute&.destroy
  86. end
  87. def following?(other_account)
  88. following.include?(other_account)
  89. end
  90. def blocking?(other_account)
  91. blocking.include?(other_account)
  92. end
  93. def muting?(other_account)
  94. muting.include?(other_account)
  95. end
  96. def requested?(other_account)
  97. follow_requests.where(target_account: other_account).exists?
  98. end
  99. def local?
  100. domain.nil?
  101. end
  102. def acct
  103. local? ? username : "#{username}@#{domain}"
  104. end
  105. def local_username_and_domain
  106. "#{username}@#{Rails.configuration.x.local_domain}"
  107. end
  108. def to_webfinger_s
  109. "acct:#{local_username_and_domain}"
  110. end
  111. def subscribed?
  112. !subscription_expires_at.blank?
  113. end
  114. def followers_domains
  115. followers.reorder(nil).pluck('distinct accounts.domain')
  116. end
  117. def favourited?(status)
  118. status.proper.favourites.where(account: self).count.positive?
  119. end
  120. def reblogged?(status)
  121. status.proper.reblogs.where(account: self).count.positive?
  122. end
  123. def keypair
  124. private_key.nil? ? OpenSSL::PKey::RSA.new(public_key) : OpenSSL::PKey::RSA.new(private_key)
  125. end
  126. def subscription(webhook_url)
  127. OStatus2::Subscription.new(remote_url, secret: secret, lease_seconds: 86_400 * 30, webhook: webhook_url, hub: hub_url)
  128. end
  129. def save_with_optional_avatar!
  130. save!
  131. rescue ActiveRecord::RecordInvalid
  132. self.avatar = nil
  133. self.header = nil
  134. self[:avatar_remote_url] = ''
  135. self[:header_remote_url] = ''
  136. save!
  137. end
  138. def avatar_original_url
  139. avatar.url(:original)
  140. end
  141. def avatar_static_url
  142. avatar_content_type == 'image/gif' ? avatar.url(:static) : avatar_original_url
  143. end
  144. def header_original_url
  145. header.url(:original)
  146. end
  147. def header_static_url
  148. header_content_type == 'image/gif' ? header.url(:static) : header_original_url
  149. end
  150. def avatar_remote_url=(url)
  151. parsed_url = Addressable::URI.parse(url).normalize
  152. return if !%w(http https).include?(parsed_url.scheme) || parsed_url.host.empty? || self[:avatar_remote_url] == url
  153. self.avatar = URI.parse(parsed_url.to_s)
  154. self[:avatar_remote_url] = url
  155. rescue OpenURI::HTTPError => e
  156. Rails.logger.debug "Error fetching remote avatar: #{e}"
  157. end
  158. def header_remote_url=(url)
  159. parsed_url = Addressable::URI.parse(url).normalize
  160. return if !%w(http https).include?(parsed_url.scheme) || parsed_url.host.empty? || self[:header_remote_url] == url
  161. self.header = URI.parse(parsed_url.to_s)
  162. self[:header_remote_url] = url
  163. rescue OpenURI::HTTPError => e
  164. Rails.logger.debug "Error fetching remote header: #{e}"
  165. end
  166. def object_type
  167. :person
  168. end
  169. def to_param
  170. username
  171. end
  172. def excluded_from_timeline_account_ids
  173. Rails.cache.fetch("exclude_account_ids_for:#{id}") { blocking.pluck(:target_account_id) + blocked_by.pluck(:account_id) + muting.pluck(:target_account_id) }
  174. end
  175. class << self
  176. def find_local!(username)
  177. find_remote!(username, nil)
  178. end
  179. def find_remote!(username, domain)
  180. return if username.blank?
  181. where('lower(accounts.username) = ?', username.downcase).where(domain.nil? ? { domain: nil } : 'lower(accounts.domain) = ?', domain&.downcase).take!
  182. end
  183. def find_local(username)
  184. find_local!(username)
  185. rescue ActiveRecord::RecordNotFound
  186. nil
  187. end
  188. def find_remote(username, domain)
  189. find_remote!(username, domain)
  190. rescue ActiveRecord::RecordNotFound
  191. nil
  192. end
  193. def triadic_closures(account, limit = 5)
  194. sql = <<-SQL.squish
  195. WITH first_degree AS (
  196. SELECT target_account_id
  197. FROM follows
  198. WHERE account_id = :account_id
  199. )
  200. SELECT accounts.*
  201. FROM follows
  202. INNER JOIN accounts ON follows.target_account_id = accounts.id
  203. WHERE account_id IN (SELECT * FROM first_degree) AND target_account_id NOT IN (SELECT * FROM first_degree) AND target_account_id <> :account_id
  204. GROUP BY target_account_id, accounts.id
  205. ORDER BY count(account_id) DESC
  206. LIMIT :limit
  207. SQL
  208. find_by_sql(
  209. [sql, { account_id: account.id, limit: limit }]
  210. )
  211. end
  212. def search_for(terms, limit = 10)
  213. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  214. textsearch = '(setweight(to_tsvector(\'simple\', accounts.display_name), \'A\') || setweight(to_tsvector(\'simple\', accounts.username), \'B\') || setweight(to_tsvector(\'simple\', coalesce(accounts.domain, \'\')), \'C\'))'
  215. query = 'to_tsquery(\'simple\', \'\'\' \' || ' + terms + ' || \' \'\'\' || \':*\')'
  216. sql = <<-SQL.squish
  217. SELECT
  218. accounts.*,
  219. ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  220. FROM accounts
  221. WHERE #{query} @@ #{textsearch}
  222. ORDER BY rank DESC
  223. LIMIT ?
  224. SQL
  225. Account.find_by_sql([sql, limit])
  226. end
  227. def advanced_search_for(terms, account, limit = 10)
  228. terms = Arel.sql(connection.quote(terms.gsub(/['?\\:]/, ' ')))
  229. textsearch = '(setweight(to_tsvector(\'simple\', accounts.display_name), \'A\') || setweight(to_tsvector(\'simple\', accounts.username), \'B\') || setweight(to_tsvector(\'simple\', coalesce(accounts.domain, \'\')), \'C\'))'
  230. query = 'to_tsquery(\'simple\', \'\'\' \' || ' + terms + ' || \' \'\'\' || \':*\')'
  231. sql = <<-SQL.squish
  232. SELECT
  233. accounts.*,
  234. (count(f.id) + 1) * ts_rank_cd(#{textsearch}, #{query}, 32) AS rank
  235. FROM accounts
  236. 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 = ?)
  237. WHERE #{query} @@ #{textsearch}
  238. GROUP BY accounts.id
  239. ORDER BY rank DESC
  240. LIMIT ?
  241. SQL
  242. Account.find_by_sql([sql, account.id, account.id, limit])
  243. end
  244. def following_map(target_account_ids, account_id)
  245. follow_mapping(Follow.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  246. end
  247. def followed_by_map(target_account_ids, account_id)
  248. follow_mapping(Follow.where(account_id: target_account_ids, target_account_id: account_id), :account_id)
  249. end
  250. def blocking_map(target_account_ids, account_id)
  251. follow_mapping(Block.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  252. end
  253. def muting_map(target_account_ids, account_id)
  254. follow_mapping(Mute.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  255. end
  256. def requested_map(target_account_ids, account_id)
  257. follow_mapping(FollowRequest.where(target_account_id: target_account_ids, account_id: account_id), :target_account_id)
  258. end
  259. private
  260. def follow_mapping(query, field)
  261. query.pluck(field).each_with_object({}) { |id, mapping| mapping[id] = true }
  262. end
  263. def avatar_styles(file)
  264. styles = { original: '120x120#' }
  265. styles[:static] = { format: 'png' } if file.content_type == 'image/gif'
  266. styles
  267. end
  268. def header_styles(file)
  269. styles = { original: '700x335#' }
  270. styles[:static] = { format: 'png' } if file.content_type == 'image/gif'
  271. styles
  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