feat: Add folder title matching and parsing (#2067)
This is a breaking change for users of the [experimental 'folder' functionality](https://card.camera/#/configuration/folders). Related: #1748
This commit is contained in:
@@ -7,7 +7,13 @@ import {
|
||||
HAFolderPathComponent,
|
||||
} from '../../../config/schema/folders';
|
||||
import { getViewItemsFromBrowseMediaArray } from '../../../ha/browse-media/browse-media-to-view-media';
|
||||
import { BrowseMedia, BrowseMediaCache } from '../../../ha/browse-media/types';
|
||||
import { BrowseMediaViewFolder } from '../../../ha/browse-media/item';
|
||||
import {
|
||||
BrowseMedia,
|
||||
BrowseMediaCache,
|
||||
BrowseMediaMetadata,
|
||||
RichBrowseMedia,
|
||||
} from '../../../ha/browse-media/types';
|
||||
import {
|
||||
BrowseMediaStep,
|
||||
BrowseMediaTarget,
|
||||
@@ -26,13 +32,24 @@ import {
|
||||
FolderQuery,
|
||||
FoldersEngine,
|
||||
} from '../types';
|
||||
import { MediaMatcher } from './media-matcher';
|
||||
import { MetadataGenerator } from './metadata-generator.js';
|
||||
|
||||
export class HAFoldersEngine implements FoldersEngine {
|
||||
private _browseMediaManager: BrowseMediaWalker;
|
||||
private _cache = new BrowseMediaCache();
|
||||
private _cache = new BrowseMediaCache<BrowseMediaMetadata>();
|
||||
|
||||
public constructor(browseMediaManager?: BrowseMediaWalker) {
|
||||
this._browseMediaManager = browseMediaManager ?? new BrowseMediaWalker();
|
||||
private _metadataGenerator: MetadataGenerator;
|
||||
private _mediaMatcher: MediaMatcher;
|
||||
|
||||
public constructor(options?: {
|
||||
browseMediaManager?: BrowseMediaWalker;
|
||||
metadataGenerator?: MetadataGenerator;
|
||||
mediaMatcher?: MediaMatcher;
|
||||
}) {
|
||||
this._browseMediaManager = options?.browseMediaManager ?? new BrowseMediaWalker();
|
||||
this._metadataGenerator = options?.metadataGenerator ?? new MetadataGenerator();
|
||||
this._mediaMatcher = options?.mediaMatcher ?? new MediaMatcher();
|
||||
}
|
||||
|
||||
public getItemCapabilities(item: ViewItem): ViewItemCapabilities | null {
|
||||
@@ -75,6 +92,23 @@ export class HAFoldersEngine implements FoldersEngine {
|
||||
};
|
||||
}
|
||||
|
||||
private getDefaultFolderPathComponents(
|
||||
haFolderConfig?: HAFolderConfig,
|
||||
): NonEmptyTuple<FolderPathComponent> {
|
||||
const shouldAddDefaultRoot = !haFolderConfig?.url && !haFolderConfig?.path?.[0]?.id;
|
||||
|
||||
const path: HAFolderPathComponent[] = [
|
||||
...(shouldAddDefaultRoot ? [{ id: HA_MEDIA_SOURCE_ROOT }] : []),
|
||||
...(haFolderConfig?.url ?? []),
|
||||
...(haFolderConfig?.path ?? []),
|
||||
];
|
||||
|
||||
return path.map((component) => ({ ha: component })) as [
|
||||
FolderPathComponent,
|
||||
...FolderPathComponent[],
|
||||
];
|
||||
}
|
||||
|
||||
public async expandFolder(
|
||||
hass: HomeAssistant,
|
||||
query: FolderQuery,
|
||||
@@ -89,11 +123,16 @@ export class HAFoldersEngine implements FoldersEngine {
|
||||
// Search through the path components from the start to find the last
|
||||
// component with a precise media source id, which is where the queries
|
||||
// start (and may drill down from).
|
||||
let start: string | null = null;
|
||||
let start: string | RichBrowseMedia<BrowseMediaMetadata> | null = null;
|
||||
while (pathComponents.length > 0) {
|
||||
const id = pathComponents[0]?.id;
|
||||
if (id) {
|
||||
start = id;
|
||||
const folderBrowseMedia =
|
||||
pathComponents[0]?.folder instanceof BrowseMediaViewFolder
|
||||
? pathComponents[0].folder.getBrowseMedia()
|
||||
: null;
|
||||
|
||||
const validStart = folderBrowseMedia ?? pathComponents[0]?.ha?.id ?? null;
|
||||
if (validStart) {
|
||||
start = validStart;
|
||||
pathComponents.shift();
|
||||
} else {
|
||||
break;
|
||||
@@ -106,37 +145,38 @@ export class HAFoldersEngine implements FoldersEngine {
|
||||
return null;
|
||||
}
|
||||
|
||||
// This matcher matches a browse media against a given path component.
|
||||
const componentMatcher = (
|
||||
media: BrowseMedia,
|
||||
component?: FolderPathComponent,
|
||||
): boolean => {
|
||||
return (
|
||||
!component ||
|
||||
(media.can_expand &&
|
||||
(component.ha?.title === media.title ||
|
||||
(component.ha?.title_re &&
|
||||
new RegExp(component.ha.title_re).test(media.title)) ||
|
||||
component.id === media.media_content_id))
|
||||
);
|
||||
};
|
||||
await this._metadataGenerator.prepare(
|
||||
pathComponents.flatMap((component) => component.ha?.parsers ?? []),
|
||||
);
|
||||
|
||||
// Generate a walk step, optionally matching against the next path component
|
||||
// (if any), otherwise just returning all the media at this level.
|
||||
const generateStep = (targets: BrowseMediaTarget[]): BrowseMediaStep[] => {
|
||||
const generateStep = (
|
||||
targets: BrowseMediaTarget<BrowseMediaMetadata>[],
|
||||
): BrowseMediaStep<BrowseMediaMetadata>[] => {
|
||||
const nextComponent = pathComponents.shift();
|
||||
return [
|
||||
{
|
||||
targets,
|
||||
metadataGenerator: (media: BrowseMedia, parent?: BrowseMedia) =>
|
||||
this._metadataGenerator.generate(media, parent, nextComponent?.ha?.parsers),
|
||||
|
||||
...(nextComponent && {
|
||||
matcher: (media: BrowseMedia) => componentMatcher(media, nextComponent),
|
||||
advance: (targets) => generateStep(targets),
|
||||
matcher: (media: BrowseMedia) =>
|
||||
this._mediaMatcher.match(
|
||||
media,
|
||||
nextComponent.ha?.matchers,
|
||||
// Set foldersOnly to true if there are more stages in the path,
|
||||
// as by definition only folders can be matched at this point.
|
||||
pathComponents.length > 0,
|
||||
),
|
||||
advance: (targets) => (pathComponents.length ? generateStep(targets) : []),
|
||||
}),
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
const browseMedia = await this._browseMediaManager.walk(
|
||||
const browseMedia = await this._browseMediaManager.walk<BrowseMediaMetadata>(
|
||||
hass,
|
||||
generateStep([start]),
|
||||
{
|
||||
@@ -148,33 +188,4 @@ export class HAFoldersEngine implements FoldersEngine {
|
||||
folder: query.folder,
|
||||
});
|
||||
}
|
||||
|
||||
private getDefaultFolderPathComponents(
|
||||
haFolderConfig?: HAFolderConfig,
|
||||
): NonEmptyTuple<FolderPathComponent> {
|
||||
const shouldAddDefaultRoot = !haFolderConfig?.url && !haFolderConfig?.path?.[0]?.id;
|
||||
|
||||
const defaultPath = [
|
||||
...(shouldAddDefaultRoot ? [{ id: HA_MEDIA_SOURCE_ROOT }] : []),
|
||||
...(haFolderConfig?.url ?? []),
|
||||
...(haFolderConfig?.path ?? []),
|
||||
];
|
||||
|
||||
return defaultPath.map((component) =>
|
||||
this._convertHAPathComponentToFolderPathComponent(component),
|
||||
) as [FolderPathComponent, ...FolderPathComponent[]];
|
||||
}
|
||||
|
||||
// Convert from the HA folder path component config schema to the general,
|
||||
// which pulls `path` to the top level.
|
||||
private _convertHAPathComponentToFolderPathComponent(
|
||||
component: HAFolderPathComponent,
|
||||
): FolderPathComponent {
|
||||
return {
|
||||
id: component.id,
|
||||
ha: {
|
||||
...component,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { Matcher } from '../../../config/schema/folders';
|
||||
import { BrowseMedia } from '../../../ha/browse-media/types';
|
||||
import { regexpExtract } from '../../../utils/regexp-extract';
|
||||
import { REGEXP_GROUP_VALUE_KEY } from './types';
|
||||
|
||||
export class MediaMatcher {
|
||||
public match(media: BrowseMedia, matchers?: Matcher[], foldersOnly = false): boolean {
|
||||
if (foldersOnly && !media.can_expand) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const matcher of matchers ?? []) {
|
||||
if (matcher.type === 'title') {
|
||||
if (!this._matchTitle(matcher, media.title)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private _matchTitle(matcher: Matcher, src: string): boolean {
|
||||
const valueToMatch = matcher.regexp
|
||||
? regexpExtract(matcher.regexp, src, { groupName: REGEXP_GROUP_VALUE_KEY })
|
||||
: src;
|
||||
|
||||
if (!valueToMatch) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (matcher.title) {
|
||||
return valueToMatch === matcher.title;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { parse } from 'date-fns';
|
||||
import { Parser } from '../../../config/schema/folders';
|
||||
import {
|
||||
BrowseMedia,
|
||||
BrowseMediaMetadata,
|
||||
RichBrowseMedia,
|
||||
} from '../../../ha/browse-media/types';
|
||||
|
||||
import parser from 'any-date-parser';
|
||||
import { isValidDate } from '../../../utils/basic';
|
||||
import { regexpExtract } from '../../../utils/regexp-extract';
|
||||
import { REGEXP_GROUP_VALUE_KEY } from './types';
|
||||
|
||||
export class MetadataGenerator {
|
||||
protected _anyDateParser: typeof parser | null = null;
|
||||
|
||||
public async prepare(parsers?: Parser[]): Promise<void> {
|
||||
if (this._anyDateParser) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Dynamically import the any-date-parser only if we have a parser that
|
||||
// requires it, in order to save on bundle size.
|
||||
if (
|
||||
parsers?.some(
|
||||
(parser) => ['date', 'startdate'].includes(parser.type) && !parser.format,
|
||||
)
|
||||
) {
|
||||
this._anyDateParser = (await import('any-date-parser')).default;
|
||||
}
|
||||
}
|
||||
|
||||
public generate(
|
||||
media: BrowseMedia,
|
||||
parent?: RichBrowseMedia<BrowseMediaMetadata>,
|
||||
parsers?: Parser[],
|
||||
): BrowseMediaMetadata | null {
|
||||
// Always propagate metadata from parent to children.
|
||||
const metadata: BrowseMediaMetadata = {
|
||||
...parent?._metadata,
|
||||
};
|
||||
|
||||
for (const parser of parsers ?? []) {
|
||||
const valueToParse = parser.regexp
|
||||
? regexpExtract(parser.regexp, media.title, {
|
||||
groupName: REGEXP_GROUP_VALUE_KEY,
|
||||
})
|
||||
: media.title;
|
||||
if (!valueToParse) {
|
||||
continue;
|
||||
}
|
||||
if (parser.type === 'startdate' || parser.type === 'date') {
|
||||
metadata.startDate =
|
||||
this._parseDate(parser, valueToParse, parent?._metadata?.startDate) ??
|
||||
undefined;
|
||||
}
|
||||
}
|
||||
|
||||
return Object.keys(metadata).length > 0 ? metadata : null;
|
||||
}
|
||||
|
||||
private _parseDate(parser: Parser, src: string, base?: Date): Date | undefined {
|
||||
if (parser.format) {
|
||||
return this._parseFormattedDate(parser.format, src, base);
|
||||
}
|
||||
return this._parseUnknownDate(src, base);
|
||||
}
|
||||
|
||||
private _parseFormattedDate(
|
||||
format: string,
|
||||
src: string,
|
||||
base?: Date,
|
||||
): Date | undefined {
|
||||
const result = parse(src, format, base ?? new Date());
|
||||
return isValidDate(result) ? result : undefined;
|
||||
}
|
||||
|
||||
private _parseUnknownDate(src: string, base?: Date): Date | undefined {
|
||||
if (!this._anyDateParser) {
|
||||
return undefined;
|
||||
}
|
||||
const result = this._anyDateParser.attempt(src);
|
||||
if (!Object.keys(result).length) {
|
||||
return undefined;
|
||||
}
|
||||
return this._anyDateParser.fromObject({
|
||||
...(base && {
|
||||
year: base.getFullYear(),
|
||||
month: base.getMonth() + 1,
|
||||
day: base.getDate(),
|
||||
hour: base.getHours(),
|
||||
minute: base.getMinutes(),
|
||||
second: base.getSeconds(),
|
||||
millisecond: base.getMilliseconds(),
|
||||
}),
|
||||
...result,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export const REGEXP_GROUP_VALUE_KEY = 'value';
|
||||
@@ -4,7 +4,7 @@ import { ResolvedMediaCache } from '../../ha/resolved-media';
|
||||
import { HomeAssistant } from '../../ha/types';
|
||||
import { Endpoint } from '../../types';
|
||||
import { AdvancedCameraCardError } from '../../types.js';
|
||||
import { ViewItem } from '../../view/item';
|
||||
import { ViewFolder, ViewItem } from '../../view/item';
|
||||
import { ViewItemCapabilities } from '../../view/types';
|
||||
|
||||
// ====
|
||||
@@ -22,8 +22,8 @@ export class FolderInitializationError extends AdvancedCameraCardError {}
|
||||
// ============
|
||||
|
||||
export type FolderPathComponent = {
|
||||
id?: string;
|
||||
ha?: Omit<HAFolderPathComponent, 'id'>;
|
||||
folder?: ViewFolder;
|
||||
ha?: HAFolderPathComponent;
|
||||
};
|
||||
|
||||
export interface FolderQuery {
|
||||
|
||||
Reference in New Issue
Block a user