├── .gitattributes ├── .github └── workflows │ ├── commit.yml │ ├── pr.yml │ └── release.yml ├── .gitignore ├── .vscode ├── extensions.json └── settings.json ├── LICENSE ├── README.md ├── blurhasher ├── eslint.config.js ├── package-lock.json ├── package.json ├── src │ ├── blurhash.ts │ ├── fields.ts │ ├── index.ts │ ├── migration.ts │ ├── regenerate.ts │ └── util.ts └── tsconfig.json ├── docker-compose.yml └── docs └── screenshot.png /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=lf 3 | *.js linguist-detect=false 4 | -------------------------------------------------------------------------------- /.github/workflows/commit.yml: -------------------------------------------------------------------------------- 1 | name: Code Check on Push 2 | 3 | on: 4 | push: 5 | branches-ignore: 6 | - main 7 | 8 | jobs: 9 | lint-and-build: 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v4 14 | 15 | - name: Setup Node.js 16 | uses: actions/setup-node@v4 17 | with: 18 | node-version: "20" 19 | 20 | - name: Install dependencies 21 | run: npm install 22 | working-directory: ./blurhasher 23 | 24 | - name: Run linter 25 | run: npm run lint 26 | working-directory: ./blurhasher 27 | 28 | - name: Build 29 | run: npm run build 30 | working-directory: ./blurhasher 31 | -------------------------------------------------------------------------------- /.github/workflows/pr.yml: -------------------------------------------------------------------------------- 1 | name: Pull Request Check 2 | 3 | on: 4 | pull_request: 5 | branches: [main] 6 | 7 | jobs: 8 | lint-and-build: 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - uses: actions/checkout@v4 13 | 14 | - name: Setup Node.js 15 | uses: actions/setup-node@v4 16 | with: 17 | node-version: "20" 18 | 19 | - name: Install dependencies 20 | run: npm install 21 | working-directory: ./blurhasher 22 | 23 | - name: Run linter 24 | run: npm run lint 25 | working-directory: ./blurhasher 26 | 27 | - name: Build 28 | run: npm run build 29 | working-directory: ./blurhasher 30 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release CI/CD 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | 7 | jobs: 8 | lint: 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - uses: actions/checkout@v4 13 | 14 | - name: Setup Node.js 15 | uses: actions/setup-node@v4 16 | with: 17 | node-version: "20" 18 | 19 | - name: Install dependencies 20 | run: npm install 21 | working-directory: ./blurhasher 22 | 23 | - name: Run linter 24 | run: npm run lint 25 | working-directory: ./blurhasher 26 | 27 | build: 28 | needs: lint 29 | runs-on: ubuntu-latest 30 | 31 | steps: 32 | - uses: actions/checkout@v4 33 | 34 | - name: Setup Node.js 35 | uses: actions/setup-node@v4 36 | with: 37 | node-version: "20" 38 | 39 | - name: Install dependencies 40 | run: npm install 41 | working-directory: ./blurhasher 42 | 43 | - name: Build 44 | run: npm run build 45 | working-directory: ./blurhasher 46 | 47 | - name: Archive built files 48 | run: tar -czvf build.tar.gz -C ./blurhasher dist package.json 49 | 50 | - name: Upload build artifact 51 | uses: actions/upload-artifact@v4 52 | with: 53 | name: built-files 54 | path: build.tar.gz 55 | 56 | semantic-release: 57 | needs: build 58 | runs-on: ubuntu-latest 59 | permissions: 60 | contents: write 61 | 62 | steps: 63 | - uses: actions/checkout@v4 64 | 65 | - name: Setup Node.js 66 | uses: actions/setup-node@v4 67 | with: 68 | node-version: "20" 69 | 70 | - name: Download build artifact 71 | uses: actions/download-artifact@v4 72 | with: 73 | name: built-files 74 | path: ./blurhasher 75 | 76 | - name: Copy README.md to blurhasher 77 | run: cp README.md blurhasher/README.md 78 | 79 | - name: Unpack build artifact 80 | run: tar -xzvf build.tar.gz 81 | working-directory: ./blurhasher 82 | 83 | - name: Semantic Release 84 | run: npx semantic-release 85 | working-directory: ./blurhasher 86 | env: 87 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 88 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 89 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | database/ 2 | uploads/ 3 | **/.DS_Store 4 | **/node_modules 5 | **/dist 6 | **/data.db 7 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": ["dbaeumer.vscode-eslint"] 3 | } 4 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnSave": true, 3 | "files.eol": "\n", 4 | "eslint.validate": [ 5 | "javascript", 6 | "typescript" 7 | ], 8 | "editor.codeActionsOnSave": { 9 | "source.fixAll.eslint": "always" 10 | }, 11 | "files.exclude": { 12 | "**/.git": true, 13 | "**/node_modules": true, 14 | "**/dist": true 15 | }, 16 | "search.exclude": { 17 | "**/node_modules": true, 18 | "**/dist": true 19 | }, 20 | "editor.rulers": [ 21 | 120 22 | ], 23 | "prettier.trailingComma": "all" 24 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2024 Anton Kovalev 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Directus Blurhasher 2 | 3 | This is an extension for [Directus](https://github.com/directus/directus) that automatically generates [blurhash](https://github.com/woltapp/blurhash/) strings for images upon their upload. 4 | 5 | Key features: 6 | - Generation and storage of blurhash strings for images upon their upload. 7 | - The ability to set the detail level for generating blurhash strings (Low, Medium, High). 8 | - Generation of blurhash strings for existing images. 9 | - Automatic migration upon extension installation. 10 | 11 | In the system collection of illustrations (`directus_files`), in addition to the main fields, a `blurhash` field is added, which will store the generated blurhash string. 12 | 13 | ![screen](./docs/screenshot.png) 14 | 15 | ## Settings 16 | The following settings are available in the Directus settings section: 17 | - **Generate on restart** - upon the next launch of Directus, blurhash strings will be generated for all existing images (this will be disabled after generation). 18 | - **Detail level** - the level of detail for generating blurhash strings (Low, Medium, High) 19 | 20 | The speed of blurhash generation directly depends on the level of detail. 21 | 22 | The level of detail affects the number of components used in generating the blurhash string. The higher the level of detail, the more components will be used, and the more detailed the blurhash string will be. 23 | 24 | - Low: 3x3 components 25 | - Medium: 6x6 components 26 | - High: 8x8 components 27 | 28 | ## Requirements 29 | 30 | This extension has been tested on Directus version v10.0.0, however, it should work on earlier versions as well. 31 | 32 | ## Installation 33 | 34 | ```bash 35 | npm install directus-extension-blurhasher 36 | ``` 37 | 38 | Example Dockerfile with the extension installed: 39 | 40 | ```Dockerfile 41 | FROM directus/directus:10.10.4 42 | 43 | USER root 44 | RUN corepack enable 45 | USER node 46 | 47 | RUN pnpm install directus-extension-blurhasher 48 | ``` 49 | 50 | ## Development 51 | Start the build process in development mode and a Docker image of Directus for testing. 52 | 53 | ```bash 54 | cd blurhasher 55 | npm install 56 | npm run dev 57 | ``` 58 | To launch Directus itself: 59 | 60 | ```bash 61 | docker compose up 62 | ``` 63 | 64 | - Login: admin@example.com 65 | - Password: admin -------------------------------------------------------------------------------- /blurhasher/eslint.config.js: -------------------------------------------------------------------------------- 1 | const typescriptEslint = require("@typescript-eslint/eslint-plugin"); 2 | const typescriptParser = require("@typescript-eslint/parser"); 3 | const prettierPlugin = require("eslint-plugin-prettier"); 4 | const prettierConfig = require("eslint-config-prettier"); 5 | 6 | module.exports = [ 7 | { 8 | languageOptions: { 9 | ecmaVersion: "latest", 10 | sourceType: "module", 11 | parser: typescriptParser, 12 | }, 13 | plugins: { 14 | "@typescript-eslint": typescriptEslint, 15 | prettier: prettierPlugin, 16 | }, 17 | rules: { 18 | "prettier/prettier": "warn", 19 | "@typescript-eslint/no-explicit-any": "off", 20 | }, 21 | settings: { 22 | "import/resolver": { 23 | node: { 24 | extensions: [".ts"], 25 | }, 26 | }, 27 | }, 28 | }, 29 | { 30 | ignores: ["dist/*"], 31 | }, 32 | { 33 | files: ["*.ts", "*.tsx"], 34 | languageOptions: { 35 | parserOptions: { 36 | project: "./tsconfig.json", 37 | }, 38 | }, 39 | }, 40 | { 41 | files: [".eslintrc.js", "eslint.config.js"], 42 | languageOptions: { 43 | sourceType: "script", 44 | }, 45 | }, 46 | ]; 47 | -------------------------------------------------------------------------------- /blurhasher/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "directus-extension-blurhasher", 3 | "description": "A Directus extension for generating and storing BlurHash strings, enhancing image loading visuals.", 4 | "icon": "extension", 5 | "version": "0.1.0", 6 | "author": "Anton Kovalev ", 7 | "license": "MIT", 8 | "keywords": [ 9 | "directus", 10 | "directus-extension", 11 | "directus-extension-hook", 12 | "blurhash", 13 | "image", 14 | "thumbnail", 15 | "placeholder" 16 | ], 17 | "files": [ 18 | "dist", 19 | "README.md" 20 | ], 21 | "release": { 22 | "branches": [ 23 | "main" 24 | ], 25 | "plugins": [ 26 | "@semantic-release/commit-analyzer", 27 | "@semantic-release/release-notes-generator", 28 | [ 29 | "@semantic-release/npm", 30 | { 31 | "npmPublish": true 32 | } 33 | ], 34 | [ 35 | "@semantic-release/github", 36 | { 37 | "assets": [ 38 | { 39 | "path": "build.tar.gz", 40 | "label": "Built Files" 41 | } 42 | ], 43 | "releasedLabels": "released" 44 | } 45 | ] 46 | ] 47 | }, 48 | "directus:extension": { 49 | "type": "hook", 50 | "path": "dist/index.js", 51 | "source": "src/index.ts", 52 | "host": ">=10.0.0", 53 | "icon": "Image", 54 | "description": "A Directus extension for generating and storing BlurHash strings, enhancing image loading visuals.", 55 | "author": "Anton Kovalev" 56 | }, 57 | "scripts": { 58 | "build": "directus-extension build", 59 | "dev": "directus-extension build -w --no-minify", 60 | "link": "directus-extension link", 61 | "lint": "eslint ." 62 | }, 63 | "devDependencies": { 64 | "@directus/extensions-sdk": "^12.1.1", 65 | "@directus/types": "^12.2.0", 66 | "@types/node": "^22.8.6", 67 | "@typescript-eslint/eslint-plugin": "^8.12.2", 68 | "@typescript-eslint/parser": "^8.12.2", 69 | "blurhash": "^2.0.5", 70 | "eslint": "^9.14.0", 71 | "eslint-config-prettier": "^9.1.0", 72 | "eslint-plugin-prettier": "^5.2.1", 73 | "pino": "^9.5.0", 74 | "prettier": "^3.3.3", 75 | "semantic-release": "^24.2.0", 76 | "sharp": "^0.33.5", 77 | "typescript": "^5.6.3" 78 | }, 79 | "repository": { 80 | "type": "git", 81 | "url": "git+https://github.com/antonko/directus-extension-blurhasher" 82 | } 83 | } -------------------------------------------------------------------------------- /blurhasher/src/blurhash.ts: -------------------------------------------------------------------------------- 1 | import { Readable } from "stream"; 2 | import { encode } from "blurhash"; 3 | import { Logger } from "pino"; 4 | // eslint-disable-next-line @typescript-eslint/no-var-requires 5 | const sharp = require("sharp"); // Ugly, but necessary because of dependencies Directus 6 | 7 | /** 8 | * Converts a readable stream to a buffer. 9 | * @param stream The readable stream to convert. 10 | * @returns A promise that resolves to a buffer containing the data from the stream. 11 | */ 12 | export const streamToBuffer = async (stream: Readable): Promise => { 13 | const chunks: Buffer[] = []; 14 | for await (const chunk of stream) { 15 | chunks.push(chunk as Buffer); 16 | } 17 | return Buffer.concat(chunks); 18 | }; 19 | 20 | /** 21 | * Generates a BlurHash string from a readable stream. 22 | * 23 | * @param stream - The readable stream to generate the BlurHash from. 24 | * @returns A Promise that resolves to the generated BlurHash string, or null if an error occurs. 25 | */ 26 | export const generateBlurHashFromStream = async ( 27 | stream: Readable, 28 | detail_level: string, 29 | logger: Logger, 30 | ): Promise => { 31 | try { 32 | const buffer = await streamToBuffer(stream); 33 | const { data, info } = await sharp(buffer) 34 | .ensureAlpha() 35 | .raw() 36 | .toBuffer({ resolveWithObject: true }); 37 | 38 | /** 39 | * Determine the x and y component counts based on the detail level 40 | */ 41 | let xComponent = 6; // Default value for medium detail 42 | let yComponent = 6; // Default value for medium detail 43 | 44 | switch (detail_level) { 45 | case "low": 46 | xComponent = 3; 47 | yComponent = 3; 48 | break; 49 | case "high": 50 | xComponent = 8; 51 | yComponent = 8; 52 | break; 53 | } 54 | 55 | const blurHash = encode( 56 | new Uint8ClampedArray(data), 57 | info.width, 58 | info.height, 59 | xComponent, 60 | yComponent, 61 | ); 62 | return blurHash; 63 | } catch (error) { 64 | logger.error(`Error generating BlurHash: ${error}`); 65 | return null; 66 | } 67 | }; 68 | -------------------------------------------------------------------------------- /blurhasher/src/fields.ts: -------------------------------------------------------------------------------- 1 | import type { FieldRaw } from "@directus/types"; 2 | export const directus_files_blurhash: FieldRaw = { 3 | collection: "directus_files", 4 | field: "blurhash", 5 | type: "string", 6 | meta: { 7 | collection: "directus_files", 8 | field: "blurhash", 9 | special: null, 10 | interface: "input", 11 | options: null, 12 | display: null, 13 | display_options: null, 14 | readonly: false, 15 | hidden: false, 16 | sort: 1, 17 | width: "full", 18 | translations: null, 19 | note: "Automatically generated by the extension blurhasher", 20 | conditions: null, 21 | required: false, 22 | group: null, 23 | validation: null, 24 | validation_message: null, 25 | }, 26 | schema: { 27 | name: "blurhash", 28 | table: "directus_files", 29 | data_type: "varchar", 30 | default_value: null, 31 | max_length: 255, 32 | numeric_precision: null, 33 | numeric_scale: null, 34 | is_generated: false, 35 | generation_expression: null, 36 | is_nullable: true, 37 | is_unique: false, 38 | is_primary_key: false, 39 | has_auto_increment: false, 40 | foreign_key_column: null, 41 | foreign_key_table: null, 42 | }, 43 | }; 44 | 45 | export const settings_detail_level: FieldRaw = { 46 | collection: "directus_settings", 47 | field: "blurhasher_detail_level", 48 | type: "string", 49 | meta: { 50 | collection: "directus_settings", 51 | field: "blurhasher_detail_level", 52 | special: null, 53 | interface: "select-dropdown", 54 | options: { 55 | choices: [ 56 | { text: "High", value: "high" }, 57 | { text: "Medium", value: "medium" }, 58 | { text: "Low", value: "low" }, 59 | ], 60 | }, 61 | display: null, 62 | display_options: null, 63 | readonly: false, 64 | hidden: false, 65 | sort: 1, 66 | width: "full", 67 | translations: null, 68 | note: "This parameter determines the detail level in the BlurHash, affecting its complexity and length from high (detailed) to low (abstract).", 69 | conditions: null, 70 | required: false, 71 | group: null, 72 | validation: null, 73 | validation_message: null, 74 | }, 75 | schema: { 76 | name: "blurhasher_detail_level", 77 | table: "directus_settings", 78 | data_type: "varchar", 79 | default_value: "medium", 80 | max_length: 255, 81 | numeric_precision: null, 82 | numeric_scale: null, 83 | is_generated: false, 84 | generation_expression: null, 85 | is_nullable: true, 86 | is_unique: false, 87 | is_primary_key: false, 88 | has_auto_increment: false, 89 | foreign_key_column: null, 90 | foreign_key_table: null, 91 | }, 92 | }; 93 | 94 | export const settings_regenerate: FieldRaw = { 95 | collection: "directus_settings", 96 | field: "blurhasher_regenerate_on_restart", 97 | type: "boolean", 98 | meta: { 99 | collection: "directus_settings", 100 | field: "blurhasher_regenerate_on_restart", 101 | special: ["cast-boolean"], 102 | interface: "boolean", 103 | options: null, 104 | display: null, 105 | display_options: null, 106 | readonly: false, 107 | hidden: false, 108 | sort: 2, 109 | width: "full", 110 | translations: null, 111 | note: "Enables regeneration of all BlurHashes for illustrations upon system restart.", 112 | conditions: null, 113 | required: false, 114 | group: null, 115 | validation: null, 116 | validation_message: null, 117 | }, 118 | schema: { 119 | name: "blurhasher_regenerate_on_restart", 120 | table: "directus_settings", 121 | data_type: "boolean", 122 | default_value: false, 123 | max_length: null, 124 | numeric_precision: null, 125 | numeric_scale: null, 126 | is_generated: false, 127 | generation_expression: null, 128 | is_nullable: true, 129 | is_unique: false, 130 | is_primary_key: false, 131 | has_auto_increment: false, 132 | foreign_key_column: null, 133 | foreign_key_table: null, 134 | }, 135 | }; 136 | -------------------------------------------------------------------------------- /blurhasher/src/index.ts: -------------------------------------------------------------------------------- 1 | import { defineHook } from "@directus/extensions-sdk"; 2 | import { runMigration } from "./migration"; 3 | import { generateBlurHashFromStream } from "./blurhash"; 4 | import { getSetting } from "./util"; 5 | import { settings_detail_level, settings_regenerate } from "./fields"; 6 | import { regenerate_all_images } from "./regenerate"; 7 | 8 | export default defineHook( 9 | ({ action, init }, { services, database, getSchema, logger }) => { 10 | const { AssetsService, ItemsService, FieldsService, SettingsService } = 11 | services; 12 | 13 | /** 14 | * Extension initialization hook. 15 | * This hook is called when the extension is loaded. 16 | **/ 17 | init("routes.custom.after", async () => { 18 | logger.info(`[blurhasher]: Initializing extension`); 19 | const schema = await getSchema(); 20 | const fieldsService = new FieldsService({ knex: database, schema }); 21 | /** 22 | * Migration 23 | */ 24 | await runMigration(fieldsService, logger); 25 | 26 | const settings = new SettingsService({ schema, knex: database }); 27 | const detail_level = await getSetting( 28 | settings, 29 | settings_detail_level.field, 30 | ); 31 | const is_regenerate = await getSetting( 32 | settings, 33 | settings_regenerate.field, 34 | ); 35 | if (!is_regenerate) { 36 | return; 37 | } 38 | /** 39 | * Regenerate all blurhashes if the setting is enabled. 40 | */ 41 | try { 42 | logger.warn("[blurhasher]: Regenerating blurhashes"); 43 | 44 | const itemsService = new ItemsService("directus_files", { 45 | knex: database, 46 | schema: schema, 47 | }); 48 | const assetsService = new AssetsService({ 49 | knex: database, 50 | schema: schema, 51 | }); 52 | await regenerate_all_images( 53 | itemsService, 54 | assetsService, 55 | detail_level, 56 | logger, 57 | ); 58 | logger.warn("[blurhasher]: Regeneration complete"); 59 | } catch (error) { 60 | logger.error( 61 | `[blurhasher]: An error occurred while regenerating blurhashes: ${error}`, 62 | ); 63 | } finally { 64 | settings.upsertSingleton({ blurhasher_regenerate_on_restart: false }); 65 | } 66 | }); 67 | 68 | /** 69 | * Action hook for the `files.upload` action. 70 | * This hook is called when a file is uploaded to Directus. 71 | */ 72 | action("files.upload", async ({ payload, key }, context) => { 73 | if ( 74 | !["image/jpeg", "image/png", "image/webp", "image/tiff"].includes( 75 | payload.type, 76 | ) 77 | ) { 78 | // Skip non-image files 79 | return; 80 | } 81 | 82 | const assetsService = new AssetsService({ 83 | ...context, 84 | knex: context.database, 85 | }); 86 | 87 | const itemsService = new ItemsService("directus_files", { 88 | knex: database, 89 | schema: context.schema, 90 | }); 91 | 92 | const { stream } = await assetsService.getAsset(key, { 93 | transformationParams: { 94 | quality: 80, 95 | width: 100, 96 | fit: "inside", 97 | }, 98 | }); 99 | 100 | const settings = new SettingsService({ 101 | schema: context.schema, 102 | knex: database, 103 | }); 104 | const detail_level = await getSetting( 105 | settings, 106 | settings_detail_level.field, 107 | ); 108 | 109 | /** 110 | * Generate the blurhash from the stream and update the item. 111 | */ 112 | const blurHash: string | null = await generateBlurHashFromStream( 113 | stream, 114 | detail_level, 115 | logger, 116 | ); 117 | itemsService.updateOne(key, { blurhash: blurHash }); 118 | }); 119 | }, 120 | ); 121 | -------------------------------------------------------------------------------- /blurhasher/src/migration.ts: -------------------------------------------------------------------------------- 1 | import { Logger } from "pino"; 2 | import type { FieldRaw } from "@directus/types"; 3 | import { 4 | directus_files_blurhash, 5 | settings_detail_level, 6 | settings_regenerate, 7 | } from "./fields"; 8 | 9 | /** 10 | * Runs the migration process. 11 | * 12 | * @param fieldsService - The service for managing fields. 13 | * @param logger - The logger for logging messages. 14 | */ 15 | export async function runMigration(fieldsService: any, logger: Logger) { 16 | await ensureField(fieldsService, directus_files_blurhash, logger); 17 | await ensureField(fieldsService, settings_detail_level, logger); 18 | await ensureField(fieldsService, settings_regenerate, logger); 19 | } 20 | 21 | /** 22 | * Ensures the existence of a field in Directus. 23 | * If the field does not exist, it creates the field using the provided field configuration. 24 | * 25 | * @param fieldsService - The Directus fields service. 26 | * @param field - The field configuration to ensure. 27 | * @param logger - The logger instance for logging messages. 28 | */ 29 | export async function ensureField( 30 | fieldsService: any, 31 | field: FieldRaw, 32 | logger: Logger, 33 | ) { 34 | const found = await fieldsService 35 | .readOne(field.collection, field.field) 36 | .catch(() => false); 37 | if (!found) { 38 | logger.warn( 39 | `[blurhasher]: Creating field ${field.collection}.${field.field}`, 40 | ); 41 | await fieldsService.createField(field.collection, field); 42 | logger.warn( 43 | `[blurhasher]: Field ${field.collection}.${field.field} created`, 44 | ); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /blurhasher/src/regenerate.ts: -------------------------------------------------------------------------------- 1 | import { Logger } from "pino"; 2 | import { generateBlurHashFromStream } from "./blurhash"; 3 | 4 | /** 5 | * Regenerates BlurHash strings for all image assets in the system. 6 | * 7 | * @param itemsService - The service responsible for fetching and updating image metadata. 8 | * @param assetsService - The service used to retrieve image assets and their streams. 9 | * @param logger - Logger instance for logging progress and errors. 10 | */ 11 | export async function regenerate_all_images( 12 | itemsService: any, 13 | assetsService: any, 14 | detail_level: string, 15 | logger: Logger, 16 | ) { 17 | /** 18 | * Fetching a list of all image files that need their BlurHash regenerated. 19 | */ 20 | const files = await itemsService.readByQuery({ 21 | fields: ["id"], // Specifying that only the 'id' field is needed from each record. 22 | filter: { 23 | type: { 24 | _in: ["image/jpeg", "image/png", "image/webp", "image/tiff"], 25 | }, 26 | }, 27 | limit: -1, 28 | }); 29 | 30 | logger.info(`Total files to regenerate: ${files.length}`); 31 | 32 | for (const file of files) { 33 | /** 34 | * Retrieving the image stream for the current file with specified transformation parameters. 35 | */ 36 | try { 37 | const { stream } = await assetsService.getAsset(file["id"], { 38 | transformationParams: { 39 | quality: 80, 40 | width: 100, 41 | fit: "inside", 42 | }, 43 | }); 44 | 45 | /** 46 | * Generating a new BlurHash string from the image stream. 47 | */ 48 | const blurHash: string | null = await generateBlurHashFromStream( 49 | stream, 50 | detail_level, 51 | logger, 52 | ); 53 | await itemsService.updateOne(file["id"], { blurhash: blurHash }); 54 | logger.info(`Regenerating blurhash for file ${file["id"]}`); 55 | } catch (error) { 56 | logger.error( 57 | `Error regenerating blurhash for file ${file["id"]}: ${error}`, 58 | ); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /blurhasher/src/util.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Retrieves a setting value from a service. 3 | * @param service - The service to retrieve the setting from. 4 | * @param field - The name of the setting field. 5 | * @returns The value of the setting, or null if not found. 6 | */ 7 | export async function getSetting(service: any, field: string) { 8 | const found = await service 9 | .readSingleton({ fields: [field] }) 10 | .catch(() => false); 11 | 12 | return !found ? null : found[field]; 13 | } 14 | -------------------------------------------------------------------------------- /blurhasher/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2019", 4 | "lib": ["ES2019", "DOM"], 5 | "moduleResolution": "node", 6 | "strict": true, 7 | "noFallthroughCasesInSwitch": true, 8 | "esModuleInterop": true, 9 | "noImplicitAny": true, 10 | "noImplicitThis": true, 11 | "noImplicitReturns": true, 12 | "noUnusedLocals": true, 13 | "noUncheckedIndexedAccess": true, 14 | "noUnusedParameters": true, 15 | "alwaysStrict": true, 16 | "strictNullChecks": true, 17 | "strictFunctionTypes": true, 18 | "strictBindCallApply": true, 19 | "strictPropertyInitialization": true, 20 | "resolveJsonModule": false, 21 | "skipLibCheck": true, 22 | "forceConsistentCasingInFileNames": true, 23 | "allowSyntheticDefaultImports": true, 24 | "isolatedModules": true, 25 | "rootDir": "./src" 26 | }, 27 | "include": ["./src/**/*.ts"] 28 | } 29 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.7" 2 | services: 3 | directus: 4 | image: directus/directus:11 5 | ports: 6 | - 8055:8055 7 | volumes: 8 | - ./database:/directus/database 9 | - ./uploads:/directus/uploads 10 | - ./blurhasher:/directus/extensions/directus-extension-blurhasher 11 | - ./blurhasher:/directus/node_modules/directus-extension-blurhasher 12 | environment: 13 | KEY: "replace-with-random-value" 14 | SECRET: "replace-with-random-value" 15 | ADMIN_EMAIL: "admin@example.com" 16 | ADMIN_PASSWORD: "admin" 17 | DB_CLIENT: "sqlite3" 18 | DB_FILENAME: "/directus/database/data.db" 19 | -------------------------------------------------------------------------------- /docs/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antonko/directus-extension-blurhasher/357f9bdad2891dc13526f502865457cf4a324b8f/docs/screenshot.png --------------------------------------------------------------------------------