Class: Person

Inherits:
ApplicationRecord show all
Includes:
Diaspora::Fields::Guid
Defined in:
app/models/person.rb

Overview

Copyright © 2010-2011, Diaspora Inc. This file is

licensed under the Affero General Public License version 3 or later.  See
the COPYRIGHT file.

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Diaspora::Fields::Guid

included, #set_guid

Constructor Details

#initialize(params = {}) ⇒ Person

Set a default of an empty profile when a new Person record is instantiated. Passing :profile => nil to Person.new will instantiate a person with no profile. Calling Person.new with a block:

Person.new do |p|
  p.profile = nil
end

will not work! The nil profile will be overriden with an empty one.


205
206
207
208
209
210
211
212
# File 'app/models/person.rb', line 205

def initialize(params={})
  params = {} if params.nil?

  profile_set = params.has_key?(:profile) || params.has_key?("profile")
  params[:profile_attributes] = params.delete(:profile) if params.has_key?(:profile) && params[:profile].is_a?(Hash)
  super
  self.profile ||= Profile.new unless profile_set
end

Class Method Details

.by_account_identifier(diaspora_id) ⇒ Object


346
347
348
# File 'app/models/person.rb', line 346

def self.(diaspora_id)
  find_by(diaspora_handle: diaspora_id.strip.downcase)
end

.community_spotlightObject


194
195
196
# File 'app/models/person.rb', line 194

def self.community_spotlight
  Person.joins(:roles).where(:roles => {:name => 'spotlight'})
end

.find_from_guid_or_username(params) ⇒ Object

Raises:

  • (ActiveRecord::RecordNotFound)

214
215
216
217
218
219
220
221
222
223
224
# File 'app/models/person.rb', line 214

def self.find_from_guid_or_username(params)
  p = if params[:id].present?
        Person.find_by(guid: params[:id])
      elsif params[:username].present? && u = User.find_by_username(params[:username])
        u.person
      else
        nil
      end
  raise ActiveRecord::RecordNotFound unless p.present?
  p
end

.find_or_fetch_by_identifier(diaspora_id) ⇒ Object

discovery (webfinger)


334
335
336
337
338
339
340
341
342
343
344
# File 'app/models/person.rb', line 334

def self.find_or_fetch_by_identifier(diaspora_id)
  # exiting person?
  person = (diaspora_id)
  return person if person.present? && person.profile.present?

  # create or update person from webfinger
  logger.info "webfingering #{diaspora_id}, it is not known or needs updating"
  DiasporaFederation::Discovery::Discovery.new(diaspora_id).fetch_and_save

  (diaspora_id)
end

.name_from_attrs(first_name, last_name, diaspora_handle) ⇒ Object


270
271
272
# File 'app/models/person.rb', line 270

def self.name_from_attrs(first_name, last_name, diaspora_handle)
  first_name.blank? && last_name.blank? ? diaspora_handle : "#{first_name.to_s.strip} #{last_name.to_s.strip}".strip
end

.search(search_str, user, only_contacts: false, mutual: false) ⇒ Object


247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'app/models/person.rb', line 247

def self.search(search_str, user, only_contacts: false, mutual: false)
  query = find_by_substring(search_str)
  return query if query.is_a?(ActiveRecord::NullRelation)

  query = if only_contacts
            query.contacts_of(user)
          else
            query.searchable(user)
          end

  query = query.where(contacts: {sharing: true, receiving: true}) if mutual

  query.where(closed_account: false)
       .order([Arel.sql("contacts.user_id IS NULL"), "profiles.last_name ASC", "profiles.first_name ASC"])
end

.search_query_string(query) ⇒ Object


230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'app/models/person.rb', line 230

def self.search_query_string(query)
  query = query.downcase
  like_operator = AppConfig.postgres? ? "ILIKE" : "LIKE"

  where_clause = <<-SQL
    profiles.full_name #{like_operator} ? OR
    people.diaspora_handle #{like_operator} ?
  SQL

  q_tokens = []
  q_tokens[0] = query.to_s.strip.gsub(/(\s|$|^)/) { "%#{$1}" }
  q_tokens[1] = q_tokens[0].gsub(/\s/,'').gsub('%','')
  q_tokens[1] << "%"

  [where_clause, q_tokens]
end

Instance Method Details

#allowed_to_be_mentioned_in_a_comment_toPerson::ActiveRecord_Relation

Selects people who can be mentioned in a comment to a specific post. For public posts all people are allowed, so no additional constraints are added. For private posts selection is limited to people who have posted comments or likes for this post.

Parameters:

  • the (Post)

    post for which we query mentionable in comments people

Returns:

  • (Person::ActiveRecord_Relation)

156
157
158
159
160
161
162
163
164
# File 'app/models/person.rb', line 156

scope :allowed_to_be_mentioned_in_a_comment_to, ->(post) {
  allowed = if post.public?
              all
            else
              left_join_visible_post_interactions_on_authorship(post.id)
                .where("comments.id IS NOT NULL OR likes.id IS NOT NULL OR people.id = #{post.author_id}")
            end
  allowed.distinct
}

#as_json(opts = {}) ⇒ Object


361
362
363
364
365
366
367
368
369
370
371
372
373
# File 'app/models/person.rb', line 361

def as_json( opts = {} )
  opts ||= {}
  json = {
    id:     id,
    guid:   guid,
    name:   name,
    avatar: profile.image_url(size: :thumb_small),
    handle: diaspora_handle,
    url:    Rails.application.routes.url_helpers.person_path(self)
  }
  json.merge!(:tags => self.profile.tags.map{|t| "##{t.name}"}) if opts[:includes] == "tags"
  json
end

#atom_urlObject


305
306
307
# File 'app/models/person.rb', line 305

def atom_url
  url_to "/public/#{username}.atom"
end

#authorObject


289
290
291
# File 'app/models/person.rb', line 289

def author
  self
end

#clear_profile!Object


380
381
382
383
# File 'app/models/person.rb', line 380

def clear_profile!
  self.profile.tombstone!
  self
end

#downcase_diaspora_handleObject


34
35
36
# File 'app/models/person.rb', line 34

def downcase_diaspora_handle
  diaspora_handle.downcase! unless diaspora_handle.blank?
end

#exported_keyObject


329
330
331
# File 'app/models/person.rb', line 329

def exported_key
  serialized_public_key
end

#find_by_substringPerson::ActiveRecord_Relation

This scope selects people where the full name contains the search_str or diaspora ID starts with the search_str. However, if the search_str doesn't have more than 1 non-whitespace character, it'll return an empty set.

Parameters:

  • search (String)

    substring

Returns:

  • (Person::ActiveRecord_Relation)

124
125
126
127
128
129
130
131
132
# File 'app/models/person.rb', line 124

scope :find_by_substring, ->(search_str) {
  search_str = search_str.strip
  if search_str.blank? || search_str.size < 2
    none
  else
    sql, tokens = search_query_string(search_str)
    joins(:profile).where(sql, *tokens)
  end
}

#first_nameObject


274
275
276
277
278
279
280
281
282
283
# File 'app/models/person.rb', line 274

def first_name
  @first_name ||= if profile.nil? || profile.first_name.nil? || profile.first_name.blank?
              self.diaspora_handle.split('@').first
            else
              names = profile.first_name.to_s.split(/\s/)
              str = names[0...-1].join(' ')
              str = names[0] if str.blank?
              str
            end
end

#has_photos?Boolean

Returns:

  • (Boolean)

357
358
359
# File 'app/models/person.rb', line 357

def has_photos?
  self.photos.exists?
end

#left_join_visible_post_interactions_on_authorshipPerson::ActiveRecord_Relation

Left joins likes and comments to a specific post where people are authors of these comments and likes

Parameters:

  • post (String, Integer)

    ID for which comments and likes should be joined

Returns:

  • (Person::ActiveRecord_Relation)

137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'app/models/person.rb', line 137

scope :left_join_visible_post_interactions_on_authorship, ->(post_id) {
  comments_sql = <<-SQL
    LEFT OUTER JOIN comments ON
    comments.author_id = people.id AND comments.commentable_type = 'Post' AND comments.commentable_id = #{post_id}
  SQL

  likes_sql = <<-SQL
    LEFT OUTER JOIN likes ON
    likes.author_id = people.id AND likes.target_type = 'Post' AND likes.target_id = #{post_id}
  SQL

  joins(comments_sql).joins(likes_sql)
}

#local?Boolean

Returns:

  • (Boolean)

353
354
355
# File 'app/models/person.rb', line 353

def local?
  !remote?
end

#lock_access!Object


375
376
377
378
# File 'app/models/person.rb', line 375

def lock_access!
  self. = true
  self.save
end

#name(opts = {}) ⇒ Object


263
264
265
266
267
268
# File 'app/models/person.rb', line 263

def name(opts = {})
  if self.profile.nil?
    fix_profile
  end
  @name ||= Person.name_from_attrs(self.profile.first_name, self.profile.last_name, self.diaspora_handle)
end

#owns?(obj) ⇒ Boolean

Returns:

  • (Boolean)

293
294
295
# File 'app/models/person.rb', line 293

def owns?(obj)
  self.id == obj.author_id
end

#profile_urlObject


301
302
303
# File 'app/models/person.rb', line 301

def profile_url
  url_to "/u/#{username}"
end

#public_keyObject


323
324
325
326
327
# File 'app/models/person.rb', line 323

def public_key
  OpenSSL::PKey::RSA.new(serialized_public_key)
rescue OpenSSL::PKey::RSAError
  nil
end

#public_key_hashObject


319
320
321
# File 'app/models/person.rb', line 319

def public_key_hash
  Base64.encode64(OpenSSL::Digest::SHA256.new(serialized_public_key).to_s)
end

#receive_urlObject


309
310
311
# File 'app/models/person.rb', line 309

def receive_url
  url_to "/receive/users/#{guid}"
end

#remote?Boolean

Returns:

  • (Boolean)

350
351
352
# File 'app/models/person.rb', line 350

def remote?
  owner_id.nil?
end

#sort_for_mention_suggestionPerson::ActiveRecord_Relation

This scope adds sorting of people in the order, appropriate for suggesting to a user (current user) who has requested a list of the people mentionable in a comment for a specific post. Sorts people in the following priority: post author > commenters > likers > contacts > non-contacts

Parameters:

  • post (Post)

    for which the mentionable in comment people list is requested

  • user (User)

    who requests the people list

Returns:

  • (Person::ActiveRecord_Relation)

172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'app/models/person.rb', line 172

scope :sort_for_mention_suggestion, ->(post, user) {
  left_join_visible_post_interactions_on_authorship(post.id)
    .joins("LEFT OUTER JOIN contacts ON people.id = contacts.person_id AND contacts.user_id = #{user.id}")
    .joins(:profile)
    .select(<<-SQL
      people.id = #{unscoped { post.author_id }} AS is_author,
      comments.id IS NOT NULL AS is_commenter,
      likes.id IS NOT NULL AS is_liker,
      contacts.id IS NOT NULL AS is_contact
      SQL
           )
    .order(Arel.sql(<<-SQL
      is_author DESC,
      is_commenter DESC,
      is_liker DESC,
      is_contact DESC,
      profiles.full_name,
      people.diaspora_handle
      SQL
                   ))
}

#to_paramObject


226
227
228
# File 'app/models/person.rb', line 226

def to_param
  self.guid
end

#urlObject


297
298
299
# File 'app/models/person.rb', line 297

def url
  url_to "/"
end

#url_to(path) ⇒ String

Parameters:

Returns:


315
316
317
# File 'app/models/person.rb', line 315

def url_to(path)
  local? ? AppConfig.url_to(path) : pod.url_to(path)
end

#usernameObject


285
286
287
# File 'app/models/person.rb', line 285

def username
  @username ||= owner ? owner.username : diaspora_handle.split("@")[0]
end