### Create Test Users Source: https://context7.com/arsduo/koala/llms.txt Generate test user accounts. You can specify whether the app should be installed and the permissions to grant. ```ruby user = @test_users.create(true, ["public_profile", "email", "user_photos"]) ``` ```ruby guest = @test_users.create(false) ``` -------------------------------- ### Create a Test User Source: https://github.com/arsduo/koala/blob/master/readme.md Creates a new test user with specified installation status and permissions. Returns the test user's data, including their access token. ```ruby user = @test_users.create(is_app_installed, desired_permissions) ``` -------------------------------- ### Install Koala Gem Source: https://github.com/arsduo/koala/blob/master/readme.md Add the Koala gem to your project's Gemfile for Bundler, or install it directly using the gem command. ```ruby gem "koala" ``` ```bash [sudo|rvm] gem install koala ``` -------------------------------- ### Get Access Token from Code Source: https://context7.com/arsduo/koala/llms.txt Obtain an access token by exchanging an authorization code. Ensure you have the necessary OAuth object initialized. ```ruby access_token = @oauth.get_access_token(code) ``` -------------------------------- ### Fetch and Parse Access Token Source: https://github.com/arsduo/koala/wiki/OAuth Methods to fetch the raw token string and parse it into a usable hash, or directly get the access token. ```APIDOC ## Fetch and Parse Access Token ### Description Provides methods to obtain and process the access token and its expiration information. ### Methods 1. **`@oauth.fetch_token_string(code)`** - **Description**: Fetches the raw access token string from the OAuth server. - **Parameters**: - **code** (string) - The authorization code. - **Response**: A string in the format `"access_token=...&expires=..."`. 2. **`@oauth.parse_token_string(token_string)`** - **Description**: Parses the raw token string into a hash. - **Parameters**: - **token_string** (string) - The raw token string obtained from `fetch_token_string`. - **Response**: A hash containing `"access_token"` and `"expires"`. 3. **`@oauth.get_access_token(code)`** - **Description**: Directly retrieves the access token string. - **Parameters**: - **code** (string) - The authorization code. - **Response**: The access token string. 4. **`@oauth.get_access_token_info(code)`** - **Description**: Retrieves the access token and its expiration information as a hash. - **Parameters**: - **code** (string) - The authorization code. - **Response**: A hash containing `"access_token"` and `"expires"`. ### Request Example ```ruby # Fetch and parse result = @oauth.fetch_token_string("AUTHORIZATION_CODE") parsed_token = @oauth.parse_token_string(result) # Get access token directly access_token = @oauth.get_access_token("AUTHORIZATION_CODE") # Get token info token_info = @oauth.get_access_token_info("AUTHORIZATION_CODE") ``` ``` -------------------------------- ### Create Test User Network Source: https://context7.com/arsduo/koala/llms.txt Efficiently create a network of test users where all users are friends with each other, simplifying the setup for social graph testing. ```ruby network = @test_users.create_network(5, true, "public_profile,email") ``` -------------------------------- ### Get Page Data with Next Page Parameters Source: https://github.com/arsduo/koala/blob/master/readme.md Retrieves the next page of data from the feed using the provided next page parameters. ```ruby next_page_params = feed.next_page_params page = @graph.get_page(next_page_params) ``` -------------------------------- ### Get Test User Graph API Instance Source: https://github.com/arsduo/koala/blob/master/readme.md Obtain a Graph API instance for a test user using their access token. ```APIDOC ## Get Test User Graph API Instance ### Description Instantiate a Koala Graph API object using the access token of a previously created test user. ### Method `Koala::Facebook::API.new` ### Endpoint N/A (Internal library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **access_token** (string) - Required - The access token of the test user. ### Request Example ```ruby # Assuming user_data is the hash returned from @test_users.create user_graph_api = Koala::Facebook::API.new(user_data["access_token"]) ``` ``` -------------------------------- ### Get Application Access Token Source: https://github.com/arsduo/koala/blob/master/readme.md Obtains an application access token, which can be used without a user session for specific requests like subscriptions. ```ruby @oauth = Koala::Facebook::OAuth.new(app_id, app_secret, callback_url) @oauth.get_app_access_token ``` -------------------------------- ### Get Access Token Directly Source: https://github.com/arsduo/koala/wiki/OAuth Convenience methods to directly obtain the access token or a hash containing the access token and its expiration information. ```ruby @oauth.get_access_token(code) # => #{access_token} ``` ```ruby @oauth.get_access_token_info(code) # => {"expires" => #{seconds_from_now}, "access_token" => #{access_token}} ``` -------------------------------- ### Get App Access Token Source: https://context7.com/arsduo/koala/llms.txt Retrieve an app-specific access token, which does not require user authorization and is useful for app-level operations. ```ruby app_token = @oauth.get_app_access_token ``` -------------------------------- ### Get Picture in a Batch Request Source: https://github.com/arsduo/koala/wiki/Batch-requests Include a `get_picture` call within a batch request. The result will be an array containing the picture data. ```ruby it 'should be able to make a get_picture call inside of a batch' do pictures = @api.batch do |batch_api| batch_api.get_picture('me') end pictures.first.should_not be_empty end ``` -------------------------------- ### Get Page Access Token Source: https://context7.com/arsduo/koala/llms.txt Fetch a page's access token using `get_page_access_token`. The user must have `manage_pages` or `pages_manage_posts` permission. ```ruby # Get the page token (user must have manage_pages / pages_manage_posts permission) page_token = @graph.get_page_access_token(page_id) # => "EAABsbCS..." # Now create an API client that acts as the page page_api = Koala::Facebook::API.new(page_token) page_api.put_wall_post("Official announcement from our page!") page_api.put_picture("/path/to/banner.jpg", "image/jpeg", { message: "New banner!" }) ``` -------------------------------- ### Get App Access Token Source: https://github.com/arsduo/koala/blob/master/readme.md Obtain an application access token for making requests on behalf of the app itself, without user involvement. ```APIDOC ## Get App Access Token ### Description Generate an application access token, which is necessary for certain API requests like subscriptions that do not require a user session. ### Method `Koala::Facebook::OAuth#get_app_access_token` ### Endpoint N/A (Internal library method) ### Request Example ```ruby @oauth = Koala::Facebook::OAuth.new(app_id, app_secret, callback_url) app_token = @oauth.get_app_access_token ``` ``` -------------------------------- ### Get Application Access Token with Koala Source: https://github.com/arsduo/koala/wiki/OAuth Obtain an application access token for sessionless activities and managing realtime updates. This token does not expire. ```ruby @oauth = Koala::Facebook::OAuth.new(app_id, app_secret) @oauth.get_app_access_token # => #{app_access_token} ``` -------------------------------- ### Write to a Connection with `API#put_connections` Source: https://context7.com/arsduo/koala/llms.txt Post data to a Graph API connection, such as creating a post on a user's feed or performing an Open Graph action. This requires an access token with appropriate publish permissions. An example demonstrates error handling for write operations without a token. ```ruby # Post to the user's feed result = @graph.put_connections("me", "feed", message: "Hello from Koala!", link: "https://github.com/arsduo/koala" ) ``` ```ruby # Post to an Open Graph action @graph.put_connections("me", "myapp:read", book: "https://myapp.com/books/123") ``` ```ruby # Error: write without a token raises immediately begin @graph.put_connections("me", "feed", message: "test") rescue Koala::Facebook::AuthenticationError => e puts e.message # => "Write operations require an access token" end ``` -------------------------------- ### Post to a Wall with `API#put_wall_post` Source: https://context7.com/arsduo/koala/llms.txt A convenience method for posting plain text or rich attachments to a user's or page's wall/feed. It simplifies the process of creating wall posts. Examples show posting to the current user's wall, including rich media, and posting to another user's wall or a managed page using a page access token. ```ruby # Plain text post to current user's wall @graph.put_wall_post("Just shipped a new feature!") ``` ```ruby # Rich attachment post @graph.put_wall_post("Check out our new product!", { "name" => "Koala Ruby SDK", "link" => "https://github.com/arsduo/koala", "caption" => "A lightweight Facebook library", "description" => "Supports Graph API, OAuth, batch requests, and more.", "picture" => "https://example.com/koala_thumbnail.png" }) ``` ```ruby # Post to another user's wall (requires permission) @graph.put_wall_post("Happy Birthday!", {}, target_user_id) ``` ```ruby # Post to a page you manage page_token = @graph.get_page_access_token(page_id) page_api = Koala::Facebook::API.new(page_token) page_api.put_wall_post("Announcing our summer sale!") ``` -------------------------------- ### Get Multiple Objects in a Batch Request Source: https://github.com/arsduo/koala/wiki/Batch-requests Use the `batch` method to retrieve multiple objects from the API in a single call. This is useful for fetching related data efficiently. ```ruby before :each do @api = Koala::Facebook::API.new(my_access_token) end it "can get two results at once" do me, facebook = @api.batch do |batch_api| batch_api.get_object('me') batch_api.get_object('facebook') end me['id'].should_not be_nil facebook['id'].should_not be_nil end ``` -------------------------------- ### Retrieve Managed Pages or Page Access Token Source: https://github.com/arsduo/koala/wiki/Acting-as-a-Page Get a list of all pages managed by the user or a specific page access token using the user's Graph API object. ```ruby # retrieve collection for all your managed pages: returns collection of hashes with page id, name, category, access token and permissions pages = @user_graph.get_connections('me', 'accounts') # get access token for first page first_page_token = pages.first['access_token'] # or: retrieve access_token for a given page_id page_token = @user_graph.get_page_access_token(page_id) ``` -------------------------------- ### Get Graph API Instance for a Test User Source: https://github.com/arsduo/koala/blob/master/readme.md Creates a Koala Graph API instance using the access token of a test user, allowing interaction with the Graph API on behalf of that test user. ```ruby user_graph_api = Koala::Facebook::API.new(user["access_token"]) ``` -------------------------------- ### Initialize OAuth Client Source: https://context7.com/arsduo/koala/llms.txt Set up the `Koala::Facebook::OAuth` client with your App ID, App Secret, and a callback URL. ```ruby @oauth = Koala::Facebook::OAuth.new( ENV["FB_APP_ID"], ENV["FB_APP_SECRET"], "https://myapp.com/auth/facebook/callback" ) ``` -------------------------------- ### Get Picture Metadata with `API#get_picture_data` Source: https://context7.com/arsduo/koala/llms.txt Retrieve the picture URL and metadata for a user or object without triggering a redirect. This is useful for getting the picture URL directly. You can specify the desired picture size (e.g., 'large', 'normal') and retrieve data for users or pages. ```ruby # Get picture data hash (avoids 302 redirect) pic = @graph.get_picture_data("me") # => {"data"=>{"is_silhouette"=>false, "url"=>"https://..."}} ``` ```ruby # Specify picture size pic = @graph.get_picture_data("me", type: "large") url = pic.dig("data", "url") # => "https://fbcdn-profile-a.akamaihd.net/..." ``` ```ruby # Get a page's picture pic = @graph.get_picture_data("FacebookForDevelopers", type: "normal") ``` -------------------------------- ### API#debug_token Source: https://context7.com/arsduo/koala/llms.txt Inspects an access token to get its metadata (scopes, expiry, associated app/user). ```APIDOC ## `API#debug_token` — Inspect an Access Token Inspects an access token to get its metadata (scopes, expiry, associated app/user). ```ruby # Use an app token or developer token in the API, pass any token to inspect app_graph = Koala::Facebook::API.new(Koala::Facebook::OAuth.new( ENV["FB_APP_ID"], ENV["FB_APP_SECRET"] ).get_app_access_token) info = app_graph.debug_token(user_access_token) # => { # "data" => { # "app_id" => "123456", # "type" => "USER", # "is_valid" => true, # "expires_at" => 1700000000, # "scopes" => ["public_profile", "email", "user_photos"], # "user_id" => "987654321" # } # } puts info.dig("data", "is_valid") # => true puts info.dig("data", "scopes") # => ["public_profile", "email", "user_photos"] ``` ``` -------------------------------- ### Initialize Real-Time Updates Subscription Source: https://context7.com/arsduo/koala/llms.txt Set up the `RealtimeUpdates` object with your app's credentials. You can optionally provide an app access token directly. ```ruby @updates = Koala::Facebook::RealtimeUpdates.new( app_id: ENV["FB_APP_ID"], secret: ENV["FB_APP_SECRET"] # app_access_token: "..." # optionally provide directly ) ``` -------------------------------- ### Initialize OAuth Helper Source: https://github.com/arsduo/koala/wiki/OAuth Create an instance of the Koala OAuth helper with your application's API key, secret, and optional callback URL. ```APIDOC ## Initialize OAuth Helper ### Description Instantiate the `Koala::Facebook::OAuth` class with your application credentials. ### Method `Koala::Facebook::OAuth.new(api_key, app_secret, callback_url)` ### Parameters - **api_key** (string) - Your application's API key. - **app_secret** (string) - Your application's secret code. - **callback_url** (string, optional) - The URL to redirect to after authentication. ### Request Example ```ruby @oauth = Koala::Facebook::OAuth.new("your_app_id", "your_secret_code", "http://yourdomain.com/callback") ``` ### Response An instance of `Koala::Facebook::OAuth`. ``` -------------------------------- ### Basic Photo and Video Uploads Source: https://github.com/arsduo/koala/wiki/Uploading-Photos-and-Videos Use `put_picture` for photos and `put_video` for videos. These methods accept various argument types including file paths, file objects, and Rails/Sinatra uploaded file objects. ```ruby @graph = Koala::Facebook::API.new(access_token) # You can supply several different arguments to put_picture and put_video: # 1) Path to a photo @graph.put_picture(path_to_my_file) # 2) Upload a file directly @graph.put_picture(file_class_object) # 3) Rails 3 file uploads (ActionDispatch::Http::UploadedFile) @graph.put_picture(params[:file]) # 4) Sinatra file uploads (Hash) @graph.put_picture(file_hash) # 5) StringIO (1.2beta3) @graph.put_picture(io, content_type) # put_video has the same syntax options available @graph.put_video(path_to_my_video) @graph.put_video(file_class_object) @graph.put_video(params[:file]) @graph.put_video(file_hash) ``` -------------------------------- ### Run Live Tests Against Facebook Beta Tier Source: https://github.com/arsduo/koala/blob/master/readme.md Perform live tests against Facebook's beta tier by setting both LIVE and BETA environment variables. This is useful for testing against pre-release API versions. ```bash LIVE=true BETA=true bundle exec rake spec ``` -------------------------------- ### Run Live Tests Against Facebook Servers Source: https://github.com/arsduo/koala/blob/master/readme.md Execute live tests against Facebook's servers by setting the LIVE environment variable. This allows for testing against actual API endpoints. ```bash LIVE=true bundle exec rake spec ``` -------------------------------- ### Configuring Faraday Adapter for IO Uploads Source: https://github.com/arsduo/koala/wiki/Uploading-Photos-and-Videos When uploading IO objects like StringIO, ensure your Faraday adapter is set correctly. The default adapter is often sufficient. ```ruby Faraday.default_adapter = :net_http # or whichever library you want ``` -------------------------------- ### Run Unit Tests Source: https://github.com/arsduo/koala/blob/master/readme.md Execute the project's unit tests using Rake. These tests run against mock responses by default, ensuring they are ready to run out of the box. ```bash bundle exec rake spec ``` -------------------------------- ### Initialize Test User Management Source: https://context7.com/arsduo/koala/llms.txt Set up the `TestUsers` object with your app's ID and secret to manage test accounts for development and testing purposes. ```ruby @test_users = Koala::Facebook::TestUsers.new( app_id: ENV["FB_APP_ID"], secret: ENV["FB_APP_SECRET"] ) ``` -------------------------------- ### HTTP Service Configuration Source: https://context7.com/arsduo/koala/llms.txt Configure global HTTP options, proxies, timeouts, and custom Faraday middleware for Koala's HTTP client. ```APIDOC ## HTTP Service Configuration — Faraday Middleware Koala uses Faraday for HTTP, giving full control over connection options, SSL, proxies, timeouts, and custom middleware stacks. ```ruby # Set global HTTP options (SSL, proxy, timeouts) Koala.http_service.http_options = { ssl: { ca_path: "/etc/ssl/certs" }, proxy: "http://proxy.mycompany.com:3128", request: { timeout: 30, open_timeout: 5 } } # Per-request options (merged with global options) profile = @graph.get_object("me", {}, request: { timeout: 10 }) feed = @graph.get_connections("me", "feed", {}, ssl: { verify: false }) # Custom Faraday middleware stack (e.g. add logging) require 'faraday/detailed_logger' Koala.http_service.faraday_middleware = proc do |builder| builder.response :detailed_logger, Rails.logger builder.request :multipart builder.request :url_encoded builder.adapter Faraday.default_adapter end ``` ``` -------------------------------- ### Batch API Calls Source: https://github.com/arsduo/koala/blob/master/readme.md Demonstrates how to make multiple API calls efficiently using Facebook's batch API. ```APIDOC ## Batch API Calls ### Description Execute multiple Graph API requests in a single network call for improved performance. ### Method Ruby block syntax using `@graph.batch` ### Endpoint N/A (Internal library method) ### Request Example ```ruby @graph.batch do |batch_api| batch_api.get_object('me') batch_api.put_wall_post('Making a post in a batch.') end ``` ### Response Returns an array of results corresponding to each call within the batch. ``` -------------------------------- ### Initialize Koala OAuth Helper Source: https://github.com/arsduo/koala/wiki/OAuth Create an OAuth helper instance with your application's API key, secret, and an optional callback URL. This object is used for all subsequent OAuth operations. ```ruby @oauth = Koala::Facebook::OAuth.new(api_key, app_secret, callback_url) ``` -------------------------------- ### `Koala::Facebook::API.new` — Create an API Client Source: https://context7.com/arsduo/koala/llms.txt Instantiate a Graph API client. You can provide an access token and optional app secret for secure signing. If no arguments are provided, it uses globally configured credentials. ```APIDOC ## `Koala::Facebook::API.new` — Create an API Client Instantiate a Graph API client with an access token and optional app secret. Providing the app secret enables automatic `appsecret_proof` signing on every request for added security. ```ruby require 'koala' # Basic client (uses globally configured token if none provided) @graph = Koala::Facebook::API.new(ENV["FB_USER_ACCESS_TOKEN"]) # Secure client with appsecret_proof signing (recommended for server-side apps) @graph = Koala::Facebook::API.new(ENV["FB_USER_ACCESS_TOKEN"], ENV["FB_APP_SECRET"]) # Client with per-instance rate limit hook @graph = Koala::Facebook::API.new( ENV["FB_USER_ACCESS_TOKEN"], ENV["FB_APP_SECRET"], ->(limits) { Datadog.gauge("fb.rate_limit", limits.dig("x-app-usage", "call_count") || 0) } ) # Client using globally configured credentials (no arguments needed) Koala.configure { |c| c.access_token = ENV["FB_TOKEN"]; c.app_secret = ENV["FB_SECRET"] } @graph = Koala::Facebook::API.new ``` ``` -------------------------------- ### Authenticate as a User Source: https://github.com/arsduo/koala/wiki/Acting-as-a-Page Initialize the Koala API with a user access token that has the `manage_pages` permission. ```ruby @user_graph = Koala::Facebook::API.new(user_access_token) ``` -------------------------------- ### Get User Info from Cookies Source: https://context7.com/arsduo/koala/llms.txt Extract user information, including access token and user ID, directly from Facebook JS SDK cookies. ```ruby user_info = @oauth.get_user_info_from_cookies(cookies) ``` -------------------------------- ### List and Unsubscribe from Real-Time Updates Source: https://context7.com/arsduo/koala/llms.txt Manage your real-time update subscriptions. `list_subscriptions` shows active subscriptions, while `unsubscribe` can remove specific subscriptions or all of them. ```ruby subs = @updates.list_subscriptions ``` ```ruby @updates.unsubscribe("user") ``` ```ruby @updates.unsubscribe ``` -------------------------------- ### Subscribe to Real-Time Updates Source: https://context7.com/arsduo/koala/llms.txt Register your application to receive push notifications for changes to specified fields of a given object type. Requires a callback URL and a secret verification token. ```ruby @updates.subscribe( "user", # object type "first_name,last_name,email", # fields to watch "https://myapp.com/fb/webhooks", # your callback URL "my_secret_verify_token" # token you verify against ) ``` -------------------------------- ### Batch Request with Different HTTP Methods Source: https://github.com/arsduo/koala/wiki/Batch-requests Demonstrates using different HTTP methods (POST, DELETE) within a single batch request. This allows for complex operations like creating and then deleting a resource. ```ruby it "handles different request methods" do result = @api.put_wall_post("Hello, world, from the test suite batch API!") wall_post = result["id"] wall_post, koppel = @api.batch do |batch_api| batch_api.put_like(wall_post) batch_api.delete_object(wall_post) end end ``` -------------------------------- ### Mixed API Calls in a Batch Request Source: https://github.com/arsduo/koala/wiki/Batch-requests Combine different types of API calls, such as getting user info and connections, within a single batch request. Ensure the expected data types are handled. ```ruby it 'should be able to make mixed calls inside of a batch' do me, friends = @api.batch do |batch_api| batch_api.get_object('me') batch_api.get_connections('me', 'friends') end me['id'].should_not be_nil friends.should be_an(Array) end ``` -------------------------------- ### Fetch Graph API Objects and Connections Source: https://github.com/arsduo/koala/blob/master/readme.md Use the Koala Graph API to retrieve data from Facebook. This includes getting user profiles, connections (like friends), and other objects. The results are returned as Hashes or GraphCollection objects for paginated data. ```ruby profile = @graph.get_object("me") friends = @graph.get_connections("me", "friends") ``` ```ruby # Three-part queries are easy too! @graph.get_connections("me", "mutualfriends/#{friend_id}") ``` -------------------------------- ### Make API Calls as a Page Source: https://github.com/arsduo/koala/wiki/Acting-as-a-Page Perform various actions as the authenticated page, such as retrieving page information, posting to the wall, or uploading pictures. Ensure necessary permissions like `publish_pages` are granted for posting actions. ```ruby @page_graph.get_object('me') # I'm a page @page_graph.get_connection('me', 'feed') # the page's wall @page_graph.put_wall_post('post on page wall') # post as page, requires new publish_pages permission @page_graph.put_connections('me', 'feed', :message => message, :link => link_url) #post as link to page @page_graph.put_picture(picture_url, {:message => "hello"}, page_id) #post as picture with caption ``` -------------------------------- ### Initialize TestUsers Source: https://github.com/arsduo/koala/blob/master/readme.md Initializes the TestUsers class for creating and managing test user accounts for application testing. ```ruby @test_users = Koala::Facebook::TestUsers.new(app_id: id, secret: secret) ``` -------------------------------- ### `API#get_object` — Fetch a Single Graph Object Source: https://context7.com/arsduo/koala/llms.txt Retrieves a single Facebook object by its ID or alias. You can specify fields to retrieve and use a post-processing block for custom data extraction. It also supports overriding the API version for a specific call and includes error handling examples. ```APIDOC ## `API#get_object` — Fetch a Single Graph Object Retrieves any Facebook object by ID or alias. Accepts an optional hash of Graph API fields/parameters and an optional post-processing block. ```ruby # Fetch the current user's full profile profile = @graph.get_object("me") # => {"id"=>"123456789", "name"=>"Jane Doe", "email"=>"jane@example.com"} # Request specific fields only profile = @graph.get_object("me", fields: "id,name,email,picture") # => {"id"=>"123456789", "name"=>"Jane Doe", "email"=>"jane@example.com", "picture"=>{...}} # Use a post-processing block to extract just what you need education = @graph.get_object("me", fields: "education") { |data| data["education"] } # => [{"school"=>{"name"=>"MIT"}, "type"=>"College"}, ...] # Fetch a page by its name alias page = @graph.get_object("FacebookForDevelopers") # => {"id"=>"...", "name"=>"Facebook for Developers", "fan_count"=>... # Override the API version for a single call user = @graph.get_object("me", {}, api_version: "v19.0") # Error handling begin obj = @graph.get_object("invalid_id_xyz") rescue Koala::Facebook::ClientError => e puts "Client error #{e.fb_error_code}: #{e.fb_error_message}" rescue Koala::Facebook::ServerError => e puts "Facebook server error: #{e.http_status}" end ``` ``` -------------------------------- ### Post Binary Files in Batch Requests Source: https://github.com/arsduo/koala/wiki/Batch-requests Upload binary files, such as images, as part of a batch request. Ensure the file is opened correctly and passed to the `put_picture` method. ```ruby it "posts binary files" do file = File.open(File.join(File.dirname(__FILE__), "..", "fixtures", "beach.jpg")) Koala::Facebook::BatchOperation.instance_variable_set(:@identifier, 0) result = @api.batch do |batch_api| batch_api.put_picture(file) end @temporary_object_id = result[0]["id"] @temporary_object_id.should_not be_nil end ``` -------------------------------- ### Global Configuration Source: https://context7.com/arsduo/koala/llms.txt Configure application-wide defaults for Koala, such as access tokens, app ID, and callback URLs, to avoid repeating settings on every API call. ```APIDOC ## Global Configuration Set application-wide defaults so credentials and settings don't need to be repeated on every API call. ```ruby # config/initializers/koala.rb (Rails) or at app startup Koala.configure do |config| config.access_token = ENV["FB_ACCESS_TOKEN"] config.app_access_token = ENV["FB_APP_ACCESS_TOKEN"] config.app_id = ENV["FB_APP_ID"] config.app_secret = ENV["FB_APP_SECRET"] config.oauth_callback_url = "https://myapp.com/auth/facebook/callback" config.api_version = "v19.0" # default Graph API version config.preserve_form_arguments = false # set true for Marketing/Ads API config.mask_tokens = true # mask tokens in debug logs (default) # Optional: react to rate limit headers on every response config.rate_limit_hook = ->(limits) { Rails.logger.warn("FB app usage: #{limits['x-app-usage']}") if limits['x-app-usage'] Rails.logger.warn("FB ad usage: #{limits['x-ad-account-usage']}") if limits['x-ad-account-usage'] } end ``` ``` -------------------------------- ### Multiple Binary File Uploads in Batch Source: https://github.com/arsduo/koala/wiki/Batch-requests Upload multiple binary files within a single batch request. Each `put_picture` call will be processed as a separate operation in the batch. ```ruby it "posts binary files with multiple requests" do file = File.open(File.join(File.dirname(__FILE__), "..", "fixtures", "beach.jpg")) Koala::Facebook::BatchOperation.instance_variable_set(:@identifier, 0) results = @api.batch do |batch_api| batch_api.put_picture(file) batch_api.put_picture(file, {}, "koppel") end results[0]["id"].should_not be_nil results[1]["id"].should_not be_nil end ``` -------------------------------- ### List Current Real-time Subscriptions Source: https://github.com/arsduo/koala/blob/master/readme.md Retrieves an array of current real-time subscriptions, with each subscription represented as a hash. ```ruby @updates.list_subscriptions ``` -------------------------------- ### Uploading Photos and Videos Source: https://github.com/arsduo/koala/wiki/Uploading-Photos-and-Videos The `put_picture` and `put_video` methods allow for uploading media files. They support various input formats for the file, including file paths, file objects, Rails/Sinatra uploads, and StringIO objects. An optional content type can be provided, and additional Facebook API arguments can be passed. ```APIDOC ## put_picture and put_video ### Description Methods to upload photos and videos to Facebook. ### Method POST (implied by `put_` prefix and API interaction) ### Endpoint `/me/photos` or `/me/videos` (implied by Facebook Graph API conventions) ### Parameters #### Path Parameters - **user_or_album_id** (string) - Optional - The ID of the user or album to upload to. Defaults to 'me'. #### Query Parameters None explicitly documented for the core upload, but additional parameters can be passed in the `facebook_arguments` hash. #### Request Body - **file** (various types) - Required - The media file to upload. Can be a file path, file object, Rails UploadedFile, Sinatra file hash, or StringIO object. - **content_type** (string) - Optional - The MIME type of the file. If not provided, it will be auto-detected. - **facebook_arguments** (object) - Optional - A hash containing additional parameters like `caption` for photos or `title` for videos. - **http_options** (object) - Optional - HTTP-specific options. ### Request Example ```ruby @graph = Koala::Facebook::API.new(access_token) # Uploading a photo from a file path with a caption @graph.put_picture("path/to/my/photo.jpg", nil, { "caption" => "A beautiful sunset" }, "me") # Uploading a video from a file object with a title @graph.put_video(file_object, nil, { "title" => "My vacation video" }, "me") ``` ### Response #### Success Response (200 OK) - **id** (string) - The ID of the uploaded photo or video. ``` -------------------------------- ### Initialize RealtimeUpdates Source: https://github.com/arsduo/koala/blob/master/readme.md Initializes the RealtimeUpdates class for managing real-time subscriptions to Facebook Graph API updates. ```ruby @updates = Koala::Facebook::RealtimeUpdates.new(app_id: app_id, secret: secret) ``` -------------------------------- ### Create Test User Source: https://github.com/arsduo/koala/blob/master/readme.md Generate a test user account for development and testing purposes. ```APIDOC ## Create Test User ### Description Create a new test user account that can be used to simulate user interactions with your application. ### Method `Koala::Facebook::TestUsers#create` ### Endpoint N/A (Internal library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **is_app_installed** (boolean) - Optional - Whether the test user should have the app installed. - **desired_permissions** (array of strings) - Optional - Permissions to grant to the test user. ### Request Example ```ruby @test_users = Koala::Facebook::TestUsers.new(app_id: id, secret: secret) user_data = @test_users.create(true, ['email', 'publish_actions']) # user_data contains details of the created test user, including access token. ``` ``` -------------------------------- ### Configure Koala HTTPService for mockfacebook Source: https://github.com/arsduo/koala/wiki/Using-Koala-with-mockfacebook Add this snippet to your spec_helper to direct Koala's HTTPService to use mockfacebook running on localhost:8000. ```ruby module Koala module HTTPService def self.server(options = {}) "http://localhost:8000" end end end ``` -------------------------------- ### Create Koala Facebook API Client Source: https://context7.com/arsduo/koala/llms.txt Instantiate a Graph API client. Providing an app secret enables automatic `appsecret_proof` signing for enhanced security. You can use globally configured credentials if no arguments are provided. ```ruby require 'koala' # Basic client (uses globally configured token if none provided) @graph = Koala::Facebook::API.new(ENV["FB_USER_ACCESS_TOKEN"]) # Secure client with appsecret_proof signing (recommended for server-side apps) @graph = Koala::Facebook::API.new(ENV["FB_USER_ACCESS_TOKEN"], ENV["FB_APP_SECRET"]) # Client with per-instance rate limit hook @graph = Koala::Facebook::API.new( ENV["FB_USER_ACCESS_TOKEN"], ENV["FB_APP_SECRET"], ->(limits) { Datadog.gauge("fb.rate_limit", limits.dig("x-app-usage", "call_count") || 0) } ) # Client using globally configured credentials (no arguments needed) Koala.configure { |c| c.access_token = ENV["FB_TOKEN"]; c.app_secret = ENV["FB_SECRET"] } @graph = Koala::Facebook::API.new ``` -------------------------------- ### Configure Global HTTP Options Source: https://context7.com/arsduo/koala/llms.txt Set global HTTP connection options for Koala, including SSL certificates, proxy servers, and request timeouts. These settings apply to all subsequent requests unless overridden. ```ruby Koala.http_service.http_options = { ssl: { ca_path: "/etc/ssl/certs" }, proxy: "http://proxy.mycompany.com:3128", request: { timeout: 30, open_timeout: 5 } } ``` -------------------------------- ### Upload Media with `API#put_picture` and `API#put_video` Source: https://context7.com/arsduo/koala/llms.txt Upload photos or videos to Facebook using `put_picture` or `put_video`. These methods accept various input formats including file paths, IO objects, URLs, and Rack-style uploaded files. You can specify content types and add messages or other parameters. Uploading to a specific page requires a page access token. ```ruby # Upload from a local file path result = @graph.put_picture("/path/to/photo.jpg", "image/jpeg", { message: "Beach day!" }) # => {"id"=>"9876543210"} ``` ```ruby # Upload from a URL (no content-type needed) result = @graph.put_picture("https://example.com/image.png", { message: "From the web" }) ``` ```ruby # Upload to a specific page (using page access token) page_api.put_picture("/path/to/promo.jpg", "image/jpeg", { message: "New product photo!", published: true }, page_id ) ``` ```ruby # Upload a video (same interface as put_picture) result = @graph.put_video("/path/to/clip.mp4", "video/mp4", { title: "My Video", description: "A short clip" } ) # => {"id"=>"1122334455"} ``` ```ruby # Upload from a Rack/Rails params hash # result = @graph.put_picture(params[:photo], { message: "Uploaded from form" }) ``` -------------------------------- ### Basic Batch API Calls Source: https://context7.com/arsduo/koala/llms.txt Execute multiple Graph API calls in one request using `batch`. Results are returned in the order of the calls. ```ruby # Basic batch: returns array of results in call order results = @graph.batch do |b| b.get_object("me") b.get_connections("me", "feed", limit: 5) b.get_object("FacebookForDevelopers", fields: "name,fan_count") end me, feed, fb4dev = results puts me["name"] # => "Jane Doe" puts feed.first["id"] # => "123_456" puts fb4dev["fan_count"] # => 42000 ``` -------------------------------- ### Batch Request with Different Access Tokens Source: https://github.com/arsduo/koala/wiki/Batch-requests Make batch requests using different access tokens for different calls. This is useful when interacting with resources requiring distinct permissions. ```ruby it "should handle requests for two different tokens" do me, insights = @api.batch do |batch_api| batch_api.get_object('me') batch_api.get_connections(@app_id, 'insights', {}, {"access_token" => @app_api.access_token}) end me['id'].should_not be_nil insights.should be_an(Array) end ``` -------------------------------- ### Verify Webhook Challenge Source: https://context7.com/arsduo/koala/llms.txt Implement webhook verification by responding to Facebook's challenge request. This method ensures that your callback URL is valid and configured correctly. ```ruby challenge = Koala::Facebook::RealtimeUpdates.meet_challenge( params, "my_secret_verify_token" ) if challenge render plain: challenge, status: 200 else head :forbidden end ``` -------------------------------- ### Configure SSL Certificate for HTTP Requests Source: https://github.com/arsduo/koala/blob/master/readme.md Set a global SSL certificate path to resolve Net::HTTP errors when making HTTP requests. This configuration is applied to the Koala HTTP service. ```ruby Koala.http_service.http_options = { ssl: { ca_path: "/etc/ssl/certs" } } ``` -------------------------------- ### List Realtime Subscriptions Source: https://github.com/arsduo/koala/blob/master/readme.md Retrieve a list of all current real-time update subscriptions configured for the application. ```APIDOC ## List Realtime Subscriptions ### Description Retrieve an array of all current real-time update subscriptions. ### Method `Koala::Facebook::RealtimeUpdates#list_subscriptions` ### Endpoint N/A (Internal library method) ### Response Returns an array of hashes, where each hash represents a subscription. ``` -------------------------------- ### OAuth Methods Source: https://context7.com/arsduo/koala/llms.txt Methods for handling OAuth flows, obtaining access tokens, and parsing signed requests. ```APIDOC ## OAuth Methods ### Get Access Token Obtain an access token using an authorization code. ```ruby access_token = @oauth.get_access_token(code) ``` ### Exchange Access Token Extend a short-lived access token to a long-lived one (60 days). ```ruby long_lived = @oauth.exchange_access_token(short_lived_token) long_lived_info = @oauth.exchange_access_token_info(short_lived_token) ``` ### Get App Access Token Obtain an app-specific access token without requiring user interaction. ```ruby app_token = @oauth.get_app_access_token ``` ### Parse Signed Request Parse a signed request, typically from a canvas app or cookie. ```ruby request_data = @oauth.parse_signed_request(params["signed_request"]) ``` ### Get User Info from Cookies Extract user information from Facebook JS SDK cookies. ```ruby user_info = @oauth.get_user_info_from_cookies(cookies) ``` ### URL for Dialog Build a URL for various Facebook dialogs (e.g., feed, friends). ```ruby feed_dialog_url = @oauth.url_for_dialog("feed", link: "https://myapp.com", redirect_uri: "https://myapp.com/after-share" ) ``` ``` -------------------------------- ### Like an Object Source: https://context7.com/arsduo/koala/llms.txt Use `put_like` to like a Facebook object. Returns true on success. ```ruby # Like an object @graph.put_like(post_id) # => true ``` -------------------------------- ### API#put_comment / API#put_like / API#delete_like Source: https://context7.com/arsduo/koala/llms.txt Shorthand methods for common write operations: commenting on an object, liking it, and unliking it. ```APIDOC ## `API#put_comment` / `API#put_like` / `API#delete_like` — Convenience Write Methods Shorthand methods for common write operations: commenting on an object, liking it, and unliking it. ```ruby # Comment on a post result = @graph.put_comment(post_id, "Great post!") # => {"id"=>"123_456"} # Like an object @graph.put_like(post_id) # => true # Unlike an object @graph.delete_like(post_id) # => true # Chained usage @graph.put_comment(post_id, "Congrats!") && @graph.put_like(post_id) ``` ``` -------------------------------- ### Initialize Koala Graph API Source: https://github.com/arsduo/koala/blob/master/readme.md Create an instance of the Koala Facebook API. An access token is required, which can be obtained from the Facebook Graph API Explorer. You can also set default access tokens and app secrets globally. ```ruby require 'koala' # access_token and other values aren't required if you set the defaults as described above @graph = Koala::Facebook::API.new(access_token) ``` ```ruby # For extra security (recommended), you can provide an appsecret parameter, # tying your access tokens to your app secret. # (See https://developers.facebook.com/docs/reference/api/securing-graph-api/ # You may need to turn on 'Require proof on all calls' in the advanced section # of your app's settings when doing this. @graph = Koala::Facebook::API.new(access_token, app_secret) ``` -------------------------------- ### Post to Facebook Wall using Graph API Source: https://github.com/arsduo/koala/blob/master/readme.md Publish content to a user's feed or wall using the `put_connections` method. Ensure you have the necessary permissions for posting. ```ruby @graph.put_connections("me", "feed", message: "I am writing on my wall!") ``` -------------------------------- ### Handle Realtime Verification Challenge Source: https://github.com/arsduo/koala/blob/master/readme.md Respond to Facebook's verification request for real-time update callback URLs. ```APIDOC ## Handle Realtime Verification Challenge ### Description Provide a static method to handle the verification challenge sent by Facebook when setting up a real-time update callback URL. ### Method `Koala::Facebook::RealtimeUpdates.meet_challenge` ### Endpoint N/A (Internal library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (Hash) - Required - The parameters received from Facebook's verification request. - **your_verify_token** (string) - Required - The verify token configured for the subscription. ### Response Returns the `hub.challenge` parameter if the verify token matches, otherwise handles the verification failure. ### Request Example ```ruby # Assuming params is the hash of request parameters from Facebook response = Koala::Facebook::RealtimeUpdates.meet_challenge(params, your_verify_token) ``` ``` -------------------------------- ### List and Befriend Test Users Source: https://context7.com/arsduo/koala/llms.txt Retrieve a list of all created test users for your app. You can also establish friendships between test users to simulate social interactions. ```ruby all_users = @test_users.list ``` ```ruby @test_users.befriend(user, guest) ``` -------------------------------- ### Batch Request with Named Dependencies Source: https://github.com/arsduo/koala/wiki/Batch-requests Define dependencies between batch requests using names. A request with `depends_on` will only execute after the named request completes successfully. Successful dependent requests have their results omitted. ```ruby it "allows you to create dependencies" do me, koppel = @api.batch do |batch_api| batch_api.get_object("me", {}, :batch_args => {:name => "getme"}) batch_api.get_object("koppel", {}, :batch_args => {:depends_on => "getme"}) end me.should be_nil # gotcha! it's omitted because it's a successfully-executed dependency koppel["id"].should_not be_nil end ``` -------------------------------- ### Build Facebook Dialog URL Source: https://context7.com/arsduo/koala/llms.txt Construct a URL for initiating Facebook dialogs, such as sharing to the feed or requesting user permissions. Requires specifying the dialog type and relevant parameters. ```ruby feed_dialog_url = @oauth.url_for_dialog("feed", link: "https://myapp.com", redirect_uri: "https://myapp.com/after-share" ) ``` -------------------------------- ### Generate Access Token URL Source: https://github.com/arsduo/koala/wiki/OAuth Construct the URL required to exchange an authorization code for an access token. This request should be made from your server. ```ruby @oauth.url_for_access_token(code) # => "https://graph.facebook.com/oauth/access_token?client_id=#{app_id}&redirect_uri=#{callback_url}&client_secret=#{app_secret}&code=#{code}" ``` -------------------------------- ### Batch API Calls with Post-Processing Source: https://context7.com/arsduo/koala/llms.txt Perform batch API calls where each call can have a specific post-processing block to handle its result. ```ruby # Batch with per-call post-processing blocks @graph.batch do |b| b.get_object("me") { |u| self.current_user = u } b.get_connections("me", "friends") { |f| self.friends = f } b.get_connections("me", "photos", limit: 10) { |p| self.photos = p } end ``` -------------------------------- ### Uploading Ad Images Source: https://github.com/arsduo/koala/wiki/Uploading-Photos-and-Videos For Facebook Ad Images, you must read the image data and then upload it using the `put_connections` method with the `bytes` parameter. Ensure `open-uri` and `base64` are required. ```ruby require 'open-uri' img_data = open(my_post.image.url :medium).read img = @graph.put_connections('act_X', 'adimages', bytes: Base64.encode64(img_data)) ``` -------------------------------- ### Authenticate as a Page Source: https://github.com/arsduo/koala/wiki/Acting-as-a-Page Use the obtained page access token to initialize a new Koala API object to act as the page. ```ruby @page_graph = Koala::Facebook::API.new(page_token) ``` -------------------------------- ### Make Batch API Calls Source: https://github.com/arsduo/koala/blob/master/readme.md Executes multiple Facebook Graph API calls in a single batch request. Returns an array of results. ```ruby @graph.batch do |batch_api| batch_api.get_object('me') batch_api.put_wall_post('Making a post in a batch.') end ``` -------------------------------- ### Batch Request Dependencies (omit_response_on_success=false) Source: https://github.com/arsduo/koala/wiki/Batch-requests Create relationships between batch requests where one request depends on the result of a previous one. Setting `omit_response_on_success` to `false` ensures the response is always returned. ```ruby it "allows you create relationships between requests without omit_response_on_success" do results = @api.batch do |batch_api| batch_api.get_connections("me", "friends", {:limit => 5}, :batch_args => {:name => "get-friends"}) batch_api.get_objects("{result=get-friends:$.data.*.id}") end results[0].should be_nil results[1].should be_an(Hash) end ``` -------------------------------- ### Specifying Content Type for Uploads Source: https://github.com/arsduo/koala/wiki/Uploading-Photos-and-Videos For file paths and File objects, you can optionally provide a content type as the second argument. If not provided, Koala attempts to detect it automatically. ```ruby @graph.put_picture(file_with_weird_extension, content_type) ``` -------------------------------- ### Configure Global Rate Limit Hook Source: https://github.com/arsduo/koala/blob/master/readme.md Sets a global rate limit hook using Koala.configure to process rate limit information for app, ad account, and business use cases. ```ruby Koala.configure do |config| config.rate_limit_hook = ->(limits) { limits["x-app-usage"] # {"call_count"=>0, "total_cputime"=>0, "total_time"=>0} limits["x-ad-account-usage"] # {"acc_id_util_pct"=>9.67} limits["x-business-use-case-usage"] # {"123456789012345"=>[{"type"=>"messenger", "call_count"=>1, "total_cputime"=>1, "total_time"=>1, "estimated_time_to_regain_access"=>0}]} } end ```