Chilkat Examples

ChilkatHOMEAndroid™Classic ASPCC++C#Mono C#.NET Core C#C# UWP/WinRTDataFlexDelphi ActiveXDelphi DLLVisual FoxProJavaLianjaMFCObjective-CPerlPHP ActiveXPHP ExtensionPowerBuilderPowerShellPureBasicCkPythonChilkat2-PythonRubySQL ServerSwift 2Swift 3/4TclUnicode CUnicode C++Visual Basic 6.0VB.NETVB.NET UWP/WinRTVBScriptXojo PluginNode.jsExcelGo

Node.js Examples

ASN.1
Amazon S3
Amazon S3 (new)
Amazon SES
Amazon SNS
Amazon SQS
Async
Azure Cloud Storage
Azure Service Bus
Base64
Bounced Email
Box
CSR
CSV
Certificates
Compression
DKIM / DomainKey
DSA
Diffie-Hellman
Digital Signatures
Dropbox
Dynamics CRM
ECC
Email Object
Encryption
FTP
Facebook
FileAccess
Firebase
GMail REST API
GeoOp
Google APIs
Google Calendar
Google Cloud Storage
Google Drive
Google Sheets
Gzip
HTML-to-XML/Text
HTTP
HTTP Misc
IMAP
JSON
JSON Web Encryption (JWE)
JSON Web Signatures (JWS)
JSON Web Token (JWT)

Java KeyStore (JKS)
Jira
MHT / HTML Email
MIME
Microsoft Graph
NTLM
OAuth1
OAuth2
OneDrive
OpenSSL
Outlook
PEM
PFX/P12
POP3
PRNG
PayPal
Peoplevox
QuickBooks
REST
REST Misc
RSA Encryption
SCP
SFTP
SMTP
SSH
SSH Key
SSH Tunnel
SharePoint
Shopify
Socket/SSL/TLS
Spider
Stream
Stripe
SugarCRM
Tar Archive
Twitter
Upload
VoiceBase
Walmart
WebSocket
XAdES
XML
XML Digital Signatures
XMP
Xero
Zip
curl
eBay

 

 

 

(Node.js) Facebook Download all Photos to Local Files

Demonstrates how to download all of one's Facebook photos to a local filesystem directory. This sample code keeps a local cache to avoid re-downloading the same photos twice. The program can be run again after a time, and it will download only photos that haven't yet been downloaded.

Install Chilkat for Node.js and Electron using npm at

Chilkat npm packages for Node.js

Chilkat npm packages for Electron

on Windows, Linux, MacOSX, and ARM

var os = require('os');
if (os.platform() == 'win32') {  
    if (os.arch() == 'ia32') {
        var chilkat = require('@chilkat/ck-node11-win-ia32');
    } else {
        var chilkat = require('@chilkat/ck-node11-win64'); 
    }
} else if (os.platform() == 'linux') {
    if (os.arch() == 'arm') {
        var chilkat = require('@chilkat/ck-node11-arm');
    } else if (os.arch() == 'x86') {
        var chilkat = require('@chilkat/ck-node11-linux32');
    } else {
        var chilkat = require('@chilkat/ck-node11-linux64');
    }
} else if (os.platform() == 'darwin') {
    var chilkat = require('@chilkat/ck-node11-macosx');
}

function chilkatExample() {

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // This example will use a local disk cache to avoid re-fetching the same
    // photo id after it's been fetched once.
    var fbCache = new chilkat.Cache();
    // The cache will use 1 level of 256 sub-directories.
    fbCache.Level = 1;
    // Use a directory path that makes sense on your operating system..
    fbCache.AddRoot("C:/fbCache");

    // This example assumes a previously obtained an access token
    var oauth2 = new chilkat.OAuth2();
    oauth2.AccessToken = "FACEBOOK-ACCESS-TOKEN";

    var rest = new chilkat.Rest();

    // Connect to Facebook.
    var success = rest.Connect("graph.facebook.com",443,true,true);
    if (success !== true) {
        console.log(rest.LastErrorText);
        return;
    }

    // Provide the authentication credentials (i.e. the access key)
    rest.SetAuthOAuth2(oauth2);

    // There are two choices:  
    // We can choose to download the photos the person is tagged in or has uploaded
    // by setting type to "tagged" or "uploaded".
    rest.AddQueryParam("type","uploaded");

    // To download all photos, we begin with an outer loop that iterates over
    // the list of photo nodes in pages.  Each page returned contains a list of 
    // photo node ids.  Each photo node id must be retrieved to get the download URL(s)
    // of the actual image.

    // I don't know the max limit for the number of records that can be downloaded at once.
    rest.AddQueryParam("limit","100");

    // Get the 1st page of photos ids.
    // See https://developers.facebook.com/docs/graph-api/reference/user/photos/ for more information.
    var responseJson = rest.FullRequestNoBody("GET","/v2.7/me/photos");
    if (rest.LastMethodSuccess !== true) {
        console.log(rest.LastErrorText);
        return;
    }

    var photoJson = new chilkat.JsonObject();
    var saPhotoUrls = new chilkat.StringArray();
    var sbPhotoIdPath = new chilkat.StringBuilder();

    var json = new chilkat.JsonObject();
    json.EmitCompact = false;
    json.Load(responseJson);

    var i;
    var photoId;
    var imageUrl;

    // Get the "after" cursor.
    var afterCursor = json.StringOf("paging.cursors.after");
    while (json.LastMethodSuccess == true) {

        console.log("-------------------");
        console.log("afterCursor = " + afterCursor);

        // For each photo id in this page...
        i = 0;
        var numItems = json.SizeOfArray("data");
        while (i < numItems) {
            json.I = i;
            photoId = json.StringOf("data[i].id");
            console.log("photoId = " + photoId);

            // We need to fetch the JSON for this photo.  Check to see if it's in the local disk cache,
            // and if not, then get it from Facebook.
            var photoJsonStr = fbCache.FetchText(photoId);
            if (fbCache.LastMethodSuccess == false) {
                // It's not locally available, so get it from Facebook..
                sbPhotoIdPath.Clear();
                sbPhotoIdPath.Append("/v2.7/");
                sbPhotoIdPath.Append(photoId);

                rest.ClearAllQueryParams();
                rest.AddQueryParam("fields","id,album,images");

                console.log("Fetching photo node from Facebook...");

                // This REST request will continue using the existing connection.
                // If the connection was closed, it will automatically reconnect to send the request.
                photoJsonStr = rest.FullRequestNoBody("GET",sbPhotoIdPath.GetAsString());
                if (rest.LastMethodSuccess !== true) {
                    console.log(rest.LastErrorText);
                    return;
                }

                // Add the photo JSON to the local cache.
                fbCache.SaveTextNoExpire(photoId,"",photoJsonStr);
            }

            // Parse the photo JSON and add the main photo download URL to saPhotoUrls
            // There may be multiple URLs in the images array, but the 1st one is the largest and main photo URL.
            // The others are smaller sizes of the same photo.
            photoJson.Load(photoJsonStr);
            imageUrl = photoJson.StringOf("images[0].source");
            if (photoJson.LastMethodSuccess == true) {

                // Actually, we'll add a small JSON document that contains both the image ID and the URL.
                var imgUrlJson = new chilkat.JsonObject();
                imgUrlJson.AppendString("id",photoId);
                imgUrlJson.AppendString("url",imageUrl);
                saPhotoUrls.Append(imgUrlJson.Emit());
                console.log("imageUrl = " + imageUrl);
            }

            i = i+1;
        }

        // Prepare for getting the next page of photos ids.
        // We can continue using the same REST object.
        // If already connected, we'll continue using the existing connection.
        // Otherwise, a new connection will automatically be made if needed.
        rest.ClearAllQueryParams();
        rest.AddQueryParam("type","uploaded");
        rest.AddQueryParam("limit","20");
        rest.AddQueryParam("after",afterCursor);

        // Get the next page of photo ids.
        responseJson = rest.FullRequestNoBody("GET","/v2.7/me/photos");
        if (rest.LastMethodSuccess !== true) {
            console.log(rest.LastErrorText);
            return;
        }

        json.Load(responseJson);
        afterCursor = json.StringOf("paging.cursors.after");
    }

    console.log("No more pages of photos.");

    // Now iterate over the photo URLs and download each to a file.
    // We can use Chilkat HTTP.  No Facebook authorization (access token) is required to download
    // the photo once the URL is known.  
    var http = new chilkat.Http();

    // We'll cache the image data so that if run again, we don't re-download the same image again.
    var numUrls = saPhotoUrls.Count;
    i = 0;
    var urlJson = new chilkat.JsonObject();

    var fac = new chilkat.FileAccess();

    while (i < numUrls) {
        urlJson.Load(saPhotoUrls.GetString(i));
        photoId = urlJson.StringOf("id");
        imageUrl = urlJson.StringOf("url");

        // Check the local cache for the image data.
        // Only download and save if not already cached.
        imageBytes = fbCache.FetchFromCache(imageUrl);
        if (fbCache.LastMethodSuccess == false) {
            //  This photo needs to be downloaded.

            var sbImageUrl = new chilkat.StringBuilder();
            sbImageUrl.Append(imageUrl);

            // Let's form a filename..
            var extension = ".jpg";
            if (sbImageUrl.Contains(".gif",false) == true) {
                extension = ".gif";
            }

            if (sbImageUrl.Contains(".png",false) == true) {
                extension = ".png";
            }

            if (sbImageUrl.Contains(".tiff",false) == true) {
                extension = ".tiff";
            }

            if (sbImageUrl.Contains(".bmp",false) == true) {
                extension = ".bmp";
            }

            var sbLocalFilePath = new chilkat.StringBuilder();
            sbLocalFilePath.Append("C:/Photos/facebook/uploaded/");
            sbLocalFilePath.Append(photoId);
            sbLocalFilePath.Append(extension);

            imageBytes = http.QuickGet(imageUrl);
            if (http.LastMethodSuccess !== true) {
                console.log(http.LastErrorText);
                return;
            }

            // We've downloaded the photo image bytes into memory.
            // Save it to the cache AND save it to the output file.
            fbCache.SaveToCacheNoExpire(imageUrl,"",imageBytes);
            fac.WriteEntireFile(sbLocalFilePath.GetAsString(),imageBytes);

            console.log("Downloaded to " + sbLocalFilePath.GetAsString());
        }

        i = i+1;
    }

    console.log("Finished downloading all Facebook photos!");

}

chilkatExample();

 

© 2000-2016 Chilkat Software, Inc. All Rights Reserved.