Guest User

Untitled

a guest
Jul 21st, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. require 'net/http'
  2. require 'json'
  3.  
  4. # need to accumulate twitter usernames to avoid hitting twitter api
  5. # rate limit. the users/lookup method will lookup up to 100 users at
  6. # a time.
  7. @twitter_username_sxsocial_id_map = {}
  8.  
  9. def get_user_id
  10. @username = @link.url.split('/').last
  11. @network = @link.url.match(/([\w]+).com/)[1]
  12. case @network
  13. when 'facebook' then get_facebook_id if @link.user.facebook_id.blank?
  14. when 'twitter' then push_twitter_username if @link.user.twitter_id.blank?
  15. when 'linkedin' then get_linkedin_id if @link.user.linkedin_id.blank?
  16. else
  17. @id = nil
  18. end
  19. if @id
  20. @link.user.save
  21. end
  22. end
  23.  
  24. def get_facebook_id
  25. response = Net::HTTP.get_response('graph.facebook.com', "/#{@username}")
  26. if response.code == '200'
  27. puts response.body
  28. unless response.body.match(/^false/) # some kind of error
  29. json = JSON.parse(response.body)
  30. @id = json['id']
  31. @link.user.facebook_id = @id
  32. end
  33. else
  34. @id = nil
  35. end
  36. end
  37.  
  38. def push_twitter_username
  39. @twitter_username_sxsocial_id_map[@username.downcase] = @link.user.id
  40. # can only do 100 at a time due to twitter api limitation
  41. if @twitter_username_sxsocial_id_map.size == 99
  42. pop_twitter_usernames
  43. @twitter_username_sxsocial_id_map = {}
  44. end
  45. @id = nil # so we don't try to save this user yet
  46. end
  47.  
  48. def pop_twitter_usernames
  49. puts "POPPING TWITTER USERNAMES"
  50. username_list = []
  51. @twitter_username_sxsocial_id_map.each_key do |username|
  52. username_list << username
  53. end
  54. twitter_users = Twitter.users(username_list.join(', '))
  55. twitter_users.each do |twitter_user|
  56. our_user_id = @twitter_username_sxsocial_id_map[twitter_user['screen_name'].downcase]
  57. unless our_user_id.blank?
  58. our_user = User.find(our_user_id)
  59. our_user.update_attribute :twitter_id, twitter_user['id']
  60. end
  61. end
  62. end
  63.  
  64. ### not implemented yet
  65. def get_linkedin_id
  66. @id = nil
  67. end
  68.  
  69. #links = Link.find(:all, :conditions => 'user_id = 444')
  70.  
  71. links = Link.find(:all,
  72. :conditions => "url ilike '%facebook.com%' or url ilike '%twitter.com%'"#,
  73. #:limit => 10
  74. )
  75.  
  76. links.each do |link|
  77. @link = link
  78. get_user_id
  79. end
  80.  
  81. # pop the remaining twitter usernames
  82. pop_twitter_usernames
Add Comment
Please, Sign In to add comment