Sample code for 30+ languages & platforms
PureBasic Requires Chilkat v9.5.0.62+

Facebook Download all Photos to Local Files

See more Facebook Examples

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.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkJsonObject.pb"
IncludeFile "CkOAuth2.pb"
IncludeFile "CkHttp.pb"
IncludeFile "CkFileAccess.pb"
IncludeFile "CkCache.pb"
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkRest.pb"
IncludeFile "CkStringTable.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  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.
    fbCache.i = CkCache::ckCreate()
    If fbCache.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ;  The cache will use 1 level of 256 sub-directories.
    CkCache::setCkLevel(fbCache, 1)
    ;  Use a directory path that makes sense on your operating system..
    CkCache::ckAddRoot(fbCache,"C:/fbCache")

    ;  This example assumes a previously obtained an access token
    oauth2.i = CkOAuth2::ckCreate()
    If oauth2.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkOAuth2::setCkAccessToken(oauth2, "FACEBOOK-ACCESS-TOKEN")

    rest.i = CkRest::ckCreate()
    If rest.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ;  Connect to Facebook.
    success = CkRest::ckConnect(rest,"graph.facebook.com",443,1,1)
    If success <> 1
        Debug CkRest::ckLastErrorText(rest)
        CkCache::ckDispose(fbCache)
        CkOAuth2::ckDispose(oauth2)
        CkRest::ckDispose(rest)
        ProcedureReturn
    EndIf

    ;  Provide the authentication credentials (i.e. the access key)
    CkRest::ckSetAuthOAuth2(rest,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".
    CkRest::ckAddQueryParam(rest,"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.
    CkRest::ckAddQueryParam(rest,"limit","100")

    ;  Get the 1st page of photos ids.
    ;  See https://developers.facebook.com/docs/graph-api/reference/user/photos/ for more information.
    responseJson.s = CkRest::ckFullRequestNoBody(rest,"GET","/v2.7/me/photos")
    If CkRest::ckLastMethodSuccess(rest) <> 1
        Debug CkRest::ckLastErrorText(rest)
        CkCache::ckDispose(fbCache)
        CkOAuth2::ckDispose(oauth2)
        CkRest::ckDispose(rest)
        ProcedureReturn
    EndIf

    photoJson.i = CkJsonObject::ckCreate()
    If photoJson.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    saPhotoUrls.i = CkStringTable::ckCreate()
    If saPhotoUrls.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    sbPhotoIdPath.i = CkStringBuilder::ckCreate()
    If sbPhotoIdPath.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    json.i = CkJsonObject::ckCreate()
    If json.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkJsonObject::setCkEmitCompact(json, 0)
    CkJsonObject::ckLoad(json,responseJson)

    i.i
    photoId.s
    imageUrl.s

    ;  Get the "after" cursor.
    afterCursor.s = CkJsonObject::ckStringOf(json,"paging.cursors.after")
    While CkJsonObject::ckLastMethodSuccess(json) = 1

        Debug "-------------------"
        Debug "afterCursor = " + afterCursor

        ;  For each photo id in this page...
        i = 0
        numItems.i = CkJsonObject::ckSizeOfArray(json,"data")
        While i < numItems
            CkJsonObject::setCkI(json, i)
            photoId = CkJsonObject::ckStringOf(json,"data[i].id")
            Debug "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.
            photoJsonStr.s = CkCache::ckFetchText(fbCache,photoId)
            If CkCache::ckLastMethodSuccess(fbCache) = 0
                ;  It's not locally available, so get it from Facebook..
                CkStringBuilder::ckClear(sbPhotoIdPath)
                CkStringBuilder::ckAppend(sbPhotoIdPath,"/v2.7/")
                CkStringBuilder::ckAppend(sbPhotoIdPath,photoId)

                CkRest::ckClearAllQueryParams(rest)
                CkRest::ckAddQueryParam(rest,"fields","id,album,images")

                Debug "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 = CkRest::ckFullRequestNoBody(rest,"GET",CkStringBuilder::ckGetAsString(sbPhotoIdPath))
                If CkRest::ckLastMethodSuccess(rest) <> 1
                    Debug CkRest::ckLastErrorText(rest)
                    CkCache::ckDispose(fbCache)
                    CkOAuth2::ckDispose(oauth2)
                    CkRest::ckDispose(rest)
                    CkJsonObject::ckDispose(photoJson)
                    CkStringTable::ckDispose(saPhotoUrls)
                    CkStringBuilder::ckDispose(sbPhotoIdPath)
                    CkJsonObject::ckDispose(json)
                    ProcedureReturn
                EndIf

                ;  Add the photo JSON to the local cache.
                CkCache::ckSaveTextNoExpire(fbCache,photoId,"",photoJsonStr)
            EndIf

            ;  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.
            CkJsonObject::ckLoad(photoJson,photoJsonStr)
            imageUrl = CkJsonObject::ckStringOf(photoJson,"images[0].source")
            If CkJsonObject::ckLastMethodSuccess(photoJson) = 1

                ;  Actually, we'll add a small JSON document that contains both the image ID and the URL.
                imgUrlJson.i = CkJsonObject::ckCreate()
                If imgUrlJson.i = 0
                    Debug "Failed to create object."
                    ProcedureReturn
                EndIf

                CkJsonObject::ckAppendString(imgUrlJson,"id",photoId)
                CkJsonObject::ckAppendString(imgUrlJson,"url",imageUrl)
                CkStringTable::ckAppend(saPhotoUrls,CkJsonObject::ckEmit(imgUrlJson))
                Debug "imageUrl = " + imageUrl
            EndIf

            i = i + 1
        Wend

        ;  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.
        CkRest::ckClearAllQueryParams(rest)
        CkRest::ckAddQueryParam(rest,"type","uploaded")
        CkRest::ckAddQueryParam(rest,"limit","20")
        CkRest::ckAddQueryParam(rest,"after",afterCursor)

        ;  Get the next page of photo ids.
        responseJson = CkRest::ckFullRequestNoBody(rest,"GET","/v2.7/me/photos")
        If CkRest::ckLastMethodSuccess(rest) <> 1
            Debug CkRest::ckLastErrorText(rest)
            CkCache::ckDispose(fbCache)
            CkOAuth2::ckDispose(oauth2)
            CkRest::ckDispose(rest)
            CkJsonObject::ckDispose(photoJson)
            CkStringTable::ckDispose(saPhotoUrls)
            CkStringBuilder::ckDispose(sbPhotoIdPath)
            CkJsonObject::ckDispose(json)
            CkJsonObject::ckDispose(imgUrlJson)
            ProcedureReturn
        EndIf

        CkJsonObject::ckLoad(json,responseJson)
        afterCursor = CkJsonObject::ckStringOf(json,"paging.cursors.after")
    Wend

    Debug "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.  
    http.i = CkHttp::ckCreate()
    If http.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ;  We'll cache the image data so that if run again, we don't re-download the same image again.
    numUrls.i = CkStringTable::ckCount(saPhotoUrls)
    i = 0
    urlJson.i = CkJsonObject::ckCreate()
    If urlJson.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

ERROR - PureBasic is an array language
    fac.i = CkFileAccess::ckCreate()
    If fac.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    While i < numUrls
        CkJsonObject::ckLoad(urlJson,CkStringTable::ckStringAt(saPhotoUrls,i))
        photoId = CkJsonObject::ckStringOf(urlJson,"id")
        imageUrl = CkJsonObject::ckStringOf(urlJson,"url")

        ;  Check the local cache for the image data.
        ;  Only download and save if not already cached.
        imageBytes = CkCache::ckFetchFromCache(fbCache,imageUrl)
        If CkCache::ckLastMethodSuccess(fbCache) = 0
            ;   This photo needs to be downloaded.

            sbImageUrl.i = CkStringBuilder::ckCreate()
            If sbImageUrl.i = 0
                Debug "Failed to create object."
                ProcedureReturn
            EndIf

            CkStringBuilder::ckAppend(sbImageUrl,imageUrl)

            ;  Let's form a filename..
            extension.s = ".jpg"
            If CkStringBuilder::ckContains(sbImageUrl,".gif",0) = 1
                extension = ".gif"
            EndIf

            If CkStringBuilder::ckContains(sbImageUrl,".png",0) = 1
                extension = ".png"
            EndIf

            If CkStringBuilder::ckContains(sbImageUrl,".tiff",0) = 1
                extension = ".tiff"
            EndIf

            If CkStringBuilder::ckContains(sbImageUrl,".bmp",0) = 1
                extension = ".bmp"
            EndIf

            sbLocalFilePath.i = CkStringBuilder::ckCreate()
            If sbLocalFilePath.i = 0
                Debug "Failed to create object."
                ProcedureReturn
            EndIf

            CkStringBuilder::ckAppend(sbLocalFilePath,"C:/Photos/facebook/uploaded/")
            CkStringBuilder::ckAppend(sbLocalFilePath,photoId)
            CkStringBuilder::ckAppend(sbLocalFilePath,extension)

            imageBytes = CkHttp::ckQuickGet(http,imageUrl)
            If CkHttp::ckLastMethodSuccess(http) <> 1
                Debug CkHttp::ckLastErrorText(http)
                CkCache::ckDispose(fbCache)
                CkOAuth2::ckDispose(oauth2)
                CkRest::ckDispose(rest)
                CkJsonObject::ckDispose(photoJson)
                CkStringTable::ckDispose(saPhotoUrls)
                CkStringBuilder::ckDispose(sbPhotoIdPath)
                CkJsonObject::ckDispose(json)
                CkJsonObject::ckDispose(imgUrlJson)
                CkHttp::ckDispose(http)
                CkJsonObject::ckDispose(urlJson)
                CkFileAccess::ckDispose(fac)
                CkStringBuilder::ckDispose(sbImageUrl)
                CkStringBuilder::ckDispose(sbLocalFilePath)
                ProcedureReturn
            EndIf

            ;  We've downloaded the photo image bytes into memory.
            ;  Save it to the cache AND save it to the output file.
            CkCache::ckSaveToCacheNoExpire(fbCache,imageUrl,"",imageBytes)
            CkFileAccess::ckWriteEntireFile(fac,CkStringBuilder::ckGetAsString(sbLocalFilePath),imageBytes)

            Debug "Downloaded to " + CkStringBuilder::ckGetAsString(sbLocalFilePath)
        EndIf

        i = i + 1
    Wend

    Debug "Finished downloading all Facebook photos!"


    CkCache::ckDispose(fbCache)
    CkOAuth2::ckDispose(oauth2)
    CkRest::ckDispose(rest)
    CkJsonObject::ckDispose(photoJson)
    CkStringTable::ckDispose(saPhotoUrls)
    CkStringBuilder::ckDispose(sbPhotoIdPath)
    CkJsonObject::ckDispose(json)
    CkJsonObject::ckDispose(imgUrlJson)
    CkHttp::ckDispose(http)
    CkJsonObject::ckDispose(urlJson)
    CkFileAccess::ckDispose(fac)
    CkStringBuilder::ckDispose(sbImageUrl)
    CkStringBuilder::ckDispose(sbLocalFilePath)


    ProcedureReturn
EndProcedure