Module: Pindo::IconDownloader

Defined in:
lib/pindo/module/build/icon_downloader.rb

Class Method Summary collapse

Class Method Details

.download_file_with_retry(url:, save_path:, max_retries: 3, retry_delay: 2, options: {}) ⇒ Boolean

带重试机制的文件下载

Parameters:

  • url (String)

    下载URL

  • save_path (String)

    保存路径

  • max_retries (Integer) (defaults to: 3)

    最大重试次数,默认3次

  • retry_delay (Integer) (defaults to: 2)

    重试间隔秒数,默认2秒

  • options (Hash) (defaults to: {})

    URI.open 的选项

Returns:

  • (Boolean)

    是否下载成功



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/pindo/module/build/icon_downloader.rb', line 14

def self.download_file_with_retry(url:, save_path:, max_retries: 3, retry_delay: 2, options: {})
  return false if url.nil? || url.empty?
  return false if save_path.nil? || save_path.empty?

  # 默认选项
  default_options = {
    read_timeout: 30,
    open_timeout: 10,
    redirect: true,
    ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE
  }
  merged_options = default_options.merge(options)

  # 确保目录存在
  save_dir = File.dirname(save_path)
  FileUtils.mkdir_p(save_dir) unless File.exist?(save_dir)

  attempt = 0
  last_error = nil

  while attempt < max_retries
    attempt += 1
    begin
      URI.open(url, merged_options) do |file|
        File.binwrite(save_path, file.read)
      end

      # 验证文件已下载
      if File.exist?(save_path) && File.size(save_path) > 0
        return true
      else
        raise "下载的文件为空或不存在"
      end
    rescue => e
      last_error = e
      if attempt < max_retries
        Funlog.instance.fancyinfo_error("下载失败 (第#{attempt}次): #{e.message}#{retry_delay}秒后重试...")
        sleep(retry_delay)
      end
    end
  end

  # 所有重试都失败
  Funlog.instance.fancyinfo_error("下载失败,已重试#{max_retries}次: #{last_error&.message}")
  false
end

.download_icon_with_retry(icon_url:, save_path:, max_retries: 3) ⇒ Boolean

带重试机制的 Icon 下载

Parameters:

  • icon_url (String)

    Icon的下载URL

  • save_path (String)

    保存路径

  • max_retries (Integer) (defaults to: 3)

    最大重试次数,默认3次

Returns:

  • (Boolean)

    是否下载成功



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/pindo/module/build/icon_downloader.rb', line 66

def self.download_icon_with_retry(icon_url:, save_path:, max_retries: 3)
  Funlog.instance.fancyinfo_start("正在从 JPS 下载项目 Icon...")

  success = download_file_with_retry(
    url: icon_url,
    save_path: save_path,
    max_retries: max_retries,
    retry_delay: 2
  )

  if success
    Funlog.instance.fancyinfo_success("Icon 下载成功!")
  else
    Funlog.instance.fancyinfo_error("Icon 下载失败!")
  end

  success
end