Class: Helios::Videos::Processors::Cloudflare

Inherits:
Helios::Videos::Processor show all
Defined in:
lib/helios/videos/processors/cloudflare.rb

Constant Summary collapse

SIGNING_KEY_CACHE_KEY =
"helios_videos_cf_signing_key"
SIGNING_KEY_ID_CACHE_KEY =
"helios_videos_cf_signing_key_id"

Instance Attribute Summary

Attributes inherited from Helios::Videos::Processor

#config

Instance Method Summary collapse

Methods inherited from Helios::Videos::Processor

#initialize

Constructor Details

This class inherits a constructor from Helios::Videos::Processor

Instance Method Details

#delete!(video) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/helios/videos/processors/cloudflare.rb', line 48

def delete!(video)
  return unless video.key.present?

  uri = URI("https://api.cloudflare.com/client/v4/accounts/#{}/stream/#{video.key}")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Delete.new(uri.request_uri, {
    "Authorization" => "Bearer #{api_token}",
    "Content-Type" => "application/json"
  })

  response = http.request(request)

  if response.is_a?(Net::HTTPSuccess)
    Rails.logger.info("[helios-videos] Cloudflare video #{video.key} deleted")
  else
    Rails.logger.warn("[helios-videos] Failed to delete Cloudflare video #{video.key}: #{response.code}")
  end
end

#download_thumbnail!(video, time: "3s") ⇒ Object



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/helios/videos/processors/cloudflare.rb', line 116

def download_thumbnail!(video, time: "3s")
  return false unless video.key.present?
  return true if video.thumbnail_image.attached?

  subdomain = customer_subdomain(video)
  return false unless subdomain.present?

  if video.requires_signed_urls?
    token = signed_token(video, expiration: 1.hour)
    base_url = "https://#{subdomain}.cloudflarestream.com/#{token}/thumbnails/thumbnail.jpg"
  else
    base_url = "https://#{subdomain}.cloudflarestream.com/#{video.key}/thumbnails/thumbnail.jpg"
  end
  url = time.present? ? "#{base_url}?time=#{time}" : base_url

  require "open-uri"
  downloaded_image = URI.open(url)
  video.thumbnail_image.attach(
    io: downloaded_image,
    filename: "video_#{video.id}_thumbnail.jpg",
    content_type: "image/jpeg"
  )
  Rails.logger.info("[helios-videos] Downloaded thumbnail for video #{video.id}")
  true
rescue => e
  Rails.logger.error("[helios-videos] Failed to download thumbnail for video #{video.id}: #{e.message}")
  false
end

#ingest!(video) ⇒ Object



12
13
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
# File 'lib/helios/videos/processors/cloudflare.rb', line 12

def ingest!(video)
  return if video.key.present?
  return unless video.video_file.attached?

  uri = URI("https://api.cloudflare.com/client/v4/accounts/#{}/stream/copy")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Post.new(uri.request_uri, {
    "Authorization" => "Bearer #{api_token}",
    "Content-Type" => "application/json"
  })

  request.body = {
    url: video.video_file.url,
    meta: { name: video.name },
    requireSignedURLs: config.require_signed_urls
  }.to_json

  response = http.request(request)
  body = JSON.parse(response.body)

  unless response.is_a?(Net::HTTPSuccess)
    Rails.logger.error("[helios-videos] Cloudflare ingest error: #{response.code} - #{response.body}")
    raise "Cloudflare ingest failed: #{response.code}"
  end

  video.update!(
    key: body["result"]["uid"],
    playback_urls: body["result"]["playback"],
    requires_signed_urls: config.require_signed_urls
  )

  Rails.logger.info("[helios-videos] Video #{video.id} ingested into Cloudflare: #{video.key}")
end

#playback_url(video, signed: false, expiration: 4.hours) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
# File 'lib/helios/videos/processors/cloudflare.rb', line 69

def playback_url(video, signed: false, expiration: 4.hours)
  return nil unless video.key.present?

  if signed || video.requires_signed_urls?
    token = signed_token(video, expiration: expiration)
    subdomain = customer_subdomain(video)
    "https://#{subdomain}.cloudflarestream.com/#{token}/manifest/video.m3u8"
  else
    video.playback_urls&.dig("hls")
  end
end

#player_component(video, muted: false, expiration: 4.hours) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/helios/videos/processors/cloudflare.rb', line 81

def player_component(video, muted: false, expiration: 4.hours)
  return "(VIDEO NOT AVAILABLE)" unless video.key.present?

  video_src = playback_url(video, signed: video.requires_signed_urls?, expiration: expiration)

  <<~HTML.html_safe
    <video
      id="videojs-#{video.key}"
      class="video-js vjs-default-skin"
      style="width: 100%; height: 100%;"
      controls
      preload="auto"
      data-setup='{}'
      #{"muted" if muted}
    >
      <source src="#{video_src}" type="application/x-mpegURL" />
      Your browser does not support HLS video.
    </video>
  HTML
end

#signed_token(video, expiration: 4.hours) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/helios/videos/processors/cloudflare.rb', line 102

def signed_token(video, expiration: 4.hours)
  key_id, private_key = fetch_signing_key

  now = Time.now.to_i
  payload = {
    sub: video.key,
    kid: key_id,
    exp: now + expiration.to_i,
    nbf: now - 60
  }

  JWT.encode(payload, private_key, "RS256", typ: "JWT", kid: key_id)
end