Cmdlets for Facebook

Build 24.0.9060

Establishing a Connection

With the CData Cmdlets users can install a data module, set the connection properties, and start scripting. This section provides examples of using our Facebook Cmdlets with native PowerShell cmdlets, like the CSV import and export cmdlets.

Installing and Connecting

If you have PSGet, installing the cmdlets can be accomplished from the PowerShell Gallery with the following command. You can also obtain a setup from the CData site.

Install-Module FacebookCmdlets

The following line is then added to your profile, loading the cmdlets on the next session:

Import-Module FacebookCmdlets;

You can then use the Connect-FB cmdlet to create a connection object that can be passed to other cmdlets:

$conn = Connect-FB

Connecting to Facebook

Before you can connect to Facebook, you must obtain the appropriate connection properties. Since Facebook supports user authentication only via OAuth, you must either use the CData-supplied embedded OAuth application or create a custom OAuth application, as described in Creating a Custom OAuth Application.

You can also set the following optional connection properties:

  • Target: This property enables you to filter the results of all queries in the connection to records that match a specified target. For example, to retrieve comments on a video, specify the Id of the video as the target. To specify this restriction per query, use the table's Target column.
  • AggregateFormat: This property enables you to return aggregate columns as XML data rather than JSON (the default format).

Authenticating to Facebook

The following subsections describe how to authenticate to Facebook from any available OAuth access flow. For information about creating a custom OAuth application, see Creating a Custom OAuth Application.

Desktop Applications

CData provides an embedded OAuth application that simplifies OAuth desktop Authentication. You can also create a custom OAuth application, as described in Creating a Custom OAuth Application.

For authentication, the only difference between the two methods is that to connect via a custom OAuth application you must set the following connection properties:

  • OAuthClientId: (custom applications only) Set to the client Id in your application settings.
  • OAuthClientSecret: (custom applications only) Set to the client secret in your application settings.
  • CallbackURL: Set to the Redirect URL in your application settings.
  • Scope (optional): Set this only if you need to customizie the permissions that the driver requests.
  • AuthenticateAsPage (optional): Set this to a page Id to make requests as a page. The page must be managed by the authenticated user.

When you connect the cmdlet opens the OAuth endpoint in your default browser. Log in and grant permissions to the application.

Web Applications

When connecting via a Web application, you must create and register a custom OAuth application with Facebook, as described in Creating a Custom OAuth Application. You can then use the cmdlet to get and manage the OAuth token values.

Get an OAuth Access Token

To obtain the OAuthAccessToken set the following connection properties:

  • OAuthClientId: Set to the client Id in your application settings.
  • OAuthClientSecret: Set to the client secret in your application settings
  • Scope (optional): Set only if you need to customizie the permissions that the driver requests.
  • AuthenticateAsPage (optional): Set to a page Id to make requests as a page. The page must be managed by the authenticated user.

Now call stored procedures to complete the OAuth exchange:

  1. Call the GetOAuthAuthorizationURL stored procedure. Set the AuthMode input to WEB and set the CallbackURL input to the Redirect URI you specified in your app settings. If necessary, set the "Scope" parameter to request custom permissions.
  2. Open the URL, log in, and authorize the application. You are redirected back to the callback URL.
  3. Call the GetOAuthAccessToken stored procedure. Set the AuthMode input to WEB. Set the Verifier input to the "code" parameter in the query string of the callback URL. If necessary, set the "Scope" parameter to request custom permissions.

To connect to data, set the OAuthAccessToken connection property to the access token returned by the stored procedure. When the access token expires after ExpiresIn seconds, call GetOAuthAccessToken again to obtain a new access token.

Headless Machines

To configure the driver to use OAuth with a user account on a headless machine, you must authenticate on another device that has an internet browser.

Creating a custom OAuth app is optional in the headless OAuth flow; if you want to skip creating an app, you can connect with the driver's embedded OAuth credentials. However, you might want to create a custom OAuth app to change the information displayed when users log into Facebook to grant permissions to the driver. For information on how to create a custom OAuth application, see Creating a Custom OAuth Application.

  1. Choose one of these two options:
    • Option 1: Obtain the OAuthVerifier value as described in "Obtain and Exchange a Verifier Code", below.
    • Option 2: Install the cmdlet on another machine and transfer the OAuth authentication values after you authenticate through the usual browser-based flow, as described in "Transfer OAuth Settings", below.
  2. Configure the cmdlet to automatically refresh the access token from the headless machine.

Option 1: Obtain and Exchange a Verifier Code

To obtain a verifier code, you must authenticate at the OAuth authorization URL. Follow the steps below to authenticate from the machine with an internet browser and obtain the OAuthVerifier connection property.

  1. If you are using the Embedded OAuth Application:
    1. Call the GetOAuthAuthorizationURL stored procedure.
    2. Click Facebook OAuth endpoint to open the endpoint in your browser.
  2. If you are using a custom OAuth application, create the Authorization URL by setting the following properties:
    • InitiateOAuth: Set to OFF.
    • OAuthClientId: Set to the client Id assigned when you registered your application.
    • OAuthClientSecret: Set to the client secret assigned when you registered your application.
  3. Call the GetOAuthAuthorizationURL stored procedure with the CallbackURI input parameter set to the exact Redirect URI you specified in your application settings.
  4. Open the URL returned by the stored procedure in a browser.
  5. Log in and grant permissions to the cmdlet. You are then redirected to the callback URL, which contains the verifier code.
  6. Save the value of the verifier code. Later you will set this in the OAuthVerifier connection property.

Finally, on the headless machine, set the following connection properties to obtain the OAuth authentication values:

  • OAuthClientId: Set to the Client ID in your OAuth Integration settings.
  • OAuthClientSecret: Set to the Client Secret in your OAuth Integration settings.
  • OAuthVerifier: Set to the verifier code.
  • OAuthSettingsLocation: Set to persist the encrypted OAuth authentication values to the specified location.
  • InitiateOAuth: Set to REFRESH.

Connect to Data

After the OAuth settings file is generated, set the following properties to connect to data:

  • OAuthSettingsLocation: Set to the location containing the encrypted OAuth authentication values. Make sure this location gives read and write permissions to the provider to enable the automatic refreshing of the access token.
  • InitiateOAuth: Set to REFRESH.

Option 2: Transfer OAuth Settings

To install the cmdlet on another machine, authenticate, and then transfer the resulting OAuth values:

  1. On a second machine, install the cmdlet and connect with the following properties set:
    • OAuthSettingsLocation: Set to a writable location.
    • OAuthClientId: Set to the client ID in your app settings.
    • OAuthClientSecret: Set to the client secret in your app settings.
    • CallbackURL: Set to the callback URL in your app settings.
  2. Test the connection to authenticate. The resulting authentication values are written and encrypted to the path specified by OAuthSettingsLocation. After you have successfully tested the connection, copy the OAuth settings file to your headless machine. On the headless machine, set the following connection properties to connect to data:
    • InitiateOAuth: Set to REFRESH.
    • OAuthSettingsLocation: Set to the location of your OAuth settings file. Make sure this location gives read and write permissions to the cmdlet to enable the automatic refreshing of the access token.

Requesting Additional Permissions

You may find while using the cmdlet that Facebook returns an error stating your app does not have permissions to do a certain action. To resolve this, you must generate a new OAuth access token with the required permissions. Set the Scope property in the authentication step for a desktop application. You can find a list of available Facebook permissions here:

http://developers.facebook.com/docs/authentication/permissions/

Permissions that may be required depending on your use case are:

user_birthday, user_photos, user_videos, user_likes, user_hometown, user_location, read_insights, pages_manage_metadata, pages_read_engagement, pages_read_user_content, pages_messaging, business_management, instagram_basic, instagram_manage_insights

Note that in some cases, permissions restrictions might not be due to missing but requestable Facebook OAuth permissions, but instead might be due to missing OAuth app features, like Page Public Content Access or Page Public Metadata Access. These features are tied to the OAuth app as a whole, and cannot be approved or denied for individual OAuth access tokens requested by users. Consider Creating a Custom OAuth Application if you need access to app features not available with the embedded OAuth app.

AuthenticateAsPage Property

Use the AuthenticateAsPage connection property if you want to post as a single page. To query collections of pages, leave AuthenticateAsPage blank, in which case CData tools automatically detect which page tokens to use.

The following sections compare the two options.

Posting as a Page

After authenticating to Facebook with your user account, you can post, etc. as one of the pages you manage: Set the AuthenticateAsPage property to the Id of the page you want. You can find the Ids for all pages your account has access to by querying the Pages view.

Automatic Page

Facebook has made a number of recent changes that require page tokens for most resources owned by a page. This can be troublesome if you manage multiple pages and want to execute the same queries across all pages (such as retrieving Insights). In order to make this work seamlessly with our tools, we have added a way to automatically detect the page token to use. For this to work, simply do not specify the AuthenticateAsPage. Note that the correct page token can only be resolved if the page id is specified as part of the target in the request. This means for some requests you will still need to manually specify AuthenticateAsPage.

Retrieving Data

The Select-FB cmdlet provides a native PowerShell interface for retrieving data:

$results = Select-FB -Connection $conn -Table "Posts" -Columns @("ID, FromName") -Where "Target='11111'"
The Invoke-FB cmdlet provides an SQL interface. This cmdlet can be used to execute an SQL query via the Query parameter.

Piping Cmdlet Output

The cmdlets return row objects to the pipeline one row at a time. The following line exports results to a CSV file:

Select-FB -Connection $conn -Table Posts -Where "Target = '11111'" | Select -Property * -ExcludeProperty Connection,Table,Columns | Export-Csv -Path c:\myPostsData.csv -NoTypeInformation

You will notice that we piped the results from Select-FB into a Select-Object cmdlet and excluded some properties before piping them into an Export-CSV cmdlet. We do this because the CData Cmdlets append Connection, Table, and Columns information onto each row object in the result set, and we do not necessarily want that information in our CSV file.

However, this makes it easy to pipe the output of one cmdlet to another. The following is an example of converting a result set to JSON:

 
PS C:\> $conn  = Connect-FB
PS C:\> $row = Select-FB -Connection $conn -Table "Posts" -Columns (ID, FromName) -Where "Target = '11111'" | select -first 1
PS C:\> $row | ConvertTo-Json
{
  "Connection":  {

  },
  "Table":  "Posts",
  "Columns":  [

  ],
  "ID":  "MyID",
  "FromName":  "MyFromName"
} 

Deleting Data

The following line deletes any records that match the criteria:

Select-FB -Connection $conn -Table Posts -Where "Target = '11111'" | Remove-FB

Modifying Data

The cmdlets make data transformation easy as well as data cleansing. The following example loads data from a CSV file into Facebook, checking first whether a record already exists and needs to be updated instead of inserted.

Import-Csv -Path C:\MyPostsUpdates.csv | %{
  $record = Select-FB -Connection $conn -Table Posts -Where ("Id = `'"+$_.Id+"`'")
  if($record){
    Update-FB -Connection $conn -Table Posts -Columns @("ID","FromName") -Values @($_.ID, $_.FromName) -Where "Id  = `'$_.Id`'"
  }else{
    Add-FB -Connection $conn -Table Posts -Columns @("ID","FromName") -Values @($_.ID, $_.FromName)
  }
}

Copyright (c) 2024 CData Software, Inc. - All rights reserved.
Build 24.0.9060