Google Driveのアップデートで、各アイテムのURLに「リソースキー」が付与されることとなりました。
これに伴って、DriveAppにもAPIが追加されました。
- DriveApp.getFolderByIdAndResourceKey(id, resourceKey)
- DriveApp.getFileByIdAndResourceKey(id, resourceKey)
現時点でのDriveAppには残念ながらURLからフォルダやファイルを取得するAPIが用意されていません。
そこで本記事では、URLからフォルダやファイルを取得するコードを紹介します。
コード
URLのパターンとしては以下の4パターンあります。(ファイルについてはファイルの種別によって先頭のURLが変わります)
- https://drive.google.com/drive/folders/{フォルダID}
- https://drive.google.com/drive/folders/{フォルダID}?resourcekey={リソースキー}
- https://drive.google.com/file/d/{ファイルID}/view?usp=sharing
- https://drive.google.com/file/d/{ファイルID}/view?usp=sharing&resourcekey={リソースキー}
今回はこの4パターンに対応したコードです。以下の2つの関数を作成しました。URLを渡せばフォルダやファイルのオブジェクトが返ってきます。
- URLからフォルダを取得するgetFolderByUrl関数
- URLからファイルを取得するgetFileByUrl関数
コード.gs
function myFunction() {
// URLからフォルダを取得
const folderUrl = 'https://drive.google.com/drive/folders/xxxxxxxxxx?resourcekey=yyyyyyyyyyyy'
const folder = getFolderByUrl(folderUrl)
console.log(folder.getName())
// URLからファイルを取得
const fileUrl = 'https://drive.google.com/file/d/xxxxxxxxxx/view?usp=sharing&resourcekey=yyyyyyyyyyyy'
const file = getFileByUrl(fileUrl)
console.log(file.getName())
}
それぞれの関数は以下の通りです。
関数.gs
// URLからフォルダを取得する
function getFolderByUrl(url) {
const info = getIdAndResourcekeyByUrl(url, true)
if (info['resourcekey']) {
return DriveApp.getFolderByIdAndResourceKey(info['id'], info['resourcekey'])
} else {
return DriveApp.getFolderById(info['id'])
}
}
// URLからファイルを取得する
function getFileByUrl(url) {
const info = getIdAndResourcekeyByUrl(url, false)
if (info['resourcekey']) {
return DriveApp.getFileByIdAndResourceKey(info['id'], info['resourcekey'])
} else {
return DriveApp.getFileById(info['id'])
}
}
// アイテム情報オブジェクトを取得する
function getIdAndResourcekeyByUrl(url, isFolder=true) {
return {
'id': getIdByUrl(url, isFolder),
'resourcekey': getQueryParamsByUrl(url)['resourcekey']
}
}
// URLからアイテムIDを取得する
function getIdByUrl(url, isFolder=true) {
if (!url || url === '') {
throw Error('無効なURL')
}
// スラッシュでURLを分割
const splitedUrl = url.split('/')
// idの前に来る特定の文字列
let searchString = 'd'
if (isFolder) {
searchString = 'folders'
}
let id = ''
for (let i=0; i<splitedUrl.length; i++) {
// 特定の文字列に一致する場合はidを取得
if (splitedUrl[i] === searchString && splitedUrl[i+1]) {
id = splitedUrl[i+1]
break
}
}
// クエリパラメータは除去
return id.split('?')[0]
}
// URLからクエリパラメータを取得
function getQueryParamsByUrl(url) {
const params = {}
if (url.split('?').length < 0) {
// クエリパラメータがない
return params
}
// クエリパラメータの文字列を取得
const queryUrl = url.split('?')[1]
if (queryUrl) {
// パラメータ毎にキーと値を抽出
const queryRawParams = queryUrl.split('&')
queryRawParams.forEach(function(value, index) {
const kv = value.split('=')
params[kv[0]] = kv[1]
})
return params
}
// 全てのキーと値を持ったオブジェクトを返却
return params
}