Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions backend/src/api/model/block/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,7 @@ pub(crate) struct VideoBlock {
pub(crate) event: Option<Id>,
pub(crate) show_title: bool,
pub(crate) show_link: bool,
pub(crate) show_metadata: bool,
}

impl_block!(VideoBlock);
Expand All @@ -239,6 +240,10 @@ impl VideoBlock {
self.show_link
}

fn show_metadata(&self) -> bool {
self.show_metadata
}

fn id(&self) -> Id {
Block::id(self)
}
Expand Down Expand Up @@ -356,6 +361,7 @@ impl_from_db!(
event: row.video::<Option<Key>>().map(Id::event),
show_title: unwrap_type_dep(row.show_title(), "event", "show_title"),
show_link: unwrap_type_dep(row.show_link(), "event", "show_link"),
show_metadata: unwrap_type_dep(row.show_metadata(), "event", "show_metadata"),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This made me wonder about existing video blocks. The show_metadata column is not NOT NULL, i.e. it can be null, but it has a default of false. So all added blocks have false in that column, which is also true for our test DB dumps. So I guess the only way a null could sneak in there if we set it explicitly right? And from grepping the code base it does not seem like there is any way Tobira sets it to null.

So I guess it's fine! For series and playlist we have a DB constraint to make sure its not null and I guess it would be nice for events as well, but no need to introduce a new migration in this PR. So yeah, just wanted to write down my reasoning here, no need for action.

}.into(),

BlockType::Playlist => PlaylistBlock {
Expand Down
10 changes: 6 additions & 4 deletions backend/src/api/model/block/mutations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,17 +109,17 @@ impl BlockValue {
let (realm, index) = Self::prepare_realm_for_block(realm, index, context).await?;
let event = block.event.key_for(Id::EVENT_KIND)
.ok_or_else(|| invalid_input!("`block.event` does not refer to an event"))?;

context.db
.execute(
"insert into blocks (realm, index, type, video, show_title, show_link) \
values ($1, $2, 'video', $3, $4, $5)",
"insert into blocks (realm, index, type, video, show_title, show_link,show_metadata) \
values ($1, $2, 'video', $3, $4, $5, $6)",
&[
&realm.key,
&index,
&event,
&block.display_options.show_title,
&block.display_options.show_link,
&block.display_options.show_metadata,
],
)
.await?;
Expand Down Expand Up @@ -386,7 +386,8 @@ impl BlockValue {
"update blocks set \
video = coalesce($2, video), \
show_title = coalesce($3, show_title), \
show_link = coalesce($4, show_link) \
show_link = coalesce($4, show_link), \
show_metadata = coalesce($5, show_metadata) \
where id = $1 \
and type = 'video' \
returning {selection}",
Expand All @@ -397,6 +398,7 @@ impl BlockValue {
&video_id,
&set.display_options.show_title,
&set.display_options.show_link,
&set.display_options.show_metadata,
])
.await?
.pipe(|row| Ok(Self::from_row_start(&row)))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
-- Adds a single `show_metadata` field to blocks, used for video blocks to also show
-- metadata below the video player.

-- Ensure that all existing video blocks have a value for `show_metadata` (defaulting to false).
update blocks set show_metadata = false where type = 'video' and show_metadata is null;

alter table blocks
drop constraint video_block_has_fields,
add constraint video_block_has_fields check (type <> 'video' or (
show_title is not null and
show_link is not null and
show_metadata is not null
));
2 changes: 1 addition & 1 deletion frontend/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ type SyncConfig = {
pollPeriod: number;
};

type MetadataLabel = "builtin:license" | "builtin:source" | TranslatedString;
export type MetadataLabel = "builtin:license" | "builtin:source" | TranslatedString;

export type TranslatedString = { default: string } & Record<"en" | "de", string | undefined>;

Expand Down
199 changes: 18 additions & 181 deletions frontend/src/routes/Video.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React, {
ReactNode,
useEffect,
useRef,
useState,
Expand All @@ -14,13 +13,11 @@ import {
LuCode, LuDownload, LuInfo, LuLink, LuRss, LuSettings, LuLockOpen,
} from "react-icons/lu";
import {
match, unreachable, screenWidthAtMost, screenWidthAbove, useColorScheme,
unreachable, screenWidthAtMost, screenWidthAbove, useColorScheme,
Floating, FloatingContainer, FloatingTrigger, WithTooltip, Card, Button,
notNullish,
ProtoButton,
} from "@opencast/appkit";
import { VideoObject, WithContext } from "schema-dts";
import { TFunction } from "i18next";

import { fetchQuery, loadQuery } from "../relay";
import { InitialLoading, RootLoader } from "../layout/Root";
Expand All @@ -37,7 +34,6 @@ import {
isSynced,
toIsoDuration,
useForceRerender,
translatedConfig,
secondsToTimeString,
eventId,
keyOfId,
Expand All @@ -49,7 +45,7 @@ import {
import { BREAKPOINT_SMALL, BREAKPOINT_MEDIUM } from "../GlobalStyle";
import { LinkButton } from "../ui/LinkButton";
import CONFIG from "../config";
import { Link, useRouter } from "../router";
import { useRouter } from "../router";
import { isRealUser, useUser } from "../User";
import { b64regex, checkRealmPath } from "./util";
import { NotAuthorized } from "../ui/error";
Expand All @@ -71,13 +67,13 @@ import {
PlaylistBlockPlaylistData$key,
} from "../ui/Blocks/__generated__/PlaylistBlockPlaylistData.graphql";
import { getEventTimeInfo } from "../util/video";
import { formatDuration, TrackInfo } from "../ui/Video";
import { TrackInfo } from "../ui/Video";
import { ellipsisOverflowCss } from "../ui";
import { realmBreadcrumbs } from "../util/realm";
import { COLORS } from "../color";
import { preciseDateTime, preferredLocaleForLang, PrettyDate } from "../ui/time";
import { PlayerContextProvider, usePlayerContext } from "../ui/player/PlayerContext";
import { CollapsibleDescription } from "../ui/metadata";
import { MetadataSection, MetadataSectionSeriesLink } from "../ui/metadata";
import { DirectSeriesRoute, SeriesRoute } from "./Series";
import { EmbedVideoRoute } from "./Embed";
import { ManageVideoDetailsRoute } from "./manage/Video/VideoDetails";
Expand All @@ -97,7 +93,6 @@ import { isSpaceOnInteractiveElement } from "../ui/player/PlayerShortcuts";
import { VideoListLayout } from "../ui/Blocks/__generated__/SeriesBlockData.graphql";
import { LIST_ORDERS, Order } from "../ui/Blocks/VideoList";


// ===========================================================================================
// ===== Route definitions
// ===========================================================================================
Expand Down Expand Up @@ -898,32 +893,6 @@ const Metadata: React.FC<MetadataProps> = ({ event, realmPath }) => {
const user = useUser();
const { paella, playerIsLoaded } = usePlayerContext();

const autoTimestampProcessor = (text: string) => {
const timestampRegex = /((?<!\S)(?:\d?\d:)?\d?\d:\d{2}(?!\S))/g;
return <>{text.split(timestampRegex).map((part, index) => {
if (!part.match(timestampRegex)) {
return part;
}
const parts = part.split(":").map(Number);
const [hours, minutes, seconds] = parts.length === 2 ? [0, ...parts] : parts;
const timestamp = ((hours * 60) + minutes) * 60 + seconds;
if (timestamp * 1000 > event.syncedData.duration) {
return part;
}

return <ProtoButton
key={index}
onClick={() => paella.current?.player.videoContainer.setCurrentTime(timestamp)}
css={{
color: COLORS.primary0,
":hover": {
color: COLORS.primary1,
},
}}
>{part}</ProtoButton>;
})}</>;
};

const shrinkOnMobile = {
[screenWidthAtMost(BREAKPOINT_SMALL)]: {
padding: "5px 10px",
Expand Down Expand Up @@ -974,32 +943,23 @@ const Metadata: React.FC<MetadataProps> = ({ event, realmPath }) => {
/>
</section>
</div>
<div css={{
display: "flex",
flexWrap: "wrap",
gap: 16,
"> div": {
backgroundColor: COLORS.neutral10,
borderRadius: 8,
[screenWidthAtMost(BREAKPOINT_MEDIUM)]: {
overflowWrap: "anywhere",
},
},
}}>
<CollapsibleDescription
type="video"
description={event.description}
creators={event.creators}
bottomPadding={40}
textProcessor={autoTimestampProcessor}
/>
<div css={{ flex: "1 200px", alignSelf: "flex-start", padding: "20px 22px" }}>
<MetadataTable {...{ event, realmPath }} />
</div>
</div>
<MetadataSection
event={event}
valueStyle="line-break"
seriesLink={getSeriesLink(event.series, realmPath)}
/>
</>;
};

export const getSeriesLink = (
series: { id: string; title: string } | null | undefined,
realmPath: string | null,
): MetadataSectionSeriesLink | undefined => series ? {
title: series.title,
url: realmPath == null
? DirectSeriesRoute.url({ seriesId: series.id })
: SeriesRoute.url({ seriesId: series.id, realmPath }),
} : undefined;

const DownloadButton: React.FC<{ event: SyncedEvent }> = ({ event }) => {
const { t } = useTranslation();
Expand Down Expand Up @@ -1217,126 +1177,3 @@ const VideoDate: React.FC<VideoDateProps> = ({ event }) => {
);
};

type MetadataTableProps = {
event: Event;
realmPath: string | null;
};

const MetadataTable = React.forwardRef<HTMLDListElement, MetadataTableProps>(({
event, realmPath,
}, ref) => {
const { t, i18n } = useTranslation();
const pairs: [string, ReactNode][] = [];

if (event.series) {
const seriesId = event.series.id;
const target = realmPath == null
? DirectSeriesRoute.url({ seriesId })
: SeriesRoute.url({ seriesId, realmPath });
pairs.push([
t("video.part-of-series"),
// eslint-disable-next-line react/jsx-key
<Link to={target}>
{event.series.title}
</Link>,
]);
}

if (event.metadata.dcterms.language) {
const languageNames = new Intl.DisplayNames(i18n.resolvedLanguage, { type: "language" });
const languages = event.metadata.dcterms.language.map(lng => languageNames.of(lng) ?? lng);

pairs.push([
t("general.language.language", { count: languages.length }),
languages.join(", "),
]);
}

for (const [namespace, fields] of Object.entries(CONFIG.metadataLabels)) {
const metadataNs = event.metadata[namespace];
if (metadataNs === undefined) {
continue;
}

for (const [field, label] of Object.entries(fields)) {
if (field in metadataNs) {
const translatedLabel = typeof label === "object"
? translatedConfig(label, i18n)
: match(label, {
"builtin:license": () => t("video.license"),
"builtin:source": () => t("video.source"),
});

const values = metadataNs[field].map((value, i) => {
const displayValue = (
label === "builtin:license" && value in LICENSE_TRANSLATIONS
) ? LICENSE_TRANSLATIONS[value](t) : value;

return <React.Fragment key={i}>
{i > 0 && <br />}
{isValidLink(displayValue)
? <Link to={displayValue}>{displayValue}</Link>
: displayValue
}
</React.Fragment>;
});

pairs.push([translatedLabel, values]);
}
}
}

if (event.syncedData?.duration && !event.isLive) {
pairs.push([
t("video.duration"),
formatDuration(event.syncedData.duration),
]);
}

return (
<dl ref={ref} css={{
display: "grid",
gridTemplateColumns: "max-content 1fr",
columnGap: 8,
rowGap: 6,
fontSize: 14,
lineHeight: 1.3,
"& > dt::after": {
content: "':'",
},
"& > dd": {
color: COLORS.neutral60,
},
}}>
{pairs.map(([label, value], i) => <React.Fragment key={i}>
<dt>{label}</dt>
<dd>{value}</dd>
</React.Fragment>)}
</dl>
);
});

const LICENSE_TRANSLATIONS: Record<string, (t: TFunction) => string> = {
"ALLRIGHTS": (t: TFunction) => t("license.all-rights"),
"CC-BY": () => "CC BY",
"CC-BY-SA": () => "CC BY-SA",
"CC-BY-ND": () => "CC BY-ND",
"CC-BY-NC": () => "CC BY-NC",
"CC-BY-NC-SA": () => "CC BY-NC-SA",
"CC-BY-NC-ND": () => "CC BY-NC-ND",
};

const isValidLink = (s: string): boolean => {
const trimmed = s.trim();
if (!(trimmed.startsWith("http://") || trimmed.startsWith("https://"))) {
return false;
}

try {
new URL(trimmed);
} catch (_) {
return false;
}

return true;
};
1 change: 1 addition & 0 deletions frontend/src/routes/manage/Realm/Content/AddButtons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ const AddButtonsMenu: React.FC<Props & {floatingRef: RefObject<FloatingHandle>}>
[LuFilm, "video", () => addBlock("Video", (_store, block) => {
block.setValue(true, "showTitle");
block.setValue(true, "showLink");
block.setValue(false, "showMetadata");
})],
[LuListVideo, "playlist", () => addBlock("Playlist", (_store, block) => {
block.setValue("ORIGINAL", "order");
Expand Down
Loading
Loading