class Applocale::GoogleHelper

Constants

APPLICATION_NAME
CLIENT_SECRETS_PATH
OOB_URI
SCOPE

Attributes

credential_path[RW]
spreadsheet_id[RW]
xlsx_path[RW]

Public Class Methods

get_spreadsheet_id(link) click to toggle source
# File lib/applocale/Core/GoogleHepler/google_helper.rb, line 181
def self.get_spreadsheet_id(link)
  if !link.nil? && link.length > 0
    if link.match(/https:\/\/docs.google.com\/spreadsheets\/d\/([^\/]*)/i)
      if $1.strip.length > 0
        return $1.strip
      end
    end
  end
  ErrorUtil::DownloadFromGoogleFail.new.raise
end
new(link, credential_path, xlsx_path) click to toggle source
# File lib/applocale/Core/GoogleHepler/google_helper.rb, line 22
def initialize(link, credential_path, xlsx_path)
  self.download_link = link.to_s.strip
  self.credential_path = credential_path.to_s.strip
  self.xlsx_path = xlsx_path.to_s.strip
  self.spreadsheet_id = GoogleHelper.get_spreadsheet_id(link)

  if self.download_link.length <= 0
    ErrorUtil::ConfigFileInValid.new('[link] is missing in config file ').raise
  end
  if self.credential_path.length <= 0
    ErrorUtil::ConfigFileInValid.new('[credential_path] is missing in config file ').raise
  end
  if self.xlsx_path.length <= 0
    ErrorUtil::ConfigFileInValid.new('[xlsx_path] is missing in config file ').raise
  end
end

Public Instance Methods

download(sheet_obj_list, export_format:, export_to:) click to toggle source
# File lib/applocale/Core/GoogleHepler/google_helper.rb, line 45
def download(sheet_obj_list, export_format:, export_to:)
  FileUtils.mkdir_p(export_to) unless File.directory?(export_to)
  remove_old_files(from: export_to)
  authorization = authorize
  begin
    case export_format
      when 'csv'
        service = Google::Apis::SheetsV4::SheetsService.new
        service.client_options.application_name = APPLICATION_NAME
        service.authorization = authorization
        sheets = service.get_spreadsheet(self.spreadsheet_id).sheets
        sheetMap = {}
        sheets.each do |sheet|
          sheetMap[sheet.properties.title.to_s] = sheet.properties.sheet_id
        end

        index = 0
        Parallel.each(sheet_obj_list) do |sheet_obj|
        sheet_name = sheet_obj.sheetname
        file_path = File.expand_path("#{sheet_name}.csv", export_to)
        if sheetMap[sheet_name].nil?
          ErrorUtil::SheetNotExist.new(sheet_name).raise
        end
        if !sheet_obj.obj.use_export
          link = "https://docs.google.com/spreadsheets/d/#{self.spreadsheet_id}/gviz/tq?tqx=out:csv&sheet=#{sheet_name}&access_token=#{authorization.access_token}"
          puts "\nto download sheet: #{sheet_name}\nhttps://docs.google.com/spreadsheets/d/#{self.spreadsheet_id}/gviz/tq?tqx=out:csv&sheet=#{sheet_name}&access_token=xxxxx"
          csv = open(link)
          IO.copy_stream(csv, file_path)
        else
          if index % 3 == 0
            puts "please wait ... "
            sleep(5)
          else
            puts "please wait .. "
            sleep(2)
          end
          link =  "https://docs.google.com/spreadsheets/d/#{self.spreadsheet_id}/export?format=csv&gid=#{sheetMap[sheet_name]}&access_token=#{authorization.access_token}"
          puts "\nto download sheet: #{sheet_name}\nhttps://docs.google.com/spreadsheets/d/#{self.spreadsheet_id}/export?format=csv&gid=#{sheetMap[sheet_name]}&access_token=xxxxx"
          File.open(file_path, "wb") do |file|
            file.write open(link).read
          end
          index = index + 1
        end
        end
    when 'xlsx'
      service = Google::Apis::DriveV3::DriveService.new
      service.client_options.application_name = APPLICATION_NAME
      service.authorization = authorization
      service.export_file(self.spreadsheet_id,
                          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                          download_dest: self.xlsx_path)
    end

    if Dir["#{export_to}/*"].any?
      puts 'Download from google finished'.green
    else
      ErrorUtil::DownloadFromGoogleFail.new.raise
    end
  rescue Google::Apis::AuthorizationError => e
    failauth
  rescue Google::Apis::ClientError => e
    failauth
  rescue Google::Apis::ServerError => e
    failauth
  rescue => execption
    ErrorUtil.raise(execption)
  end
end

Private Instance Methods

askfor_relogin(is_firsttime) click to toggle source
# File lib/applocale/Core/GoogleHepler/google_helper.rb, line 121
def askfor_relogin(is_firsttime)
  unless is_firsttime
    puts "Invalid Command. Please input [Y/N]".red
  end
  puts "login again? [Y/N]".red
  code = STDIN.gets.chomp.downcase
  if code == 'y'
    reset_loginacc
    self.download
  elsif code == 'n'
    exit(0)
  else
    askfor_relogin(false)
  end
end
authorize() click to toggle source
# File lib/applocale/Core/GoogleHepler/google_helper.rb, line 138
def authorize
  FileUtils.mkdir_p(File.dirname(self.credential_path))
  client_id = Google::Auth::ClientId.from_file(File.expand_path(CLIENT_SECRETS_PATH, File.dirname(__FILE__)))
  token_store = Google::Auth::Stores::FileTokenStore.new(file: self.credential_path)
  authorizer = Google::Auth::UserAuthorizer.new(
      client_id, SCOPE, token_store)
  user_id = 'default'
  credentials = authorizer.get_credentials(user_id)
  if credentials.nil?
    url = authorizer.get_authorization_url(
        base_url: OOB_URI)
    puts '!!! Open the following URL in the browser and enter the '.red +
             'resulting code after authorization:'.red
    puts url.blue.on_white
    code = STDIN.gets.chomp
    credentials = authorizer.get_and_store_credentials_from_code(
        user_id: user_id, code: code, base_url: OOB_URI)
  end
  credentials.refresh! if credentials.expired?
  credentials
end
failauth() click to toggle source
# File lib/applocale/Core/GoogleHepler/google_helper.rb, line 115
def failauth
  ErrorUtil::DownloadFromGoogleFail.new.to_warn
  askfor_relogin(true)
end
remove_old_files(from:) click to toggle source
# File lib/applocale/Core/GoogleHepler/google_helper.rb, line 40
def remove_old_files(from:)
  FileUtils.rm_rf Dir.glob("#{from}/*.{csv,xlsx}") if File.directory?(from)
end
reset_loginacc() click to toggle source
# File lib/applocale/Core/GoogleHepler/google_helper.rb, line 161
def reset_loginacc
  if File.exist? self.credential_path
    File.delete(self.credential_path)
  end
  puts "Account Reseted!"
end