Подтвердить что ты не робот

Проблемы с получением адресной книги для получения списка контактов Gmail, Yahoo, Hotmail, Twitter и Facebook в Ruby on Rails

При поиске в плагине Contacts во время поиска.

Но в соответствии с описанием, описанным в файле readme. Для подключения контактов требуется имя пользователя и пароль. Но это не очень хороший подход.

4b9b3361

Ответ 1

Плагин Mini FB для входа в Facebook. Это также позволяет мне получать контакты пользователей. Поэтому я могу использовать этот для Facebook. Koala - еще одно решение для поиска друзей facebook

ОБНОВЛЕНИЕ FACEBOOK

Здесь я получил решение для facebook, но я просто покажу, как пригласить друзей на facebook

    <div id="facebook_invites" class="conclusion" style="width: 750px; text-align: center">
      <a id="wall_post" href="#" style="font-size: 2em;">Post on your Wall</a><br/>
      <a id="invite_friends" href="#" style="font-size: 1.5em;">Invite your Friends</a>
      </div>
        <div id="fb-root"></div>


      <script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
        <script type="text/javascript">
          $('#wall_post').click(function() {
            FB.init({
              appId:'app_id', cookie:true,
              status:true, xfbml:true
            });

            FB.ui({ method: 'feed',
              link: 'http://localhost:3000/',
              picture: 'http://localhost:3000/',
              description: 'abc is cool.',
              name: 'abc.com'});
          });

          $('#invite_friends').click(function() {
            FB.init({
              appId:'app_id', cookie:true,
              status:true, xfbml:true
            });

            FB.ui({ method: 'apprequests',
              message: 'abc is cool.'});
          });
        </script>


Обновление Google

Из руководство для разработчиков Google, у нас есть раздел "Извлечение всех контактов", но между ними есть строка, написанная, например: -

Примечание. Получение других пользовательских контактов не поддерживается текущей версией API контактов.

   /*
    * Retrieve all contacts
    */

    // Create the contacts service object
    var contactsService =
       new google.gdata.contacts.ContactsService('GoogleInc-jsguide-1.0');

    // The feed URI that is used for retrieving contacts
    var feedUri = 'http://www.google.com/m8/feeds/contacts/default/full';
    var query = new google.gdata.contacts.ContactQuery(feedUri);

    // Set the maximum of the result set to be 50
    query.setMaxResults(50);

    // callback method to be invoked when getContactFeed() returns data
    var callback = function(result) {

     // An array of contact entries
     var entries = result.feed.entry;

     // Iterate through the array of contact entries
     for (var i = 0; i < entries.length; i++) {
       var contactEntry = entries[i];

       var emailAddresses = contactEntry.getEmailAddresses();

       // Iterate through the array of emails belonging to a single contact entry
       for (var j = 0; j < emailAddresses.length; j++) {
         var emailAddress = emailAddresses[j].getAddress();
         PRINT('email = ' + emailAddress);
       }    
     }
    }

    // Error handler
    var handleError = function(error) {
     PRINT(error);
    }

    // Submit the request using the contacts service object
    contactsService.getContactFeed(query, callback, handleError);

Другое решение для сторонних пользователей google: Решение для google:

Получите ваш client_id и client_secret из здесь. Это грубая script, которая отлично работает. Изменено в соответствии с вашими потребностями.

    require 'net/http'
    require 'net/https'
    require 'uri'
    require 'rexml/document'

    class ImportController < ApplicationController

      def authenticate
        @title = "Google Authetication"

        client_id = "xxxxxxxxxxxxxx.apps.googleusercontent.com"
        google_root_url = "https://accounts.google.com/o/oauth2/auth?state=profile&redirect_uri="+googleauth_url+"&response_type=code&client_id="+client_id.to_s+"&approval_prompt=force&scope=https://www.google.com/m8/feeds/"
        redirect_to google_root_url
      end

      def authorise
        begin
          @title = "Google Authetication"
          token = params[:code]
          client_id = "xxxxxxxxxxxxxx.apps.googleusercontent.com"
          client_secret = "xxxxxxxxxxxxxx"
          uri = URI('https://accounts.google.com/o/oauth2/token')
          http = Net::HTTP.new(uri.host, uri.port)
          http.use_ssl = true
          http.verify_mode = OpenSSL::SSL::VERIFY_NONE
          request = Net::HTTP::Post.new(uri.request_uri)

          request.set_form_data('code' => token, 'client_id' => client_id, 'client_secret' => client_secret, 'redirect_uri' => googleauth_url, 'grant_type' => 'authorization_code')
          request.content_type = 'application/x-www-form-urlencoded'
          response = http.request(request)
          response.code
          access_keys = ActiveSupport::JSON.decode(response.body)

          uri = URI.parse("https://www.google.com/m8/feeds/contacts/default/full?oauth_token="+access_keys['access_token'].to_s+"&max-results=50000&alt=json")

          http = Net::HTTP.new(uri.host, uri.port)
          http.use_ssl = true
          http.verify_mode = OpenSSL::SSL::VERIFY_NONE
          request = Net::HTTP::Get.new(uri.request_uri)
          response = http.request(request)
          contacts = ActiveSupport::JSON.decode(response.body)
          contacts['feed']['entry'].each_with_index do |contact,index|

             name = contact['title']['$t']
             contact['gd$email'].to_a.each do |email|
              email_address = email['address']
              Invite.create(:full_name => name, :email => email_address, :invite_source => "Gmail", :user_id => current_user.id)  # for testing i m pushing it into database..
            end

          end  
        rescue Exception => ex
           ex.message
        end
        redirect_to root_path , :notice => "Invite or follow your Google contacts."


      end

    end

Снимок экрана для настроек.

enter image description here

Ответ 2

Для Gmail или для вашей конкретной цели: Контакты Gmail.

Для контактов Yahoo, насколько мне известно, Contacts, похоже, используется. Если у кого-то есть лучшая альтернатива. Пожалуйста, упомяните.

Для Twitter я настоятельно рекомендую Twitter gem.

В Facebook вы уже собрали свой драгоценный камень в Facebook. Тем не менее, я лично использую FB Graph.

Edit:

Хмм, я попытался взглянуть на документ. Никаких примеров не упомянуто. Хотя он упоминает:

См. пример /authsub.rb для примера который использует GmailContacts

Этого нигде не найти. Возможно, может помочь быстрое письмо автору?

Похоже, что "Контактный камень" хорошо документирован онлайн. Если вы можете найти способ работать с вашими проектными требованиями. Затем вы можете использовать это как универсальное решение для других поставщиков электронной почты.

Альтернативно, другой способ для поиска контактов, я нашел этот, который может быть полезен.

Ответ 3

Для Gmail, а не для использования какого-либо драгоценного камня, вы должны использовать пример кода, это не стоит драгоценного камня.

См. мой пример кода здесь https://gist.github.com/742461

На самом деле здесь был пост в блоге - http://rtdptech.com/2010/12/importing-gmail-contacts-list-to-rails-application/, но, похоже, он сталкивается с проблемами перенаправления.

Ответ 4

Вам нужно будет отслеживать, какой пользователь пригласил, который через таблицу соединений. Здесь FB.ui JS w/callback, чтобы вы начали:

FB.ui({
    method: 'apprequests',
    title: t,
    message: m
},
function(response) {
  if (response) {
    $.ajax({
      type: 'POST',
      url: "/invitation_requests/create",
      data: { "requests[]" : response.request_ids },
      timeout: 12500,
      async : false, // This fixes an issue w/ IE
      complete: function() {
        $.cookie( "latest_request_ids", response.request_ids.length );
        window.location = "/users"
      }
    });
  }
});