Module: PgDrive::Uploader

Defined in:
lib/pg_drive/uploader.rb

Constant Summary collapse

Drive =
Google::Apis::DriveV2
AUTH_SCOPE =
"https://www.googleapis.com/auth/drive".freeze
RETRY_COUNT =
3

Class Method Summary collapse

Class Method Details

.call(content) ⇒ Object



8
9
10
11
12
13
14
15
16
17
# File 'lib/pg_drive/uploader.rb', line 8

def call(content)
  drive = Drive::DriveService.new
  drive.authorization = credentials
  drive.insert_file(
    Drive::File.new(title: "backup-#{Time.now.to_i}"),
    upload_source: gzip(content),
    content_type: GZIP_MIME_TYPE,
    options: { retries: RETRY_COUNT }
  )
end

.client_idObject



27
28
29
# File 'lib/pg_drive/uploader.rb', line 27

def client_id
  Google::Auth::ClientId.new(google_key, google_secret)
end

.credentialsObject



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/pg_drive/uploader.rb', line 39

def credentials
  refresh_token = ENV["PG_DRIVE_CREDENTIALS"]
  if refresh_token.nil? || refresh_token.empty?
    raise InvalidEnvironment, MISSING_CRED_WARNING
  end
  Google::Auth::UserRefreshCredentials.new(
    client_id: google_key,
    client_secret: google_secret,
    refresh_token: refresh_token,
    scope: AUTH_SCOPE
  )
end

.google_keyObject



31
32
33
# File 'lib/pg_drive/uploader.rb', line 31

def google_key
  ENV.fetch("PG_DRIVE_GOOGLE_KEY")
end

.google_secretObject



35
36
37
# File 'lib/pg_drive/uploader.rb', line 35

def google_secret
  ENV.fetch("PG_DRIVE_GOOGLE_SECRET")
end

.gzip(string) ⇒ Object



19
20
21
22
23
24
25
# File 'lib/pg_drive/uploader.rb', line 19

def gzip(string)
  gzipped_io = StringIO.new
  writer = Zlib::GzipWriter.new(gzipped_io)
  writer.write(string)
  writer.close
  StringIO.new(gzipped_io.string)
end