Unicode C++
Unicode C++
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 Unicode C++ Downloads
#include <CkCacheW.h>
#include <CkOAuth2W.h>
#include <CkRestW.h>
#include <CkJsonObjectW.h>
#include <CkStringArrayW.h>
#include <CkStringBuilderW.h>
#include <CkHttpW.h>
#include <CkByteData.h>
#include <CkFileAccessW.h>
void ChilkatSample(void)
{
bool success = false;
// 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.
CkCacheW fbCache;
// The cache will use 1 level of 256 sub-directories.
fbCache.put_Level(1);
// Use a directory path that makes sense on your operating system..
fbCache.AddRoot(L"C:/fbCache");
// This example assumes a previously obtained an access token
CkOAuth2W oauth2;
oauth2.put_AccessToken(L"FACEBOOK-ACCESS-TOKEN");
CkRestW rest;
// Connect to Facebook.
success = rest.Connect(L"graph.facebook.com",443,true,true);
if (success != true) {
wprintf(L"%s\n",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(L"type",L"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(L"limit",L"100");
// Get the 1st page of photos ids.
// See https://developers.facebook.com/docs/graph-api/reference/user/photos/ for more information.
const wchar_t *responseJson = rest.fullRequestNoBody(L"GET",L"/v2.7/me/photos");
if (rest.get_LastMethodSuccess() != true) {
wprintf(L"%s\n",rest.lastErrorText());
return;
}
CkJsonObjectW photoJson;
CkStringArrayW saPhotoUrls;
CkStringBuilderW sbPhotoIdPath;
CkJsonObjectW json;
json.put_EmitCompact(false);
json.Load(responseJson);
int i;
const wchar_t *photoId = 0;
const wchar_t *imageUrl = 0;
// Get the "after" cursor.
const wchar_t *afterCursor = json.stringOf(L"paging.cursors.after");
while (json.get_LastMethodSuccess() == true) {
wprintf(L"-------------------\n");
wprintf(L"afterCursor = %s\n",afterCursor);
// For each photo id in this page...
i = 0;
int numItems = json.SizeOfArray(L"data");
while (i < numItems) {
json.put_I(i);
photoId = json.stringOf(L"data[i].id");
wprintf(L"photoId = %s\n",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.
const wchar_t *photoJsonStr = fbCache.fetchText(photoId);
if (fbCache.get_LastMethodSuccess() == false) {
// It's not locally available, so get it from Facebook..
sbPhotoIdPath.Clear();
sbPhotoIdPath.Append(L"/v2.7/");
sbPhotoIdPath.Append(photoId);
rest.ClearAllQueryParams();
rest.AddQueryParam(L"fields",L"id,album,images");
wprintf(L"Fetching photo node from Facebook...\n");
// 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(L"GET",sbPhotoIdPath.getAsString());
if (rest.get_LastMethodSuccess() != true) {
wprintf(L"%s\n",rest.lastErrorText());
return;
}
// Add the photo JSON to the local cache.
fbCache.SaveTextNoExpire(photoId,L"",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(L"images[0].source");
if (photoJson.get_LastMethodSuccess() == true) {
// Actually, we'll add a small JSON document that contains both the image ID and the URL.
CkJsonObjectW imgUrlJson;
imgUrlJson.AppendString(L"id",photoId);
imgUrlJson.AppendString(L"url",imageUrl);
saPhotoUrls.Append(imgUrlJson.emit());
wprintf(L"imageUrl = %s\n",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(L"type",L"uploaded");
rest.AddQueryParam(L"limit",L"20");
rest.AddQueryParam(L"after",afterCursor);
// Get the next page of photo ids.
responseJson = rest.fullRequestNoBody(L"GET",L"/v2.7/me/photos");
if (rest.get_LastMethodSuccess() != true) {
wprintf(L"%s\n",rest.lastErrorText());
return;
}
json.Load(responseJson);
afterCursor = json.stringOf(L"paging.cursors.after");
}
wprintf(L"No more pages of photos.\n");
// 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.
CkHttpW http;
// We'll cache the image data so that if run again, we don't re-download the same image again.
int numUrls = saPhotoUrls.get_Count();
i = 0;
CkJsonObjectW urlJson;
CkByteData imageBytes;
CkFileAccessW fac;
while (i < numUrls) {
urlJson.Load(saPhotoUrls.getString(i));
photoId = urlJson.stringOf(L"id");
imageUrl = urlJson.stringOf(L"url");
// Check the local cache for the image data.
// Only download and save if not already cached.
success = fbCache.FetchFromCache(imageUrl,imageBytes);
if (fbCache.get_LastMethodSuccess() == false) {
// This photo needs to be downloaded.
CkStringBuilderW sbImageUrl;
sbImageUrl.Append(imageUrl);
// Let's form a filename..
const wchar_t *extension = L".jpg";
if (sbImageUrl.Contains(L".gif",false) == true) {
extension = L".gif";
}
if (sbImageUrl.Contains(L".png",false) == true) {
extension = L".png";
}
if (sbImageUrl.Contains(L".tiff",false) == true) {
extension = L".tiff";
}
if (sbImageUrl.Contains(L".bmp",false) == true) {
extension = L".bmp";
}
CkStringBuilderW sbLocalFilePath;
sbLocalFilePath.Append(L"C:/Photos/facebook/uploaded/");
sbLocalFilePath.Append(photoId);
sbLocalFilePath.Append(extension);
success = http.QuickGet(imageUrl,imageBytes);
if (http.get_LastMethodSuccess() != true) {
wprintf(L"%s\n",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,L"",imageBytes);
fac.WriteEntireFile(sbLocalFilePath.getAsString(),imageBytes);
wprintf(L"Downloaded to %s\n",sbLocalFilePath.getAsString());
}
i = i + 1;
}
wprintf(L"Finished downloading all Facebook photos!\n");
}