Skip to content

Commit

Permalink
preload video poster upon page load
Browse files Browse the repository at this point in the history
  • Loading branch information
breunigs committed Dec 2, 2024
1 parent b1ea25e commit e787a69
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 2 deletions.
3 changes: 2 additions & 1 deletion lib/veloroute_web/endpoint.ex
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ defmodule VelorouteWeb.Endpoint do
websocket: true,
longpoll: false

socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
socket "/live", Phoenix.LiveView.Socket,
websocket: [connect_info: [:user_agent, session: @session_options]]

plug Video.ServePlug
plug Esri.Tiles
Expand Down
1 change: 1 addition & 0 deletions lib/veloroute_web/live/frame_live.ex
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ defmodule VelorouteWeb.FrameLive do
socket
|> update_map_bounds(params)
|> VelorouteWeb.Live.VideoState.maybe_update_video(article, params)
|> VelorouteWeb.Live.VideoState.maybe_preload_video_poster()
|> maybe_autoplay(params["autoplay"] == "true")

socket =
Expand Down
29 changes: 29 additions & 0 deletions lib/veloroute_web/live/video_state.ex
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,35 @@ defmodule VelorouteWeb.Live.VideoState do
end
end

def maybe_preload_video_poster(%{assigns: %{video_hash: hash, video_start: start_ms}} = socket) do
if !test_env?() && !Phoenix.LiveView.connected?(socket) && valid_hash(hash) &&
start_ms != nil && !probably_robot?(socket) do
Logger.debug("video poster async load start #{hash} #{start_ms}")

Task.start(VelorouteWeb.ImageExtractController, :extract, [
hash,
start_ms,
start_ms,
:webp
])
end

socket
end

def maybe_preload_video_poster(socket), do: socket

defp test_env?() do
Application.get_env(:veloroute, :env) == :test
end

defp probably_robot?(socket) do
ua = Phoenix.LiveView.get_connect_info(socket, :user_agent) |> String.downcase()

["http://", "https://", "bot", "ows.eu/owler", "python-requests", "okhttp"]
|> Enum.any?(&String.contains?(ua, &1))
end

@spec position_from_time(Phoenix.LiveView.Socket.t(), %{binary() => binary()}) ::
Video.Rendered.indicator() | nil
defp position_from_time(%{assigns: %{video: state}}, params) do
Expand Down
2 changes: 1 addition & 1 deletion lib/warmup.ex
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ defmodule Warmup do
end

defp initial_video_poster() do
Task.start_link(fn ->
Task.start(fn ->
with {hash, ts} <- VelorouteWeb.Live.VideoState.default_video_poster() do
VelorouteWeb.ImageExtractController.extract(hash, ts, ts, :webp)
end
Expand Down

0 comments on commit e787a69

Please sign in to comment.