main();
function main(){
const filesIdArray = getFileIds();
const token = getToken();
for (let i = 0; i < filesIdArray.length; i++){
deleteFile(token, filesIdArray[i]);
}
}
/**
* データ項目からファイル ID を取得し、配列に入れて返す
* ID の数が通信制限を超えていればエラー
* @return {Array<String>} ファイル ID の配列
*/
function getFileIds(){
const fileIds = engine.findDataByNumber(configs.get("FileIdsItem"));
if (fileIds === null) {
throw "File / Folder IDs aren't set.";
}
let fileIdsArray = fileIds.split("\n");
fileIdsArray = fileIdsArray.filter(lines => lines !== ""); // 空文字列を削除
if (fileIdsArray.length === 0) {
throw "File / Folder IDs aren't set.";
}
if (fileIdsArray.length > httpClient.getRequestingLimit()){
//check number of files
throw "Number of File IDs is over the limit.";
}
return fileIdsArray;
}
/**
* トークンを取得する
* 指定されたユーザが削除されている場合、または Google Drive との連携設定がされていない場合はエラー
* @return {String} OAuth2 のトークン
*/
function getToken(){
const userId = configs.get("UserID");
const quser = quserDao.findById(parseInt(userId));
if (quser === null) {
throw `User not found: ${userId}`;
}
engine.log(`User Name: ${quser.getName()}`);
let token;
try{
token = httpClient.getGoogleOAuth2Token(quser, "Drive");
}catch(e){
throw "This User has not connected with Google Drive.";
}
return token;
}
/**
* ファイルを削除する
* メタデータの "trashed" パラメータを true にすることでファイルをゴミ箱に入れる
* 削除の結果をログ出力し、失敗した場合はエラーとする
* @param {String} token OAuth2 のトークン
* @param {String} fileId 削除するファイルの ID
*/
function deleteFile(token, fileId) {
const url = `https://www.googleapis.com/drive/v3/files/${fileId}`;
const body = {
trashed: true
};
let response = httpClient.begin()
.bearer(token)
.queryParam("supportsAllDrives", "true")
.body(JSON.stringify(body), "application/json; charset=UTF-8")
.patch(url);
const status = response.getStatusCode();
engine.log(`File ID: ${fileId} \nstatus: ${status}`);
if (status >= 300) {
engine.log(response.getResponseAsString());
throw `Failed to delete \nstatus: ${status} `;
}else{
engine.log("Delete successful");
}
}