Google APIを使ってファイルの親ディレクトリを調べる
仕事しているとGoogleスプレッドシートのURLやらDocのURLやらを教えていただくのですが、親ディレクトリが知りたいときとかあると思います。
コピーして使うときとか、そもそも何が入ってるんだっけ?みたいな。
Webで使い方を調べても良かったのですが、訓練だと思ってAPI経由で調べる方法を探してみました。
module Ore class Benri def self.parent_dir(file_id) session = create_session file = session.spreadsheet_by_key(file_id) file.parents.first.self_link.gsub(/parents\//,"").gsub(/www.googleapis/,"drive.google").gsub(/v2\/files/,"#folders") end def self.create_session client = Google::APIClient.new auth = client.authorization auth.client_id = ENV['GOOGLE_DRIVE_CLIENT_ID'] auth.client_secret = ENV['GOOGLE_DRIVE_CLIENT_SECRET'] auth.scope = Settings.analytics.google.auth.scope auth.redirect_uri = Settings.analytics.google.auth.redirect_url auth.refresh_token = ENV['GOOGLE_DRIVE_REFRESH_TOKEN'] begin auth.fetch_access_token! rescue Signet::AuthorizationError puts('1. Open this page:\n%s\n\n' % auth.authorization_uri) puts('2. Enter the authorization code shown in the page: ') auth.code = $stdin.gets.chomp auth.fetch_access_token! end ENV['GOOGLE_DRIVE_REFRESH_TOKEN'] = auth.refresh_token GoogleDrive.login_with_oauth(auth.access_token) end end end # how to use? ### Ore::Benri.parent_dir("fileのid")