Class: Lt::Lcms::Lesson::Downloader::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/lt/lcms/lesson/downloader/base.rb

Direct Known Subclasses

Gdoc, Gslide, Gspreadsheet, PDF

Constant Summary collapse

RETRY_DELAYES =
[10.seconds, 30.seconds, 45.seconds, 1.minute, 3.minutes].freeze
MAX_RETRY_COUNT =
RETRY_DELAYES.size
MIME_TYPE_EXPORT =
'text/plain'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(credentials, file_url, opts = {}) ⇒ Base

Returns a new instance of Base.



21
22
23
24
25
# File 'lib/lt/lcms/lesson/downloader/base.rb', line 21

def initialize(credentials, file_url, opts = {})
  @credentials = credentials
  @file_url = file_url
  @options = opts
end

Instance Attribute Details

#contentObject (readonly)

Returns the value of attribute content.



19
20
21
# File 'lib/lt/lcms/lesson/downloader/base.rb', line 19

def content
  @content
end

Class Method Details

.file_id_for(url) ⇒ Object



14
15
16
17
# File 'lib/lt/lcms/lesson/downloader/base.rb', line 14

def self.file_id_for(url)
  url.scan(%r{/d/([^/]+)/?}).first.try(:first) ||
    url.scan(%r{/open\?id=([^/]+)/?}).first.try(:first)
end

Instance Method Details

#download(mime_type: self.class::MIME_TYPE_EXPORT) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/lt/lcms/lesson/downloader/base.rb', line 27

def download(mime_type: self.class::MIME_TYPE_EXPORT)
  retry_attempt ||= 0
  raw_content = service
                  .export_file(file_id, mime_type)
                  .encode('ASCII-8BIT')
                  .force_encoding('UTF-8')
  @content =
    if block_given?
      yield raw_content
    else
      raw_content
    end
  self
rescue ::Google::Apis::RateLimitError
  raise unless options[:import_retry]
  raise if retry_attempt >= MAX_RETRY_COUNT

  sleep RETRY_DELAYES[retry_attempt] * rand(1.0..5.0)
  retry_attempt += 1
  retry
end

#fileObject



49
50
51
52
53
54
55
# File 'lib/lt/lcms/lesson/downloader/base.rb', line 49

def file
  @file ||= service.get_file(
    file_id,
    fields: 'lastModifyingUser,modifiedTime,name,version',
    supports_all_drives: true
  )
end

#file_idObject



57
58
59
# File 'lib/lt/lcms/lesson/downloader/base.rb', line 57

def file_id
  @file_id ||= self.class.file_id_for @file_url
end