Skip to content

Instantly share code, notes, and snippets.

@arunthampi
Created September 7, 2016 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arunthampi/99ef149bfca59a4eb1a78bfe7f94a10f to your computer and use it in GitHub Desktop.
Save arunthampi/99ef149bfca59a4eb1a78bfe7f94a10f to your computer and use it in GitHub Desktop.
class Team < ActiveRecord::Base
def import_users!
return if bot.blank?
slack_client = Slack.new(bot.token)
Team.with_advisory_lock("team-import-#{self.uid}") do
object_nesting_level = 0
current_user = {}
current_profile = {}
current_user_key = nil
current_profile_key = nil
_t = self
parser = JSON::Stream::Parser.new do
start_object { object_nesting_level += 1 }
end_object do
if object_nesting_level.eql? 2
_t.import_user_from_hash!(current_user)
current_user = {}
elsif object_nesting_level.eql? 3
current_user[current_user_key] = current_profile
current_profile = {}
end
object_nesting_level -= 1
end
key do |k|
if object_nesting_level.eql? 2
current_user_key = k
elsif object_nesting_level.eql? 3
current_profile_key = k
end
end
value do |v|
if object_nesting_level.eql? 2
current_user[current_user_key] = v
elsif object_nesting_level.eql? 3
current_profile[current_profile_key] = v
end
end
end
begin
slack_client.call('users.list', :get) do |chunk, remaining_bytes, total_bytes|
if chunk.present?
parser << chunk
else
puts "chunk is nil"
end
end
rescue JSON::Stream::ParserError
Rails.logger.error "[ImportUsersForTeamJob] JSON Parser Error Team ID: #{self.id}"
end
end
Rails.logger.warn "[ImportUsersForTeamJob] importing members: #{self.members.count} ID: #{self.id}"
end
def import_user_from_hash!(user)
new_record = false
u = nil
if(existing_membership = self.team_memberships.find_by_user_uid(user['id'])).blank?
if(email = user['profile']['email']).present?
u = User.find_by(email: email)
end
if u.blank?
u = User.new
new_record = true
end
else
u = existing_membership.user
end
# No need to update email cos Mixpanel has that email
# TODO: Maybe it might be better to just update Mixpanel as well at this time
u.nickname = user['name']
if u.email.blank?
u.email = user['profile']['email']
end
u.first_name = user['profile']['first_name']
u.last_name = user['profile']['last_name']
u.full_name = user['profile']['real_name']
u.profile.timezone = user['tz']
u.profile.timezone_description = user['tz_label']
u.profile.timezone_offset = user['tz_offset'].to_i
u.save!
membership_type = TeamMembership.membership_type_from_hash(user)
if existing_membership.present?
existing_membership.update_attribute(:membership_type, membership_type)
else
TeamMembership.create!(user: u, team: self, membership_type: membership_type, user_uid: user['id'])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment