Skip to content

Instantly share code, notes, and snippets.

@labnol
Created August 19, 2014 13:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save labnol/7ee4691577f9dd0b2334 to your computer and use it in GitHub Desktop.
Save labnol/7ee4691577f9dd0b2334 to your computer and use it in GitHub Desktop.
Save Instagram Photos
function send2gp() {
var success = new Boolean(false);
var retry = 0;
var max_retry = 3; // 最高リトライ回数 max retry count
var errmsg = '';
var tokiboys1 = '長男の名前'; // 長男の名前を設定 define my first boy's name
var tokiboys2 = '二男の名前'; // 二男の名前を設定 define my second boy's name
var papa = 'パパの名前'; // 送信者(パパ)の名前を設定 define my name
// エラーで終了した場合はリトライする(Max3回)
// Retry maximum 3 times
while (success == false && retry < max_retry){
try{
//抽出対象のタグ Hashtag to grep.
var TAG_NAME = 'send2gp'; // ご自身で任意のハッシュタグを設定してもOKです。 You may also set any kind of hashtag.
// Instagram API Client ID
var CLIENT_ID = ''; // Instagramアプリを登録して取得したCLIENT_IDをセットしてください。 Insert your app Client_ID.
//エンドポイントURL Endpoint URL
var url = 'https://api.instagram.com/v1/tags/' + TAG_NAME + '/media/recent?client_id=' + CLIENT_ID;
// データの取得期間:前日の00:00:00から
// Date/Time from : from yesterday 00:00:00
var dateFrom = new Date();
dateFrom.setDate(dateFrom.getDate() - 1);
dateFrom.setHours(00,00,00,00);
// データの取得期間:前日の23:59:59まで
// Date/Time to : to yesterday 23:59:59
var dateTo = new Date(dateFrom);
dateTo.setHours(23,59,59,59);
// お爺ちゃん or お婆ちゃん(メールで送付する先)のメールアドレス
// Grandpa/Gramma's email address (or whomever you wanna send your photos/movies to...)
var toEmail = 'grandpa@tokifu.jp';
// メールの題名 (Comment this out if required)
var thisSubject = '今日の' + tokiboys1 + 'ちゃん' + tokiboys2 + 'ちゃん on ' + getDateString(dateFrom);
// Message Subject in English (Un-Comment this is required)
//var thisSubject = tokiboys1 + ' & ' + tokiboys2 + ' on ' + getDateString(dateFrom);
// メールの本文 (Comment this out if required)
var thisBody = '今日の' + tokiboys1 + 'と' + tokiboys2 + 'の写真を添付します。\n\n※ なお、写真を撮った日だけ翌日0時~1時に自動的に配信されます。\n\n';
// Message body (Uncomment this if required)
//var thisBody = '今日の' + tokiboys1 + 'と' + tokiboys2 + 'の写真を添付します。\n\n※ なお、写真を撮った日だけ翌日0時~1時に自動的に配信されます。\n\n';
// その他、システム更新情報など
// Changelog messages if you want to show your changelog messages...
var sysUpdateMsg = '\n\n';
// 本文フッター (Comment this out if required)
var thisBodyFooter = '\n\n\n' + papa + 'より';
// Body Footer (Uncomment this if required)
//var thisBodyFooter = '\n\n\n' + 'Love ' + papa;
var attachments = [];
// 写真のURLがあれば処理
// Do while URL
while(url){
// APIから詳細情報取得
// Fetch from API
var response = UrlFetchApp.fetch(url).getContentText();
// JSON保存
// Save to JSON
var responseObj = JSON.parse(response);
// 画像データ取得
// get image data
var photoData = responseObj.data;
// 画像データがあれば処理
// do while has image data
for(var i in photoData){
// Instagramの投稿日時を日付に変換
// Convert post date/time
var createdTime = new Date(parseInt(photoData[i].created_time) * 1000);
// 前日分を処理する
// Execute yesterday data only
if((createdTime >= dateFrom) && (createdTime <= dateTo)){
var fileUrl = '';
// 写真/動画切り分け
// Switch photo/movie
if(typeof photoData[i].videos == 'undefined'){
fileUrl = photoData[i].images.standard_resolution.url;
}else{
fileUrl = photoData[i].videos.standard_resolution.url;
}
var created_time = new Date(parseInt(photoData[i].caption.created_time) * 1000);
var captionTxt = renameFiles(photoData[i].caption.text, tokiboys1, tokiboys2, getDateTimeString(created_time));
// 場所
// get Place
var location_name = '';
if(photoData[i].location != null){
if(photoData[i].location.name != null){
location_name = photoData[i].location.name;
}
}
// 場所があれば追記
// add place
if(location_name){
captionTxt = captionTxt + '@' + location_name;
}
Logger.log(captionTxt);
var thisBlob = makeBlob(fileUrl, captionTxt);
eval('var attach' + i + ' = thisBlob;');
eval('attachments.push(attach' + i + ');');
}
}
// 次のページを取得
// get next page
url = responseObj.pagination.next_url;
}
// ファイルがあればメール送信
// create/send email if any photos/movies
if(attachments.length > 0){
// メッセージBody作成
// make message body
var finalBody = thisBody + sysUpdateMsg + thisBodyFooter;
// メールに添付して送信
// attachment
MailApp.sendEmail(toEmail, thisSubject,finalBody, {attachments: attachments});
}
success = true;
}catch(e){
errmsg = errmsg + '\n' + e;
retry++;
}
}
// リトライしてもエラーの場合
// error
if(success == false && retry == max_retry){
// エラーメール通知
// send error message
MailApp.sendEmail(Session.getActiveUser().getEmail(), 'send2gp Error ' + getDateTimeString(new Date()), errmsg);
Logger.log('failed');
}
}
// ファイル(画像・動画)作成
// create photos/movies blob
function makeBlob(fileUrl, captionTxt){
var contentType = '';
// 拡張子でContentType指定
// switch by file name
if(fileUrl.slice(-4) == '.jpg'){
contentType = 'image/jpeg';
}else if(fileUrl.slice(-4) == '.mp4'){
contentType = 'video/mp4';
}
var options =
{
'contentType' : contentType
};
return UrlFetchApp.fetch(fileUrl, options).getBlob().setName(captionTxt + fileUrl.slice(-4));
}
// ファイル名を作成
// create file name
function renameFiles(captionTxt, tokiboys1, tokiboys2, created_time){
// 写っている孫特定用タグ
// hashtags of my boys (can be set to any specific hashtags for your kids)
var REM_TAG1 = ' #tokiboys1'; // 長男
var REM_TAG2 = ' #tokiboys2'; // 二男
// 変換(画像を保存する時にファイル名に入れる)
// replace to my kids name
var REP_TAG1 = tokiboys1; // 長男の名前 My first boy's name.
var REP_TAG2 = tokiboys2; // 二男の名前 My second boy's name.
// REM_TAG2が含まれていればREP_TAG2を追加
// replace my second boy's hashtag to name
if(captionTxt.indexOf(REM_TAG2) !== -1){
captionTxt = REP_TAG2 + captionTxt;
}
// REM_TAG1が含まれていればREP_TAG1を追加
// replace my first boy"s hashtag to name
if(captionTxt.indexOf(REM_TAG1) !== -1){
captionTxt = REP_TAG1 + captionTxt;
}
// ハッシュタグ除去
// remove all hashtags
var regexp = new RegExp('#([^\\s]*)','g');
// 整形
// organize(finalize)
captionTxt = created_time + '_' + captionTxt.replace(/\s/g, '').replace(regexp, '');
return captionTxt;
}
// YYYY/MM/DDを取得
// fabricate YYYY/MM/DD
function getDateString(dateFrom){
return dateFrom.getFullYear().toString() + '/' + toDoubleDigits(dateFrom.getMonth()+1).toString() + '/' + toDoubleDigits(dateFrom.getDate()).toString();
}
// YYYY/MM/DD_HH:MM:SSを取得
// facbricate YYYY/MM/DD_HH:MM:SS
function getDateTimeString(dateFrom){
return dateFrom.getFullYear().toString() + '/' + toDoubleDigits(dateFrom.getMonth()+1).toString() + '/' + toDoubleDigits(dateFrom.getDate()).toString() + '_' + toDoubleDigits(dateFrom.getHours()).toString() + ':' + toDoubleDigits(dateFrom.getMinutes()).toString() + ':' + toDoubleDigits(dateFrom.getSeconds()).toString();
}
// 1桁の数字を0埋めで2桁にする
// add zero(0) to 1 digit numbers
var toDoubleDigits = function(num) {
num += '';
if (num.length === 1) {
num = '0' + num;
}
return num;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment