| 1 |
import { query } from '@agent/abilities/rest'; |
| 2 |
import apiFetch from '@wordpress/api-fetch'; |
| 3 |
import { decodeEntities } from '@wordpress/html-entities'; |
| 4 |
import { __ } from '@wordpress/i18n'; |
| 5 |
|
| 6 |
const fields = 'id,title,alt_text,mime_type,source_url,date,media_details'; |
| 7 |
|
| 8 |
export const media = { |
| 9 |
name: 'extendify/media', |
| 10 |
label: __('Media library', 'extendify-local'), |
| 11 |
description: |
| 12 |
'The images, video and files this site has uploaded. Returns each one’s id, name, description, kind, address and size — search by name, narrow to one kind of file, or ask for what a single post has attached.', |
| 13 |
inputSchema: { |
| 14 |
type: 'object', |
| 15 |
properties: { |
| 16 |
search: { |
| 17 |
type: 'string', |
| 18 |
description: 'Words to match against names and descriptions.', |
| 19 |
}, |
| 20 |
mimeType: { |
| 21 |
type: 'string', |
| 22 |
description: |
| 23 |
'One kind of file, such as image/jpeg, or a whole family, such as image.', |
| 24 |
}, |
| 25 |
postId: { |
| 26 |
type: 'integer', |
| 27 |
description: 'Only what is attached to this post.', |
| 28 |
}, |
| 29 |
limit: { |
| 30 |
type: 'integer', |
| 31 |
minimum: 1, |
| 32 |
maximum: 100, |
| 33 |
description: 'How many to return. Defaults to 10.', |
| 34 |
}, |
| 35 |
}, |
| 36 |
}, |
| 37 |
annotations: { readonly: true }, |
| 38 |
execute: async ({ search, mimeType, postId, limit = 10 } = {}) => { |
| 39 |
const response = await apiFetch({ |
| 40 |
path: `/wp/v2/media?${query({ |
| 41 |
search, |
| 42 |
mime_type: mimeType, |
| 43 |
parent: postId, |
| 44 |
per_page: limit, |
| 45 |
_fields: fields, |
| 46 |
})}`, |
| 47 |
parse: false, |
| 48 |
}); |
| 49 |
const files = await response.json(); |
| 50 |
|
| 51 |
return { |
| 52 |
total: Number(response.headers.get('X-WP-Total')), |
| 53 |
media: files.map((file) => ({ |
| 54 |
id: file.id, |
| 55 |
title: decodeEntities(file.title?.rendered ?? ''), |
| 56 |
alt: file.alt_text ?? '', |
| 57 |
mimeType: file.mime_type, |
| 58 |
url: file.source_url, |
| 59 |
date: file.date, |
| 60 |
...(file.media_details?.width && { |
| 61 |
width: file.media_details.width, |
| 62 |
height: file.media_details.height, |
| 63 |
}), |
| 64 |
})), |
| 65 |
}; |
| 66 |
}, |
| 67 |
}; |
| 68 |
|