twitter-5.16.0/0000755000004100000410000000000012666331030013335 5ustar www-datawww-datatwitter-5.16.0/twitter.gemspec0000644000004100000410000000232112666331030016402 0ustar www-datawww-datalib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'twitter/version' Gem::Specification.new do |spec| spec.add_dependency 'addressable', '~> 2.3' spec.add_dependency 'buftok', '~> 0.2.0' spec.add_dependency 'equalizer', '0.0.10' spec.add_dependency 'faraday', '~> 0.9.0' spec.add_dependency 'http', '~> 1.0' spec.add_dependency 'http_parser.rb', '~> 0.6.0' spec.add_dependency 'json', '~> 1.8' spec.add_dependency 'memoizable', '~> 0.4.0' spec.add_dependency 'naught', '~> 1.0' spec.add_dependency 'simple_oauth', '~> 0.3.0' spec.add_development_dependency 'bundler', '~> 1.0' spec.authors = ['Erik Michaels-Ober', 'John Nunemaker', 'Wynn Netherland', 'Steve Richert', 'Steve Agalloco'] spec.description = 'A Ruby interface to the Twitter API.' spec.email = %w(sferik@gmail.com) spec.files = %w(.yardopts CHANGELOG.md CONTRIBUTING.md LICENSE.md README.md twitter.gemspec) + Dir['lib/**/*.rb'] spec.homepage = 'http://sferik.github.com/twitter/' spec.licenses = %w(MIT) spec.name = 'twitter' spec.require_paths = %w(lib) spec.required_rubygems_version = '>= 1.3.5' spec.summary = spec.description spec.version = Twitter::Version end twitter-5.16.0/LICENSE.md0000644000004100000410000000215312666331030014742 0ustar www-datawww-dataCopyright (c) 2006-2016 Erik Michaels-Ober, John Nunemaker, Wynn Netherland, Steve Richert, Steve Agalloco Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. twitter-5.16.0/lib/0000755000004100000410000000000012666331030014103 5ustar www-datawww-datatwitter-5.16.0/lib/twitter/0000755000004100000410000000000012666331030015605 5ustar www-datawww-datatwitter-5.16.0/lib/twitter/headers.rb0000644000004100000410000000347612666331030017557 0ustar www-datawww-datarequire 'addressable/uri' require 'base64' require 'simple_oauth' module Twitter class Headers def initialize(client, request_method, url, options = {}) @client = client @request_method = request_method.to_sym @uri = Addressable::URI.parse(url) @options = options @signature_options = @request_method == :post && @options.values.any? { |value| value.respond_to?(:to_io) } ? {} : @options end def oauth_auth_header SimpleOAuth::Header.new(@request_method, @uri, @signature_options, @client.credentials) end def request_headers bearer_token_request = @options.delete(:bearer_token_request) headers = {} if bearer_token_request headers[:accept] = '*/*' headers[:authorization] = bearer_token_credentials_auth_header headers[:content_type] = 'application/x-www-form-urlencoded; charset=UTF-8' else headers[:authorization] = auth_header end headers end private def auth_header if @client.user_token? oauth_auth_header.to_s else @client.bearer_token = @client.token unless @client.bearer_token? bearer_auth_header end end def bearer_auth_header bearer_token = @client.bearer_token token = bearer_token.is_a?(Twitter::Token) && bearer_token.bearer? ? bearer_token.access_token : bearer_token "Bearer #{token}" end # Generates authentication header for a bearer token request # # @return [String] def bearer_token_credentials_auth_header basic_auth_token = strict_encode64("#{@client.consumer_key}:#{@client.consumer_secret}") "Basic #{basic_auth_token}" end # Base64.strict_encode64 is not available on Ruby 1.8.7 def strict_encode64(str) Base64.encode64(str).delete("\n") end end end twitter-5.16.0/lib/twitter/variant.rb0000644000004100000410000000032112666331030017572 0ustar www-datawww-datarequire 'twitter/base' module Twitter class Variant < Twitter::Base # @return [Integer] attr_reader :bitrate # @return [String] attr_reader :content_type uri_attr_reader :uri end end twitter-5.16.0/lib/twitter/suggestion.rb0000644000004100000410000000067112666331030020325 0ustar www-datawww-datarequire 'equalizer' require 'memoizable' require 'twitter/base' module Twitter class Suggestion < Twitter::Base include Equalizer.new(:slug) include Memoizable # @return [Integer] attr_reader :size # @return [String] attr_reader :name, :slug # @return [Array] def users @attrs.fetch(:users, []).collect do |user| User.new(user) end end memoize :users end end twitter-5.16.0/lib/twitter/entity.rb0000644000004100000410000000021012666331030017437 0ustar www-datawww-datarequire 'twitter/base' module Twitter class Entity < Twitter::Base # @return [Array] attr_reader :indices end end twitter-5.16.0/lib/twitter/utils.rb0000644000004100000410000000261112666331030017272 0ustar www-datawww-datamodule Twitter module Utils class << self def included(base) base.extend(ClassMethods) end end module ClassMethods def deprecate_alias(new_name, old_name, &block) define_method(new_name) do |*args| warn "#{Kernel.caller.first}: [DEPRECATION] ##{new_name} is deprecated. Use ##{old_name} instead." send(old_name, *args, &block) end end end # Returns a new array with the concatenated results of running block once for every element in enumerable. # If no block is given, an enumerator is returned instead. # # @param enumerable [Enumerable] # @return [Array, Enumerator] def flat_pmap(enumerable) return to_enum(:flat_pmap, enumerable) unless block_given? pmap(enumerable, &Proc.new).flatten(1) end module_function :flat_pmap # Returns a new array with the results of running block once for every element in enumerable. # If no block is given, an enumerator is returned instead. # # @param enumerable [Enumerable] # @return [Array, Enumerator] def pmap(enumerable) return to_enum(:pmap, enumerable) unless block_given? if enumerable.count == 1 enumerable.collect { |object| yield(object) } else enumerable.collect { |object| Thread.new { yield(object) } }.collect(&:value) end end module_function :pmap end end twitter-5.16.0/lib/twitter/configuration.rb0000644000004100000410000000134712666331030021006 0ustar www-datawww-datarequire 'memoizable' require 'twitter/base' module Twitter class Configuration < Twitter::Base include Memoizable # @return [Array] attr_reader :non_username_paths # @return [Integer] attr_reader :characters_reserved_per_media, :max_media_per_upload, :photo_size_limit, :short_url_length, :short_url_length_https alias short_uri_length short_url_length alias short_uri_length_https short_url_length_https # Returns an array of photo sizes # # @return [Array] def photo_sizes @attrs.fetch(:photo_sizes, []).inject({}) do |object, (key, value)| object[key] = Size.new(value) object end end memoize :photo_sizes end end twitter-5.16.0/lib/twitter/profile.rb0000644000004100000410000000663012666331030017577 0ustar www-datawww-datarequire 'addressable/uri' require 'memoizable' module Twitter module Profile PROFILE_IMAGE_SUFFIX_REGEX = /_normal(\.gif|\.jpe?g|\.png)$/i PREDICATE_URI_METHOD_REGEX = /_uri\?$/ include Memoizable class << self private def alias_predicate_uri_methods(method) %w(_url? _uri_https? _url_https?).each do |replacement| alias_method_sub(method, PREDICATE_URI_METHOD_REGEX, replacement) end end def alias_method_sub(method, pattern, replacement) alias_method(method.to_s.sub(pattern, replacement).to_sym, method) end end # Return the URL to the user's profile banner image # # @param size [String, Symbol] The size of the image. Must be one of: 'mobile', 'mobile_retina', 'web', 'web_retina', 'ipad', or 'ipad_retina' # @return [Addressable::URI] def profile_banner_uri(size = :web) parse_uri(insecure_uri([@attrs[:profile_banner_url], size].join('/'))) unless @attrs[:profile_banner_url].nil? end alias profile_banner_url profile_banner_uri # Return the secure URL to the user's profile banner image # # @param size [String, Symbol] The size of the image. Must be one of: 'mobile', 'mobile_retina', 'web', 'web_retina', 'ipad', or 'ipad_retina' # @return [Addressable::URI] def profile_banner_uri_https(size = :web) parse_uri([@attrs[:profile_banner_url], size].join('/')) unless @attrs[:profile_banner_url].nil? end alias profile_banner_url_https profile_banner_uri_https # @return [Boolean] def profile_banner_uri? !!@attrs[:profile_banner_url] end memoize :profile_banner_uri? alias_predicate_uri_methods :profile_banner_uri? # Return the URL to the user's profile image # # @param size [String, Symbol] The size of the image. Must be one of: 'mini', 'normal', 'bigger' or 'original' # @return [Addressable::URI] def profile_image_uri(size = :normal) parse_uri(insecure_uri(profile_image_uri_https(size))) unless @attrs[:profile_image_url_https].nil? end alias profile_image_url profile_image_uri # Return the secure URL to the user's profile image # # @param size [String, Symbol] The size of the image. Must be one of: 'mini', 'normal', 'bigger' or 'original' # @return [Addressable::URI] def profile_image_uri_https(size = :normal) # The profile image URL comes in looking like like this: # https://a0.twimg.com/profile_images/1759857427/image1326743606_normal.png # It can be converted to any of the following sizes: # https://a0.twimg.com/profile_images/1759857427/image1326743606.png # https://a0.twimg.com/profile_images/1759857427/image1326743606_mini.png # https://a0.twimg.com/profile_images/1759857427/image1326743606_bigger.png parse_uri(@attrs[:profile_image_url_https].sub(PROFILE_IMAGE_SUFFIX_REGEX, profile_image_suffix(size))) unless @attrs[:profile_image_url_https].nil? end alias profile_image_url_https profile_image_uri_https # @return [Boolean] def profile_image_uri? !!@attrs[:profile_image_url_https] end memoize :profile_image_uri? alias_predicate_uri_methods :profile_image_uri? private def parse_uri(uri) Addressable::URI.parse(uri) end def insecure_uri(uri) uri.to_s.sub(/^https/i, 'http') end def profile_image_suffix(size) :original == size.to_sym ? '\\1' : "_#{size}\\1" end end end twitter-5.16.0/lib/twitter/entity/0000755000004100000410000000000012666331030017121 5ustar www-datawww-datatwitter-5.16.0/lib/twitter/entity/user_mention.rb0000644000004100000410000000034112666331030022153 0ustar www-datawww-datarequire 'twitter/entity' module Twitter class Entity class UserMention < Twitter::Entity # @return [Integer] attr_reader :id # @return [String] attr_reader :name, :screen_name end end end twitter-5.16.0/lib/twitter/entity/uri.rb0000644000004100000410000000033512666331030020246 0ustar www-datawww-datarequire 'twitter/entity' module Twitter class Entity class URI < Twitter::Entity display_uri_attr_reader uri_attr_reader :expanded_uri, :uri end URL = URI Uri = URI Url = URI end end twitter-5.16.0/lib/twitter/entity/hashtag.rb0000644000004100000410000000023712666331030021067 0ustar www-datawww-datarequire 'twitter/entity' module Twitter class Entity class Hashtag < Twitter::Entity # @return [String] attr_reader :text end end end twitter-5.16.0/lib/twitter/entity/symbol.rb0000644000004100000410000000023612666331030020754 0ustar www-datawww-datarequire 'twitter/entity' module Twitter class Entity class Symbol < Twitter::Entity # @return [String] attr_reader :text end end end twitter-5.16.0/lib/twitter/streaming/0000755000004100000410000000000012666331030017576 5ustar www-datawww-datatwitter-5.16.0/lib/twitter/streaming/message_parser.rb0000644000004100000410000000150312666331030023122 0ustar www-datawww-datarequire 'twitter/direct_message' require 'twitter/streaming/deleted_tweet' require 'twitter/streaming/event' require 'twitter/streaming/friend_list' require 'twitter/streaming/stall_warning' require 'twitter/tweet' module Twitter module Streaming class MessageParser def self.parse(data) # rubocop:disable CyclomaticComplexity, PerceivedComplexity if data[:id] Tweet.new(data) elsif data[:event] Event.new(data) elsif data[:direct_message] DirectMessage.new(data[:direct_message]) elsif data[:friends] FriendList.new(data[:friends]) elsif data[:delete] && data[:delete][:status] DeletedTweet.new(data[:delete][:status]) elsif data[:warning] StallWarning.new(data[:warning]) end end end end end twitter-5.16.0/lib/twitter/streaming/connection.rb0000644000004100000410000000153212666331030022263 0ustar www-datawww-datarequire 'http/parser' require 'openssl' require 'resolv' module Twitter module Streaming class Connection def initialize(opts = {}) @tcp_socket_class = opts.fetch(:tcp_socket_class) { TCPSocket } @ssl_socket_class = opts.fetch(:ssl_socket_class) { OpenSSL::SSL::SSLSocket } end attr_reader :tcp_socket_class, :ssl_socket_class def stream(request, response) client_context = OpenSSL::SSL::SSLContext.new client = @tcp_socket_class.new(Resolv.getaddress(request.socket_host), request.socket_port) ssl_client = @ssl_socket_class.new(client, client_context) ssl_client.connect request.stream(ssl_client) while body = ssl_client.readpartial(1024) # rubocop:disable AssignmentInCondition response << body end end end end end twitter-5.16.0/lib/twitter/streaming/response.rb0000644000004100000410000000133612666331030021764 0ustar www-datawww-datarequire 'buftok' module Twitter module Streaming class Response # Initializes a new Response object # # @return [Twitter::Streaming::Response] def initialize(&block) @block = block @parser = Http::Parser.new(self) @tokenizer = BufferedTokenizer.new("\r\n") end def <<(data) @parser << data end def on_headers_complete(_headers) error = Twitter::Error.errors[@parser.status_code] fail error.new if error end def on_body(data) @tokenizer.extract(data).each do |line| next if line.empty? @block.call(JSON.parse(line, :symbolize_names => true)) end end end end end twitter-5.16.0/lib/twitter/streaming/stall_warning.rb0000644000004100000410000000021412666331030022764 0ustar www-datawww-datamodule Twitter module Streaming class StallWarning < Twitter::Base attr_reader :code, :message, :percent_full end end end twitter-5.16.0/lib/twitter/streaming/client.rb0000644000004100000410000001667212666331030021415 0ustar www-datawww-datarequire 'http/request' require 'twitter/arguments' require 'twitter/client' require 'twitter/headers' require 'twitter/streaming/connection' require 'twitter/streaming/response' require 'twitter/streaming/message_parser' module Twitter module Streaming class Client < Twitter::Client attr_writer :connection attr_accessor :tcp_socket_class, :ssl_socket_class # Initializes a new Client object # # @param options [Hash] A customizable set of options. # @option options [String] :tcp_socket_class A class that Connection will use to create a new TCP socket. # @option options [String] :ssl_socket_class A class that Connection will use to create a new SSL socket. # @return [Twitter::Streaming::Client] def initialize(options = {}) super @connection = Streaming::Connection.new(options) end # Returns public statuses that match one or more filter predicates # # @see https://dev.twitter.com/streaming/reference/post/statuses/filter # @see https://dev.twitter.com/streaming/overview/request-parameters # @note At least one predicate parameter (follow, locations, or track) must be specified. # @param options [Hash] A customizable set of options. # @option options [String] :follow A comma separated list of user IDs, indicating the users to return statuses for in the stream. # @option options [String] :track Includes additional Tweets matching the specified keywords. Phrases of keywords are specified by a comma-separated list. # @option options [String] :locations Includes additional Tweets falling within the specified bounding boxes. # @yield [Twitter::Tweet, Twitter::Streaming::Event, Twitter::DirectMessage, Twitter::Streaming::FriendList, Twitter::Streaming::DeletedTweet, Twitter::Streaming::StallWarning] A stream of Twitter objects. def filter(options = {}, &block) request(:post, 'https://stream.twitter.com:443/1.1/statuses/filter.json', options, &block) end # Returns all public statuses # # @see https://dev.twitter.com/streaming/reference/get/statuses/firehose # @see https://dev.twitter.com/streaming/overview/request-parameters # @note This endpoint requires special permission to access. # @param options [Hash] A customizable set of options. # @option options [Integer] :count The number of messages to backfill. # @yield [Twitter::Tweet, Twitter::Streaming::Event, Twitter::DirectMessage, Twitter::Streaming::FriendList, Twitter::Streaming::DeletedTweet, Twitter::Streaming::StallWarning] A stream of Twitter objects. def firehose(options = {}, &block) request(:get, 'https://stream.twitter.com:443/1.1/statuses/firehose.json', options, &block) end # Returns a small random sample of all public statuses # # @see https://dev.twitter.com/streaming/reference/get/statuses/sample # @see https://dev.twitter.com/streaming/overview/request-parameters # @yield [Twitter::Tweet, Twitter::Streaming::Event, Twitter::DirectMessage, Twitter::Streaming::FriendList, Twitter::Streaming::DeletedTweet, Twitter::Streaming::StallWarning] A stream of Twitter objects. def sample(options = {}, &block) request(:get, 'https://stream.twitter.com:443/1.1/statuses/sample.json', options, &block) end # Streams messages for a set of users # # @see https://dev.twitter.com/streaming/reference/get/site # @see https://dev.twitter.com/streaming/sitestreams # @see https://dev.twitter.com/streaming/overview/request-parameters # @note Site Streams is currently in a limited beta. Access is restricted to whitelisted accounts. # @overload site(*follow, options = {}, &block) # @param follow [Enumerable] A list of user IDs, indicating the users to return statuses for in the stream. # @param options [Hash] A customizable set of options. # @option options [String] :with Specifies whether to return information for just the users specified in the follow parameter, or include messages from accounts they follow. # @option options [String] :replies Specifies whether stall warnings should be delivered. # @yield [Twitter::Tweet, Twitter::Streaming::Event, Twitter::DirectMessage, Twitter::Streaming::FriendList, Twitter::Streaming::DeletedTweet, Twitter::Streaming::StallWarning] A stream of Twitter objects. def site(*args, &block) arguments = Arguments.new(args) user_ids = collect_user_ids(arguments) request(:get, 'https://sitestream.twitter.com:443/1.1/site.json', arguments.options.merge(:follow => user_ids.join(',')), &block) end # Streams messages for a single user # # @see https://dev.twitter.com/streaming/reference/get/user # @see https://dev.twitter.com/streaming/userstreams # @see https://dev.twitter.com/streaming/overview/request-parameters # @param options [Hash] A customizable set of options. # @option options [String] :with Specifies whether to return information for just the users specified in the follow parameter, or include messages from accounts they follow. # @option options [String] :replies Specifies whether to return additional @replies. # @option options [String] :stall_warnings Specifies whether stall warnings should be delivered. # @option options [String] :track Includes additional Tweets matching the specified keywords. Phrases of keywords are specified by a comma-separated list. # @option options [String] :locations Includes additional Tweets falling within the specified bounding boxes. # @yield [Twitter::Tweet, Twitter::Streaming::Event, Twitter::DirectMessage, Twitter::Streaming::FriendList, Twitter::Streaming::DeletedTweet, Twitter::Streaming::StallWarning] A stream of Twitter objects. def user(options = {}, &block) request(:get, 'https://userstream.twitter.com:443/1.1/user.json', options, &block) end # Set a Proc to be run when connection established. def before_request(&block) if block_given? @before_request = block self elsif instance_variable_defined?(:@before_request) @before_request else proc {} end end private def request(method, uri, params) before_request.call authorization = Twitter::Headers.new(self, method, uri, params).oauth_auth_header.to_s headers = default_headers.merge(:authorization => authorization) request = HTTP::Request.new(:verb => method, :uri => uri + '?' + to_url_params(params), :headers => headers) response = Streaming::Response.new do |data| if item = Streaming::MessageParser.parse(data) # rubocop:disable AssignmentInCondition yield(item) end end @connection.stream(request, response) end def to_url_params(params) params.collect do |param, value| [param, URI.encode(value)].join('=') end.sort.join('&') end def default_headers @default_headers ||= { :accept => '*/*', :user_agent => user_agent, } end def collect_user_ids(users) user_ids = [] users.flatten.each do |user| case user when Integer user_ids << user when Twitter::User user_ids << user.id end end user_ids end end end end twitter-5.16.0/lib/twitter/streaming/friend_list.rb0000644000004100000410000000012112666331030022417 0ustar www-datawww-datamodule Twitter module Streaming class FriendList < Array end end end twitter-5.16.0/lib/twitter/streaming/event.rb0000644000004100000410000000173412666331030021251 0ustar www-datawww-datamodule Twitter module Streaming class Event LIST_EVENTS = [ :list_created, :list_destroyed, :list_updated, :list_member_added, :list_member_added, :list_member_removed, :list_user_subscribed, :list_user_subscribed, :list_user_unsubscribed, :list_user_unsubscribed ].freeze TWEET_EVENTS = [ :favorite, :unfavorite ].freeze attr_reader :name, :source, :target, :target_object # @param data [Hash] def initialize(data) @name = data[:event].to_sym @source = Twitter::User.new(data[:source]) @target = Twitter::User.new(data[:target]) @target_object = target_object_factory(@name, data[:target_object]) end private def target_object_factory(event_name, data) if LIST_EVENTS.include?(event_name) Twitter::List.new(data) elsif TWEET_EVENTS.include?(event_name) Twitter::Tweet.new(data) end end end end end twitter-5.16.0/lib/twitter/streaming/deleted_tweet.rb0000644000004100000410000000026512666331030022744 0ustar www-datawww-datamodule Twitter module Streaming class DeletedTweet < Twitter::Identity # @return [Integer] attr_reader :user_id end DeletedStatus = DeletedTweet end end twitter-5.16.0/lib/twitter/rest/0000755000004100000410000000000012666331030016562 5ustar www-datawww-datatwitter-5.16.0/lib/twitter/rest/media.rb0000644000004100000410000000240112666331030020163 0ustar www-datawww-datarequire 'twitter/error' require 'twitter/headers' require 'twitter/rest/utils' module Twitter module REST module Media # Uploads media to attach to a tweet # # @see https://dev.twitter.com/rest/public/uploading-media-multiple-photos # @rate_limited No # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @raise [Twitter::Error::UnacceptableIO] Error when the IO object for the media argument does not have a to_io method. # @return [Integer] The uploaded media ID. # @param media [File, Hash] A File object with your picture (PNG, JPEG or GIF) # @param options [Hash] A customizable set of options. def upload(media, options = {}) fail(Twitter::Error::UnacceptableIO.new) unless media.respond_to?(:to_io) base_url = 'https://upload.twitter.com' path = '/1.1/media/upload.json' conn = connection.dup conn.url_prefix = base_url headers = Twitter::Headers.new(self, :post, base_url + path, options).request_headers options[:media] = media conn.post(path, options) { |request| request.headers.update(headers) }.env.body[:media_id] end end end end twitter-5.16.0/lib/twitter/rest/timelines.rb0000644000004100000410000003305512666331030021106 0ustar www-datawww-datarequire 'twitter/rest/utils' require 'twitter/tweet' require 'twitter/user' module Twitter module REST module Timelines include Twitter::REST::Utils DEFAULT_TWEETS_PER_REQUEST = 20 MAX_TWEETS_PER_REQUEST = 200 # Returns the 20 most recent mentions (statuses containing @username) for the authenticating user # # @see https://dev.twitter.com/rest/reference/get/statuses/mentions_timeline # @note This method can only return up to 800 Tweets. # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Array] # @param options [Hash] A customizable set of options. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. def mentions_timeline(options = {}) perform_get_with_objects('/1.1/statuses/mentions_timeline.json', options, Twitter::Tweet) end alias mentions mentions_timeline # Returns the 20 most recent Tweets posted by the specified user # # @see https://dev.twitter.com/rest/reference/get/statuses/user_timeline # @note This method can only return up to 3,200 Tweets. # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Array] # @overload user_timeline(user, options = {}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, URI, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @option options [Boolean, String, Integer] :exclude_replies This parameter will prevent replies from appearing in the returned timeline. Using exclude_replies with the count parameter will mean you will receive up-to count tweets - this is because the count parameter retrieves that many tweets before filtering out retweets and replies. # @option options [Boolean, String, Integer] :contributor_details Specifies that the contributors element should be enhanced to include the screen_name of the contributor. # @option options [Boolean, String, Integer] :include_rts Specifies that the timeline should include native retweets in addition to regular tweets. Note: If you're using the trim_user parameter in conjunction with include_rts, the retweets will no longer contain a full user object. def user_timeline(*args) objects_from_response_with_user(Twitter::Tweet, :get, '/1.1/statuses/user_timeline.json', args) end # Returns the 20 most recent retweets posted by the specified user # # @see https://dev.twitter.com/rest/reference/get/statuses/user_timeline # @note This method can only return up to 3,200 Tweets. # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Array] # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, URI, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @option options [Boolean, String, Integer] :exclude_replies This parameter will prevent replies from appearing in the returned timeline. Using exclude_replies with the count parameter will mean you will receive up-to count tweets - this is because the count parameter retrieves that many tweets before filtering out retweets and replies. # @option options [Boolean, String, Integer] :contributor_details Specifies that the contributors element should be enhanced to include the screen_name of the contributor. def retweeted_by_user(user, options = {}) retweets_from_timeline(options) do |opts| user_timeline(user, opts) end end alias retweeted_by retweeted_by_user # Returns the 20 most recent retweets posted by the authenticating user # # @see https://dev.twitter.com/rest/reference/get/statuses/user_timeline # @note This method can only return up to 3,200 Tweets. # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Array] # @param options [Hash] A customizable set of options. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @option options [Boolean, String, Integer] :exclude_replies This parameter will prevent replies from appearing in the returned timeline. Using exclude_replies with the count parameter will mean you will receive up-to count tweets - this is because the count parameter retrieves that many tweets before filtering out retweets and replies. # @option options [Boolean, String, Integer] :contributor_details Specifies that the contributors element should be enhanced to include the screen_name of the contributor. def retweeted_by_me(options = {}) retweets_from_timeline(options) do |opts| user_timeline(opts) end end # Returns the 20 most recent Tweets, including retweets if they exist, posted by the authenticating user and the users they follow # # @see https://dev.twitter.com/rest/reference/get/statuses/home_timeline # @note This method can only return up to 800 Tweets, including retweets. # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Array] # @param options [Hash] A customizable set of options. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @option options [Boolean, String, Integer] :exclude_replies This parameter will prevent replies from appearing in the returned timeline. Using exclude_replies with the count parameter will mean you will receive up-to count tweets - this is because the count parameter retrieves that many tweets before filtering out retweets and replies. # @option options [Boolean, String, Integer] :include_rts Specifies that the timeline should include native retweets in addition to regular tweets. Note: If you're using the trim_user parameter in conjunction with include_rts, the retweets will no longer contain a full user object. # @option options [Boolean, String, Integer] :contributor_details Specifies that the contributors element should be enhanced to include the screen_name of the contributor. def home_timeline(options = {}) perform_get_with_objects('/1.1/statuses/home_timeline.json', options, Twitter::Tweet) end # Returns the 20 most recent retweets posted by users the authenticating user follow. # # @see https://dev.twitter.com/rest/reference/get/statuses/home_timeline # @note This method can only return up to 800 Tweets, including retweets. # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Array] # @param options [Hash] A customizable set of options. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @option options [Boolean, String, Integer] :exclude_replies This parameter will prevent replies from appearing in the returned timeline. Using exclude_replies with the count parameter will mean you will receive up-to count tweets - this is because the count parameter retrieves that many tweets before filtering out retweets and replies. # @option options [Boolean, String, Integer] :contributor_details Specifies that the contributors element should be enhanced to include the screen_name of the contributor. def retweeted_to_me(options = {}) retweets_from_timeline(options) do |opts| home_timeline(opts) end end # Returns the 20 most recent tweets of the authenticated user that have been retweeted by others # # @see https://dev.twitter.com/rest/reference/get/statuses/retweets_of_me # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Array] # @param options [Hash] A customizable set of options. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @option options [Boolean, String, Integer] :include_user_entities The user entities node will be disincluded when set to false. def retweets_of_me(options = {}) perform_get_with_objects('/1.1/statuses/retweets_of_me.json', options, Twitter::Tweet) end private def retweets_from_timeline(options) options[:include_rts] = true count = options[:count] || DEFAULT_TWEETS_PER_REQUEST collect_with_count(count) do |count_options| select_retweets(yield(options.merge(count_options))) end end # @param tweets [Array] # @return [Array] def select_retweets(tweets) tweets.select(&:retweet?) end # @param count [Integer] # @return [Array] def collect_with_count(count) options = {} options[:count] = MAX_TWEETS_PER_REQUEST collect_with_max_id do |max_id| options[:max_id] = max_id unless max_id.nil? if count > 0 tweets = yield(options) count -= tweets.length tweets end end.flatten.compact[0...count] end # @param collection [Array] # @param max_id [Integer, NilClass] # @return [Array] def collect_with_max_id(collection = [], max_id = nil, &block) tweets = yield(max_id) return collection if tweets.nil? collection += tweets tweets.empty? ? collection.flatten : collect_with_max_id(collection, tweets.last.id - 1, &block) end end end end twitter-5.16.0/lib/twitter/rest/friends_and_followers.rb0000644000004100000410000003534512666331030023471 0ustar www-datawww-datarequire 'twitter/arguments' require 'twitter/cursor' require 'twitter/relationship' require 'twitter/rest/request' require 'twitter/rest/utils' require 'twitter/user' require 'twitter/utils' module Twitter module REST module FriendsAndFollowers include Twitter::REST::Utils include Twitter::Utils # @see https://dev.twitter.com/rest/reference/get/friends/ids # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Twitter::Cursor] # @overload friend_ids(options = {}) # Returns an array of numeric IDs for every user the authenticated user is following # # @param options [Hash] A customizable set of options. # @overload friend_ids(user, options = {}) # Returns an array of numeric IDs for every user the specified user is following # # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, URI, or object. # @param options [Hash] A customizable set of options. def friend_ids(*args) cursor_from_response_with_user(:ids, nil, '/1.1/friends/ids.json', args) end # @see https://dev.twitter.com/rest/reference/get/followers/ids # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Twitter::Cursor] # @overload follower_ids(options = {}) # Returns an array of numeric IDs for every user following the authenticated user # # @param options [Hash] A customizable set of options. # @overload follower_ids(user, options = {}) # Returns an array of numeric IDs for every user following the specified user # # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, URI, or object. # @param options [Hash] A customizable set of options. def follower_ids(*args) cursor_from_response_with_user(:ids, nil, '/1.1/followers/ids.json', args) end # Returns the relationship of the authenticating user to the comma separated list of up to 100 screen_names or user_ids provided. Values for connections can be: following, following_requested, followed_by, none. # # @see https://dev.twitter.com/rest/reference/get/friendships/lookup # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Array] The requested users. # @overload friendships(*users) # @param users [Enumerable] A collection of Twitter user IDs, screen names, or objects. # @overload friendships(*users, options) # @param users [Enumerable] A collection of Twitter user IDs, screen names, or objects. # @param options [Hash] A customizable set of options. def friendships(*args) arguments = Twitter::Arguments.new(args) merge_users!(arguments.options, arguments) perform_get_with_objects('/1.1/friendships/lookup.json', arguments.options, Twitter::User) end # Returns an array of numeric IDs for every user who has a pending request to follow the authenticating user # # @see https://dev.twitter.com/rest/reference/get/friendships/incoming # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Twitter::Cursor] # @param options [Hash] A customizable set of options. def friendships_incoming(options = {}) perform_get_with_cursor('/1.1/friendships/incoming.json', options, :ids) end # Returns an array of numeric IDs for every protected user for whom the authenticating user has a pending follow request # # @see https://dev.twitter.com/rest/reference/get/friendships/outgoing # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Twitter::Cursor] # @param options [Hash] A customizable set of options. def friendships_outgoing(options = {}) perform_get_with_cursor('/1.1/friendships/outgoing.json', options, :ids) end # Allows the authenticating user to follow the specified users, unless they are already followed # # @see https://dev.twitter.com/rest/reference/post/friendships/create # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Array] The followed users. # @overload follow(*users) # @param users [Enumerable] A collection of Twitter user IDs, screen names, or objects. # @overload follow(*users, options) # @param users [Enumerable] A collection of Twitter user IDs, screen names, or objects. # @param options [Hash] A customizable set of options. # @option options [Boolean] :follow (false) Enable notifications for the target user. def follow(*args) arguments = Twitter::Arguments.new(args) existing_friends = Thread.new do friend_ids.to_a end new_friends = Thread.new do users(args).collect(&:id) end follow!(new_friends.value - existing_friends.value, arguments.options) end alias create_friendship follow deprecate_alias :friendship_create, :follow # Allows the authenticating user to follow the specified users # # @see https://dev.twitter.com/rest/reference/post/friendships/create # @rate_limited No # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Array] The followed users. # @overload follow!(*users) # @param users [Enumerable] A collection of Twitter user IDs, screen names, or objects. # @overload follow!(*users, options) # @param users [Enumerable] A collection of Twitter user IDs, screen names, or objects. # @param options [Hash] A customizable set of options. # @option options [Boolean] :follow (false) Enable notifications for the target user. def follow!(*args) arguments = Twitter::Arguments.new(args) pmap(arguments) do |user| perform_post_with_object('/1.1/friendships/create.json', merge_user(arguments.options, user), Twitter::User) end.compact end alias create_friendship! follow! deprecate_alias :friendship_create!, :follow! # Allows the authenticating user to unfollow the specified users # # @see https://dev.twitter.com/rest/reference/post/friendships/destroy # @rate_limited No # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Array] The unfollowed users. # @overload unfollow(*users) # @param users [Enumerable] A collection of Twitter user IDs, screen names, or objects. # @overload unfollow(*users, options) # @param users [Enumerable] A collection of Twitter user IDs, screen names, or objects. # @param options [Hash] A customizable set of options. def unfollow(*args) parallel_users_from_response(:post, '/1.1/friendships/destroy.json', args) end alias destroy_friendship unfollow deprecate_alias :friendship_destroy, :unfollow # Allows one to enable or disable retweets and device notifications from the specified user. # # @see https://dev.twitter.com/rest/reference/post/friendships/update # @rate_limited No # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Twitter::Relationship] # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, URI, or object. # @param options [Hash] A customizable set of options. # @option options [Boolean] :device Enable/disable device notifications from the target user. # @option options [Boolean] :retweets Enable/disable retweets from the target user. def friendship_update(user, options = {}) merge_user!(options, user) perform_post_with_object('/1.1/friendships/update.json', options, Twitter::Relationship) end # Returns detailed information about the relationship between two users # # @see https://dev.twitter.com/rest/reference/get/friendships/show # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Twitter::Relationship] # @param source [Integer, String, Twitter::User] The Twitter user ID, screen name, or object of the source user. # @param target [Integer, String, Twitter::User] The Twitter user ID, screen name, or object of the target user. # @param options [Hash] A customizable set of options. def friendship(source, target, options = {}) merge_user!(options, source, 'source') options[:source_id] = options.delete(:source_user_id) unless options[:source_user_id].nil? merge_user!(options, target, 'target') options[:target_id] = options.delete(:target_user_id) unless options[:target_user_id].nil? perform_get_with_object('/1.1/friendships/show.json', options, Twitter::Relationship) end alias friendship_show friendship alias relationship friendship # Test for the existence of friendship between two users # # @see https://dev.twitter.com/rest/reference/get/friendships/show # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Boolean] true if user_a follows user_b, otherwise false. # @param source [Integer, String, Twitter::User] The Twitter user ID, screen name, or object of the source user. # @param target [Integer, String, Twitter::User] The Twitter user ID, screen name, or object of the target user. # @param options [Hash] A customizable set of options. def friendship?(source, target, options = {}) friendship(source, target, options).source.following? end # Returns a cursored collection of user objects for users following the specified user. # # @see https://dev.twitter.com/rest/reference/get/followers/list # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Twitter::Cursor] # @overload followers(options = {}) # Returns a cursored collection of user objects for users following the authenticated user. # # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :skip_status Do not include contributee's Tweets when set to true, 't' or 1. # @option options [Boolean, String, Integer] :include_user_entities The user entities node will be disincluded when set to false. # @overload followers(user, options = {}) # Returns a cursored collection of user objects for users following the specified user. # # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, URI, or object. # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :skip_status Do not include contributee's Tweets when set to true, 't' or 1. # @option options [Boolean, String, Integer] :include_user_entities The user entities node will be disincluded when set to false. def followers(*args) cursor_from_response_with_user(:users, Twitter::User, '/1.1/followers/list.json', args) end # Returns a cursored collection of user objects for every user the specified user is following (otherwise known as their "friends"). # # @see https://dev.twitter.com/rest/reference/get/friends/list # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Twitter::Cursor] # @overload friends(options = {}) # Returns a cursored collection of user objects for every user the authenticated user is following (otherwise known as their "friends"). # # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :skip_status Do not include contributee's Tweets when set to true, 't' or 1. # @option options [Boolean, String, Integer] :include_user_entities The user entities node will be disincluded when set to false. # @overload friends(user, options = {}) # Returns a cursored collection of user objects for every user the specified user is following (otherwise known as their "friends"). # # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, URI, or object. # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :skip_status Do not include contributee's Tweets when set to true, 't' or 1. # @option options [Boolean, String, Integer] :include_user_entities The user entities node will be disincluded when set to false. def friends(*args) cursor_from_response_with_user(:users, Twitter::User, '/1.1/friends/list.json', args) end alias following friends # Returns a collection of user IDs that the currently authenticated user does not want to receive retweets from. # @see https://dev.twitter.com/rest/reference/get/friendships/no_retweets/ids # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Array] # @param options [Hash] A customizable set of options. def no_retweet_ids(options = {}) perform_get('/1.1/friendships/no_retweets/ids.json', options).collect(&:to_i) end alias no_retweets_ids no_retweet_ids end end end twitter-5.16.0/lib/twitter/rest/utils.rb0000644000004100000410000002066412666331030020257 0ustar www-datawww-datarequire 'addressable/uri' require 'twitter/arguments' require 'twitter/cursor' require 'twitter/rest/request' require 'twitter/user' require 'twitter/utils' module Twitter module REST module Utils include Twitter::Utils URI_SUBSTRING = '://'.freeze DEFAULT_CURSOR = -1 private # Take a URI string or Twitter::Identity object and return its ID # # @param object [Integer, String, URI, Twitter::Identity] An ID, URI, or object. # @return [Integer] def extract_id(object) case object when ::Integer object when ::String object.split('/').last.to_i when URI object.path.split('/').last.to_i when Twitter::Identity object.id end end # @param path [String] # @param options [Hash] def perform_get(path, options = {}) perform_request(:get, path, options) end # @param path [String] # @param options [Hash] def perform_post(path, options = {}) perform_request(:post, path, options) end # @param request_method [Symbol] # @param path [String] # @param options [Hash] def perform_request(request_method, path, options = {}) Twitter::REST::Request.new(self, request_method, path, options).perform end # @param path [String] # @param options [Hash] # @param klass [Class] def perform_get_with_object(path, options, klass) perform_request_with_object(:get, path, options, klass) end # @param path [String] # @param options [Hash] # @param klass [Class] def perform_post_with_object(path, options, klass) perform_request_with_object(:post, path, options, klass) end # @param request_method [Symbol] # @param path [String] # @param options [Hash] # @param klass [Class] def perform_request_with_object(request_method, path, options, klass) response = perform_request(request_method, path, options) klass.new(response) end # @param path [String] # @param options [Hash] # @param klass [Class] def perform_get_with_objects(path, options, klass) perform_request_with_objects(:get, path, options, klass) end # @param path [String] # @param options [Hash] # @param klass [Class] def perform_post_with_objects(path, options, klass) perform_request_with_objects(:post, path, options, klass) end # @param request_method [Symbol] # @param path [String] # @param options [Hash] # @param klass [Class] def perform_request_with_objects(request_method, path, options, klass) perform_request(request_method, path, options).collect do |element| klass.new(element) end end # @param path [String] # @param options [Hash] # @param collection_name [Symbol] # @param klass [Class] def perform_get_with_cursor(path, options, collection_name, klass = nil) merge_default_cursor!(options) request = Twitter::REST::Request.new(self, :get, path, options) Twitter::Cursor.new(collection_name.to_sym, klass, request) end # @param request_method [Symbol] # @param path [String] # @param args [Array] # @return [Array] def parallel_users_from_response(request_method, path, args) arguments = Twitter::Arguments.new(args) pmap(arguments) do |user| perform_request_with_object(request_method, path, merge_user(arguments.options, user), Twitter::User) end end # @param request_method [Symbol] # @param path [String] # @param args [Array] # @return [Array] def users_from_response(request_method, path, args) arguments = Twitter::Arguments.new(args) merge_user!(arguments.options, arguments.pop || user_id) unless arguments.options[:user_id] || arguments.options[:screen_name] perform_request_with_objects(request_method, path, arguments.options, Twitter::User) end # @param klass [Class] # @param request_method [Symbol] # @param path [String] # @param args [Array] # @return [Array] def objects_from_response_with_user(klass, request_method, path, args) arguments = Twitter::Arguments.new(args) merge_user!(arguments.options, arguments.pop) perform_request_with_objects(request_method, path, arguments.options, klass) end # @param klass [Class] # @param request_method [Symbol] # @param path [String] # @param args [Array] # @return [Array] def parallel_objects_from_response(klass, request_method, path, args) arguments = Twitter::Arguments.new(args) pmap(arguments) do |object| perform_request_with_object(request_method, path, arguments.options.merge(:id => extract_id(object)), klass) end end # @param collection_name [Symbol] # @param klass [Class] # @param path [String] # @param args [Array] # @return [Twitter::Cursor] def cursor_from_response_with_user(collection_name, klass, path, args) arguments = Twitter::Arguments.new(args) merge_user!(arguments.options, arguments.pop || user_id) unless arguments.options[:user_id] || arguments.options[:screen_name] perform_get_with_cursor(path, arguments.options, collection_name, klass) end def user_id @user_id ||= verify_credentials(:skip_status => true).id end def user_id? instance_variable_defined?(:@user_id) end def merge_default_cursor!(options) options[:cursor] = DEFAULT_CURSOR unless options[:cursor] end # Take a user and merge it into the hash with the correct key # # @param hash [Hash] # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, URI, or object. # @return [Hash] def merge_user(hash, user, prefix = nil) merge_user!(hash.dup, user, prefix) end # Take a user and merge it into the hash with the correct key # # @param hash [Hash] # @param user [Integer, String, URI, Twitter::User] A Twitter user ID, screen name, URI, or object. # @return [Hash] def merge_user!(hash, user, prefix = nil) case user when Integer set_compound_key('user_id', user, hash, prefix) when String if user[URI_SUBSTRING] set_compound_key('screen_name', user.split('/').last, hash, prefix) else set_compound_key('screen_name', user, hash, prefix) end when URI, Addressable::URI set_compound_key('screen_name', user.path.split('/').last, hash, prefix) when Twitter::User set_compound_key('user_id', user.id, hash, prefix) end end def set_compound_key(key, value, hash, prefix = nil) compound_key = [prefix, key].compact.join('_').to_sym hash[compound_key] = value hash end # Take a multiple users and merge them into the hash with the correct keys # # @param hash [Hash] # @param users [Enumerable] A collection of Twitter user IDs, screen_names, or objects. # @return [Hash] def merge_users(hash, users) merge_users!(hash.dup, users) end # Take a multiple users and merge them into the hash with the correct keys # # @param hash [Hash] # @param users [Enumerable] A collection of Twitter user IDs, screen_names, URIs, or objects. # @return [Hash] def merge_users!(hash, users) user_ids, screen_names = collect_user_ids_and_screen_names(users) hash[:user_id] = user_ids.join(',') unless user_ids.empty? hash[:screen_name] = screen_names.join(',') unless screen_names.empty? hash end def collect_user_ids_and_screen_names(users) user_ids = [] screen_names = [] users.flatten.each do |user| case user when Integer user_ids << user when String screen_names << (user[URI_SUBSTRING] ? user.split('/').last : user) when URI screen_names << user.path.split('/').last when Twitter::User user_ids << user.id end end [user_ids, screen_names] end end end end twitter-5.16.0/lib/twitter/rest/undocumented.rb0000644000004100000410000000312212666331030021577 0ustar www-datawww-datarequire 'twitter/arguments' require 'twitter/cursor' require 'twitter/rest/utils' require 'twitter/tweet' require 'twitter/user' module Twitter module REST module Undocumented include Twitter::REST::Utils # @note Undocumented # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Twitter::Cursor] # @overload following_followers_of(options = {}) # Returns users following followers of the specified user # # @param options [Hash] A customizable set of options. # @overload following_followers_of(user, options = {}) # Returns users following followers of the authenticated user # # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, URI, or object. # @param options [Hash] A customizable set of options. def following_followers_of(*args) cursor_from_response_with_user(:users, Twitter::User, '/users/following_followers_of.json', args) end # Returns Tweets count for a URI # # @note Undocumented # @rate_limited No # @authentication Not required # @return [Integer] # @param uri [String, URI] A URI. # @param options [Hash] A customizable set of options. def tweet_count(uri, options = {}) connection = Faraday.new('https://cdn.api.twitter.com', connection_options) connection.get('/1/urls/count.json', options.merge(:url => uri.to_s)).body[:count] end end end end twitter-5.16.0/lib/twitter/rest/response/0000755000004100000410000000000012666331030020420 5ustar www-datawww-datatwitter-5.16.0/lib/twitter/rest/response/parse_json.rb0000644000004100000410000000135212666331030023111 0ustar www-datawww-datarequire 'faraday' require 'json' module Twitter module REST module Response class ParseJson < Faraday::Response::Middleware WHITESPACE_REGEX = /\A^\s*$\z/ def parse(body) case body when WHITESPACE_REGEX, nil nil else JSON.parse(body, :symbolize_names => true) end end def on_complete(response) response.body = parse(response.body) if respond_to?(:parse) && !unparsable_status_codes.include?(response.status) end def unparsable_status_codes [204, 301, 302, 304] end end end end end Faraday::Response.register_middleware :twitter_parse_json => Twitter::REST::Response::ParseJson twitter-5.16.0/lib/twitter/rest/response/raise_error.rb0000644000004100000410000000165612666331030023271 0ustar www-datawww-datarequire 'faraday' require 'twitter/error' module Twitter module REST module Response class RaiseError < Faraday::Response::Middleware def on_complete(response) status_code = response.status.to_i klass = Twitter::Error.errors[status_code] return unless klass if klass == Twitter::Error::Forbidden fail(handle_forbidden_errors(response)) else fail(klass.from_response(response)) end end private def handle_forbidden_errors(response) error = Twitter::Error::Forbidden.from_response(response) klass = Twitter::Error.forbidden_messages[error.message] if klass klass.from_response(response) else error end end end end end end Faraday::Response.register_middleware :twitter_raise_error => Twitter::REST::Response::RaiseError twitter-5.16.0/lib/twitter/rest/response/parse_error_json.rb0000644000004100000410000000040112666331030024314 0ustar www-datawww-datarequire 'twitter/rest/response/parse_json' module Twitter module REST module Response class ParseErrorJson < Twitter::REST::Response::ParseJson def unparsable_status_codes super + [200] end end end end end twitter-5.16.0/lib/twitter/rest/trends.rb0000644000004100000410000000573412666331030020417 0ustar www-datawww-datarequire 'twitter/place' require 'twitter/rest/request' require 'twitter/rest/utils' require 'twitter/trend_results' module Twitter module REST module Trends include Twitter::REST::Utils # Returns the top 50 trending topics for a specific WOEID # # @see https://dev.twitter.com/rest/reference/get/trends/place # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @param id [Integer] The {https://developer.yahoo.com/geo/geoplanet Yahoo! Where On Earth ID} of the location to return trending information for. WOEIDs can be retrieved by calling {Twitter::REST::Trends#trends_available}. Global information is available by using 1 as the WOEID. # @param options [Hash] A customizable set of options. # @option options [String] :exclude Setting this equal to 'hashtags' will remove all hashtags from the trends list. # @return [Array] def trends(id = 1, options = {}) options[:id] = id response = perform_get('/1.1/trends/place.json', options).first Twitter::TrendResults.new(response) end alias local_trends trends alias trends_place trends # Returns the locations that Twitter has trending topic information for # # @see https://dev.twitter.com/rest/reference/get/trends/available # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @param options [Hash] A customizable set of options. # @return [Array] def trends_available(options = {}) perform_get_with_objects('/1.1/trends/available.json', options, Twitter::Place) end alias trend_locations trends_available # Returns the locations that Twitter has trending topic information for, closest to a specified location. # # @see https://dev.twitter.com/rest/reference/get/trends/closest # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @param options [Hash] A customizable set of options. # @option options [Float] :lat If provided with a :long option the available trend locations will be sorted by distance, nearest to furthest, to the co-ordinate pair. The valid ranges for latitude are -90.0 to +90.0 (North is positive) inclusive. # @option options [Float] :long If provided with a :lat option the available trend locations will be sorted by distance, nearest to furthest, to the co-ordinate pair. The valid ranges for longitude are -180.0 to +180.0 (East is positive) inclusive. # @return [Array] def trends_closest(options = {}) perform_get_with_objects('/1.1/trends/closest.json', options, Twitter::Place) end end end end twitter-5.16.0/lib/twitter/rest/suggested_users.rb0000644000004100000410000000374112666331030022327 0ustar www-datawww-datarequire 'twitter/arguments' require 'twitter/rest/utils' require 'twitter/suggestion' require 'twitter/user' module Twitter module REST module SuggestedUsers include Twitter::REST::Utils # @return [Array] # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @overload suggestions(options = {}) # Returns the list of suggested user categories # # @see https://dev.twitter.com/rest/reference/get/users/suggestions # @param options [Hash] A customizable set of options. # @overload suggestions(slug, options = {}) # Returns the users in a given category # # @see https://dev.twitter.com/rest/reference/get/users/suggestions/:slug # @param slug [String] The short name of list or a category. # @param options [Hash] A customizable set of options. def suggestions(*args) arguments = Twitter::Arguments.new(args) if arguments.last perform_get_with_object("/1.1/users/suggestions/#{arguments.pop}.json", arguments.options, Twitter::Suggestion) else perform_get_with_objects('/1.1/users/suggestions.json', arguments.options, Twitter::Suggestion) end end # Access the users in a given category of the Twitter suggested user list and return their most recent Tweet if they are not a protected user # # @see https://dev.twitter.com/rest/reference/get/users/suggestions/:slug/members # @rate_limited Yes # @authentication Requires user context # @param slug [String] The short name of list or a category. # @param options [Hash] A customizable set of options. # @return [Array] def suggest_users(slug, options = {}) perform_get_with_objects("/1.1/users/suggestions/#{slug}/members.json", options, Twitter::User) end end end end twitter-5.16.0/lib/twitter/rest/client.rb0000644000004100000410000000673212666331030020375 0ustar www-datawww-datarequire 'faraday' require 'faraday/request/multipart' require 'twitter/client' require 'twitter/rest/api' require 'twitter/rest/request' require 'twitter/rest/request/multipart_with_file' require 'twitter/rest/response/parse_json' require 'twitter/rest/response/raise_error' require 'twitter/rest/utils' module Twitter module REST class Client < Twitter::Client include Twitter::REST::API BASE_URL = 'https://api.twitter.com'.freeze URL_PREFIX = BASE_URL ENDPOINT = BASE_URL attr_accessor :bearer_token # @param connection_options [Hash] # @return [Hash] def connection_options=(connection_options) warn "#{Kernel.caller.first}: [DEPRECATION] #{self.class.name}##{__method__} is deprecated and will be removed." @connection_options = connection_options end # @return [Hash] def connection_options @connection_options ||= { :builder => middleware, :headers => { :accept => 'application/json', :user_agent => user_agent, }, :request => { :open_timeout => 10, :timeout => 30, }, :proxy => proxy, } end # @params middleware [Faraday::RackBuilder] # @return [Faraday::RackBuilder] def middleware=(middleware) warn "#{Kernel.caller.first}: [DEPRECATION] #{self.class.name}##{__method__} is deprecated and will be removed." @middleware = middleware end # @note Faraday's middleware stack implementation is comparable to that of Rack middleware. The order of middleware is important: the first middleware on the list wraps all others, while the last middleware is the innermost one. # @see https://github.com/technoweenie/faraday#advanced-middleware-usage # @see http://mislav.uniqpath.com/2011/07/faraday-advanced-http/ # @return [Faraday::RackBuilder] def middleware @middleware ||= Faraday::RackBuilder.new do |faraday| # Convert file uploads to Faraday::UploadIO objects faraday.request :twitter_multipart_with_file # Checks for files in the payload, otherwise leaves everything untouched faraday.request :multipart # Encodes as "application/x-www-form-urlencoded" if not already encoded faraday.request :url_encoded # Handle error responses faraday.response :twitter_raise_error # Parse JSON response bodies faraday.response :twitter_parse_json # Set default HTTP adapter faraday.adapter :net_http end end # Perform an HTTP GET request def get(path, options = {}) warn "#{Kernel.caller.first}: [DEPRECATION] #{self.class.name}##{__method__} is deprecated. Use Twitter::REST::Request#perform instead." perform_get(path, options) end # Perform an HTTP POST request def post(path, options = {}) warn "#{Kernel.caller.first}: [DEPRECATION] #{self.class.name}##{__method__} is deprecated. Use Twitter::REST::Request#perform instead." perform_post(path, options) end # @return [Boolean] def bearer_token? !!bearer_token end # @return [Boolean] def credentials? super || bearer_token? end # Returns a Faraday::Connection object # # @return [Faraday::Connection] def connection @connection ||= Faraday.new(BASE_URL, connection_options) end end end end twitter-5.16.0/lib/twitter/rest/places_and_geo.rb0000644000004100000410000001711012666331030022032 0ustar www-datawww-datarequire 'twitter/geo_results' require 'twitter/place' require 'twitter/rest/utils' module Twitter module REST module PlacesAndGeo include Twitter::REST::Utils # Returns all the information about a known place # # @see https://dev.twitter.com/rest/reference/get/geo/id/:place_id # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @param place_id [String] A place in the world. These IDs can be retrieved from {Twitter::REST::PlacesAndGeo#reverse_geocode}. # @param options [Hash] A customizable set of options. # @return [Twitter::Place] The requested place. def place(place_id, options = {}) perform_get_with_object("/1.1/geo/id/#{place_id}.json", options, Twitter::Place) end # Searches for up to 20 places that can be used as a place_id # # @see https://dev.twitter.com/rest/reference/get/geo/reverse_geocode # @note This request is an informative call and will deliver generalized results about geography. # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @param options [Hash] A customizable set of options. # @option options [Float] :lat The latitude to search around. This option will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding :long option. # @option options [Float] :long The longitude to search around. The valid range for longitude is -180.0 to +180.0 (East is positive) inclusive. This option will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding :lat option. # @option options [String] :accuracy ('0m') A hint on the "region" in which to search. If a number, then this is a radius in meters, but it can also take a string that is suffixed with ft to specify feet. If coming from a device, in practice, this value is whatever accuracy the device has measuring its location (whether it be coming from a GPS, WiFi triangulation, etc.). # @option options [String] :granularity ('neighborhood') This is the minimal granularity of place types to return and must be one of: 'poi', 'neighborhood', 'city', 'admin' or 'country'. # @option options [Integer] :max_results A hint as to the number of results to return. This does not guarantee that the number of results returned will equal max_results, but instead informs how many "nearby" results to return. Ideally, only pass in the number of places you intend to display to the user here. # @return [Array] def reverse_geocode(options = {}) perform_get_with_object('/1.1/geo/reverse_geocode.json', options, Twitter::GeoResults) end # Search for places that can be attached to a {Twitter::REST::Tweets#update} # # @see https://dev.twitter.com/rest/reference/get/geo/search # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @param options [Hash] A customizable set of options. # @option options [Float] :lat The latitude to search around. This option will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding :long option. # @option options [Float] :long The longitude to search around. The valid range for longitude is -180.0 to +180.0 (East is positive) inclusive. This option will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding :lat option. # @option options [String] :query Free-form text to match against while executing a geo-based query, best suited for finding nearby locations by name. # @option options [String] :ip An IP address. Used when attempting to fix geolocation based off of the user's IP address. # @option options [String] :granularity ('neighborhood') This is the minimal granularity of place types to return and must be one of: 'poi', 'neighborhood', 'city', 'admin' or 'country'. # @option options [String] :accuracy ('0m') A hint on the "region" in which to search. If a number, then this is a radius in meters, but it can also take a string that is suffixed with ft to specify feet. If coming from a device, in practice, this value is whatever accuracy the device has measuring its location (whether it be coming from a GPS, WiFi triangulation, etc.). # @option options [Integer] :max_results A hint as to the number of results to return. This does not guarantee that the number of results returned will equal max_results, but instead informs how many "nearby" results to return. Ideally, only pass in the number of places you intend to display to the user here. # @option options [String] :contained_within This is the place_id which you would like to restrict the search results to. Setting this value means only places within the given place_id will be found. # @option options [String] :"attribute:street_address" This option searches for places which have this given street address. There are other well-known and application-specific attributes available. Custom attributes are also permitted. # @return [Array] def geo_search(options = {}) perform_get_with_object('/1.1/geo/search.json', options, Twitter::GeoResults) end alias places_nearby geo_search # Locates places near the given coordinates which are similar in name # # @see https://dev.twitter.com/rest/reference/get/geo/similar_places # @note Conceptually, you would use this method to get a list of known places to choose from first. Then, if the desired place doesn't exist, make a request to {Twitter::REST::PlacesAndGeo#place} to create a new one. The token contained in the response is the token necessary to create a new place. # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @param options [Hash] A customizable set of options. # @option options [Float] :lat The latitude to search around. This option will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding :long option. # @option options [Float] :long The longitude to search around. The valid range for longitude is -180.0 to +180.0 (East is positive) inclusive. This option will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding :lat option. # @option options [String] :name The name a place is known as. # @option options [String] :contained_within This is the place_id which you would like to restrict the search results to. Setting this value means only places within the given place_id will be found. # @option options [String] :"attribute:street_address" This option searches for places which have this given street address. There are other well-known and application-specific attributes available. Custom attributes are also permitted. # @return [Array] def similar_places(options = {}) perform_get_with_object('/1.1/geo/similar_places.json', options, Twitter::GeoResults) end alias places_similar similar_places end end end twitter-5.16.0/lib/twitter/rest/tweets.rb0000644000004100000410000005732512666331030020436 0ustar www-datawww-datarequire 'twitter/arguments' require 'twitter/error' require 'twitter/oembed' require 'twitter/rest/request' require 'twitter/rest/utils' require 'twitter/tweet' require 'twitter/utils' module Twitter module REST module Tweets include Twitter::REST::Utils include Twitter::Utils MAX_TWEETS_PER_REQUEST = 100 # Returns up to 100 of the first retweets of a given tweet # # @see https://dev.twitter.com/rest/reference/get/statuses/retweets/:id # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Array] # @param tweet [Integer, String, URI, Twitter::Tweet] A Tweet ID, URI, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 100. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. def retweets(tweet, options = {}) perform_get_with_objects("/1.1/statuses/retweets/#{extract_id(tweet)}.json", options, Twitter::Tweet) end # Show up to 100 users who retweeted the Tweet # # @see https://dev.twitter.com/rest/reference/get/statuses/retweets/:id # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Array] # @param tweet [Integer, String, URI, Twitter::Tweet] A Tweet ID, URI, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 100. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @option options [Boolean] :ids_only ('false') Only return user IDs instead of full user objects. def retweeters_of(tweet, options = {}) ids_only = !!options.delete(:ids_only) retweeters = retweets(tweet, options).collect(&:user) ids_only ? retweeters.collect(&:id) : retweeters end # Returns a Tweet # # @see https://dev.twitter.com/rest/reference/get/statuses/show/:id # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @raise [Twitter::Error::Forbidden] Error raised when supplied status is over 140 characters. # @return [Twitter::Tweet] The requested Tweet. # @param tweet [Integer, String, URI, Twitter::Tweet] A Tweet ID, URI, or object. # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. def status(tweet, options = {}) perform_get_with_object("/1.1/statuses/show/#{extract_id(tweet)}.json", options, Twitter::Tweet) end # Returns Tweets # # @see https://dev.twitter.com/rest/reference/get/statuses/lookup # @rate_limited Yes # @authentication Required # @return [Array] The requested Tweets. # @overload statuses(*tweets) # @param tweets [Enumerable] A collection of Tweet IDs, URIs, or objects. # @overload statuses(*tweets, options) # @param tweets [Enumerable] A collection of Tweet IDs, URIs, or objects. # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. def statuses(*args) arguments = Twitter::Arguments.new(args) flat_pmap(arguments.each_slice(MAX_TWEETS_PER_REQUEST)) do |tweets| perform_post_with_objects('/1.1/statuses/lookup.json', arguments.options.merge(:id => tweets.collect { |u| extract_id(u) }.join(',')), Twitter::Tweet) end end # Destroys the specified Tweets # # @see https://dev.twitter.com/rest/reference/post/statuses/destroy/:id # @note The authenticating user must be the author of the specified Tweets. # @rate_limited No # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Array] The deleted Tweets. # @overload destroy_status(*tweets) # @param tweets [Enumerable] A collection of Tweet IDs, URIs, or objects. # @overload destroy_status(*tweets, options) # @param tweets [Enumerable] A collection of Tweet IDs, URIs, or objects. # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. def destroy_status(*args) arguments = Twitter::Arguments.new(args) pmap(arguments) do |tweet| perform_post_with_object("/1.1/statuses/destroy/#{extract_id(tweet)}.json", arguments.options, Twitter::Tweet) end end alias destroy_tweet destroy_status deprecate_alias :status_destroy, :destroy_status deprecate_alias :tweet_destroy, :destroy_status # Updates the authenticating user's status # # @see https://dev.twitter.com/rest/reference/post/statuses/update # @note A status update with text identical to the authenticating user's current status will be ignored to prevent duplicates. # @rate_limited No # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Twitter::Tweet] The created Tweet. When the tweet is deemed a duplicate by Twitter, returns the last Tweet from the user's timeline. # @param status [String] The text of your status update, up to 140 characters. # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :possibly_sensitive Set to true for content which may not be suitable for every audience. # @option options [Twitter::Tweet] :in_reply_to_status An existing status that the update is in reply to. If the status being replied to was not originally posted by the authenticated user, the text of the status must begin with an @-mention, or twitter will reject the update. # @option options [Integer] :in_reply_to_status_id The ID of an existing status that the update is in reply to. # @option options [Float] :lat The latitude of the location this tweet refers to. This option will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding :long option. # @option options [Float] :long The longitude of the location this tweet refers to. The valid ranges for longitude is -180.0 to +180.0 (East is positive) inclusive. This option will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding :lat option. # @option options [Twitter::Place] :place A place in the world. These can be retrieved from {Twitter::REST::PlacesAndGeo#reverse_geocode}. # @option options [String] :place_id A place in the world. These IDs can be retrieved from {Twitter::REST::PlacesAndGeo#reverse_geocode}. # @option options [String] :media_ids A comma separated list of uploaded media IDs to attach to the Tweet. # @option options [String] :display_coordinates Whether or not to put a pin on the exact coordinates a tweet has been sent from. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. def update(status, options = {}) update!(status, options) rescue Twitter::Error::DuplicateStatus user_timeline(:count => 1).first end # Updates the authenticating user's status # # @see https://dev.twitter.com/rest/reference/post/statuses/update # @note A status update with text identical to the authenticating user's current status will be ignored to prevent duplicates. # @rate_limited No # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @raise [Twitter::Error::DuplicateStatus] Error raised when a duplicate status is posted. # @return [Twitter::Tweet] The created Tweet. # @param status [String] The text of your status update, up to 140 characters. # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :possibly_sensitive Set to true for content which may not be suitable for every audience. # @option options [Twitter::Tweet] :in_reply_to_status An existing status that the update is in reply to. If the status being replied to was not originally posted by the authenticated user, the text of the status must begin with an @-mention, or twitter will reject the update. # @option options [Integer] :in_reply_to_status_id The ID of an existing status that the update is in reply to. # @option options [Float] :lat The latitude of the location this tweet refers to. This option will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding :long option. # @option options [Float] :long The longitude of the location this tweet refers to. The valid ranges for longitude is -180.0 to +180.0 (East is positive) inclusive. This option will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding :lat option. # @option options [Twitter::Place] :place A place in the world. These can be retrieved from {Twitter::REST::PlacesAndGeo#reverse_geocode}. # @option options [String] :place_id A place in the world. These IDs can be retrieved from {Twitter::REST::PlacesAndGeo#reverse_geocode}. # @option options [String] :media_ids A comma separated list of uploaded media IDs to attach to the Tweet. # @option options [String] :display_coordinates Whether or not to put a pin on the exact coordinates a tweet has been sent from. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. def update!(status, options = {}) hash = options.dup hash[:in_reply_to_status_id] = hash.delete(:in_reply_to_status).id unless hash[:in_reply_to_status].nil? hash[:place_id] = hash.delete(:place).woeid unless hash[:place].nil? perform_post_with_object('/1.1/statuses/update.json', hash.merge(:status => status), Twitter::Tweet) end # Retweets the specified Tweets as the authenticating user # # @see https://dev.twitter.com/rest/reference/post/statuses/retweet/:id # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Array] The original tweets with retweet details embedded. # @overload retweet(*tweets) # @param tweets [Enumerable] A collection of Tweet IDs, URIs, or objects. # @overload retweet(*tweets, options) # @param tweets [Enumerable] A collection of Tweet IDs, URIs, or objects. # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. def retweet(*args) arguments = Twitter::Arguments.new(args) pmap(arguments) do |tweet| begin post_retweet(extract_id(tweet), arguments.options) rescue Twitter::Error::AlreadyRetweeted, Twitter::Error::NotFound next end end.compact end # Retweets the specified Tweets as the authenticating user and raises an error if one has already been retweeted # # @see https://dev.twitter.com/rest/reference/post/statuses/retweet/:id # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::AlreadyRetweeted] Error raised when tweet has already been retweeted. # @raise [Twitter::Error::NotFound] Error raised when tweet does not exist or has been deleted. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Array] The original tweets with retweet details embedded. # @overload retweet!(*tweets) # @param tweets [Enumerable] A collection of Tweet IDs, URIs, or objects. # @overload retweet!(*tweets, options) # @param tweets [Enumerable] A collection of Tweet IDs, URIs, or objects. # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. def retweet!(*args) arguments = Twitter::Arguments.new(args) pmap(arguments) do |tweet| post_retweet(extract_id(tweet), arguments.options) end.compact end # Updates the authenticating user's status with media # # @see https://dev.twitter.com/rest/reference/post/statuses/update_with_media # @note A status update with text/media identical to the authenticating user's current status will NOT be ignored # @rate_limited No # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @raise [Twitter::Error::UnacceptableIO] Error when the IO object for the media argument does not have a to_io method. # @return [Twitter::Tweet] The created Tweet. # @param status [String] The text of your status update, up to 140 characters. # @param media [File, Hash] A File object with your picture (PNG, JPEG or GIF) # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :possibly_sensitive Set to true for content which may not be suitable for every audience. # @option options [Twitter::Tweet] :in_reply_to_status An existing status that the update is in reply to. # @option options [Integer] :in_reply_to_status_id The ID of an existing Tweet that the update is in reply to. # @option options [Float] :lat The latitude of the location this tweet refers to. This option will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding :long option. # @option options [Float] :long The longitude of the location this tweet refers to. The valid ranges for longitude is -180.0 to +180.0 (East is positive) inclusive. This option will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding :lat option. # @option options [Twitter::Place] :place A place in the world. These can be retrieved from {Twitter::REST::PlacesAndGeo#reverse_geocode}. # @option options [String] :place_id A place in the world. These IDs can be retrieved from {Twitter::REST::PlacesAndGeo#reverse_geocode}. # @option options [String] :display_coordinates Whether or not to put a pin on the exact coordinates a tweet has been sent from. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. def update_with_media(status, media, options = {}) fail(Twitter::Error::UnacceptableIO.new) unless media.respond_to?(:to_io) hash = options.dup hash[:in_reply_to_status_id] = hash.delete(:in_reply_to_status).id unless hash[:in_reply_to_status].nil? hash[:place_id] = hash.delete(:place).woeid unless hash[:place].nil? perform_post_with_object('/1.1/statuses/update_with_media.json', hash.merge('media[]' => media, 'status' => status), Twitter::Tweet) end # Returns oEmbed for a Tweet # # @see https://dev.twitter.com/rest/reference/get/statuses/oembed # @rate_limited Yes # @authentication Requires user context # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Twitter::OEmbed] OEmbed for the requested Tweet. # @param tweet [Integer, String, URI, Twitter::Tweet] A Tweet ID, URI, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :maxwidth The maximum width in pixels that the embed should be rendered at. This value is constrained to be between 250 and 550 pixels. # @option options [Boolean, String, Integer] :hide_media Specifies whether the embedded Tweet should automatically expand images which were uploaded via {https://dev.twitter.com/rest/reference/post/statuses/update_with_media POST statuses/update_with_media}. When set to either true, t or 1 images will not be expanded. Defaults to false. # @option options [Boolean, String, Integer] :hide_thread Specifies whether the embedded Tweet should automatically show the original message in the case that the embedded Tweet is a reply. When set to either true, t or 1 the original Tweet will not be shown. Defaults to false. # @option options [Boolean, String, Integer] :omit_script Specifies whether the embedded Tweet HTML should include a `