Add source code

Signed-off-by: Nikolaos Karaolidis <nick@karaolidis.com>
This commit is contained in:
2025-02-23 13:24:50 +00:00
parent 2c3307f0d5
commit 4c36307b01
13 changed files with 2546 additions and 91 deletions

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
node_modules/
build/

View File

@@ -1,93 +1,3 @@
# darktable-ghost-cms-publish
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://git.karaolidis.com/karaolidis/darktable-ghost-cms-publish.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://git.karaolidis.com/karaolidis/darktable-ghost-cms-publish/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
A small utility to help publish images from [Darktable](https://www.darktable.org/) directly to [Ghost CMS](https://ghost.org/).

BIN
bun.lockb Normal file

Binary file not shown.

11
eslint.config.js Normal file
View File

@@ -0,0 +1,11 @@
import globals from "globals";
import pluginJs from "@eslint/js";
import tseslint from "typescript-eslint";
/** @type {import('eslint').Linter.Config[]} */
export default [
{ files: ["**/*.{js,mjs,cjs,ts}"] },
{ languageOptions: { globals: globals.browser } },
pluginJs.configs.recommended,
...tseslint.configs.recommended,
];

1962
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

24
package.json Normal file
View File

@@ -0,0 +1,24 @@
{
"name": "darktable-ghost-cms-publish",
"module": "src/index.ts",
"type": "module",
"devDependencies": {
"@eslint/js": "^9.17.0",
"@types/bun": "latest",
"@types/jsonwebtoken": "^9.0.7",
"eslint": "^9.17.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.2.1",
"globals": "^15.14.0",
"prettier": "^3.4.2",
"typescript-eslint": "^8.18.1"
},
"peerDependencies": {
"typescript": "^5.0.0"
},
"dependencies": {
"commander": "^12.1.0",
"exiftool-vendored": "^29.0.0",
"jsonwebtoken": "^9.0.2"
}
}

133
publish.lua Normal file
View File

@@ -0,0 +1,133 @@
local dt = require "darktable"
local df = require "lib/dtutils.file"
local os = require "os"
-- Some fucking bullshit happening right here.
function os.capture(command, raw)
local f = assert(io.popen(command, 'r'))
local s = assert(f:read('*a'))
f:close()
if raw then return s end
s = string.gsub(s, '^%s+', '')
s = string.gsub(s, '%s+$', '')
s = string.gsub(s, '[\n\r]+', ' ')
return s
end
local publish_title = dt.new_widget("entry") {
placeholder = "Post Title",
tooltip = "enter title for the post"
}
local publish_slug = dt.new_widget("entry") {
placeholder = "post-slug",
tooltip = "enter slug for the post (URL-friendly)"
}
local publish_keywords = dt.new_widget("entry") {
placeholder = "keywords (space-separated)",
tooltip = "enter keywords (tags) for the post"
}
local strip_gps_checkbox = dt.new_widget("check_button") {
label = "Strip GPS data",
value = false,
tooltip = "remove GPS metadata from files before uploading"
}
local widget = dt.new_widget("box") {
orientation = "vertical",
publish_title,
publish_slug,
publish_keywords,
strip_gps_checkbox
}
local function initialize(_, _, images, _, extra_data)
extra_data.exported_files = {}
extra_data.cleanup_files = {}
if publish_title.text == "" then
extra_data.title = df.get_basename(images[1].filename)
else
extra_data.title = publish_title.text
end
if publish_slug.text == "" then
extra_data.slug = df.get_basename(images[1].filename)
else
extra_data.slug = publish_slug.text
end
extra_data.keywords = publish_keywords.text
extra_data.strip_gps = strip_gps_checkbox.value
return images
end
local function store(_, image, _, filename, _, _, _, extra_data)
if extra_data.strip_gps then
local command = string.format("exiftool -gps:all= -overwrite_original '%s'", filename)
os.execute(command)
end
if image.is_raw then
local original_path = image.path .. "/" .. image.filename
local raw_filename = original_path
if extra_data.strip_gps then
local tmpfile = os.tmpname()
local command = string.format("exiftool -gps:all= -o '%s' '%s'", tmpfile, original_path)
os.execute(command)
table.insert(extra_data.cleanup_files, tmpfile)
raw_filename = tmpfile
end
table.insert(extra_data.exported_files, filename .. ":" .. raw_filename)
else
table.insert(extra_data.exported_files, filename)
end
end
local function finalize(_, _, extra_data)
local files_arg = table.concat(extra_data.exported_files, " ")
local command = string.format(
"darktable-publish --title '%s' --slug '%s' %s",
extra_data.title, extra_data.slug, files_arg
)
if extra_data.keywords ~= "" then
command = command .. string.format(" --keywords %s", extra_data.keywords)
end
-- Ignore that I use an external tool (written in JavaScript god forbid)
-- I am _not_ doing JSON generation and web requests in Lua
local result = os.capture(command)
if result and result:match("^http") then
dt.print("Post published: " .. result)
else
dt.print("Failed to publish post.")
end
local command = string.format("xdg-open %s", result)
os.execute(command)
for _, tmpfile in ipairs(extra_data.cleanup_files) do
os.remove(tmpfile)
end
end
local function supported(_, _)
return true
end
dt.register_storage(
"ghost_publish",
"publish to Ghost CMS",
store,
finalize,
supported,
initialize,
widget
)

110
src/api.ts Normal file
View File

@@ -0,0 +1,110 @@
import { sign } from "jsonwebtoken";
import { file } from "bun";
const getAdminApiKey = async () => {
const keyPath = process.env.GHOST_ADMIN_API_KEY_PATH;
if (!keyPath) {
throw new Error(
"Environment variable GHOST_ADMIN_API_KEY_PATH is not set.",
);
}
const keyFile = file(keyPath);
if (!(await keyFile.exists())) {
throw new Error(`Key file not found at path: ${keyPath}`);
}
return await keyFile.text();
};
const getEndpoint = () => {
const endpoint = process.env.GHOST_URL;
if (!endpoint) {
throw new Error("Environment variable GHOST_URL is not set.");
}
return endpoint;
};
const createJwt = (key: string) => {
const [id, secret] = key.split(":");
if (!id || !secret) {
throw new Error("Invalid API key format. Expected format: {id}:{secret}");
}
return sign({}, Buffer.from(secret, "hex"), {
keyid: id,
algorithm: "HS256",
expiresIn: "5m",
audience: `/admin/`,
});
};
const upload = async (
slug: string,
path: string,
type: string | undefined,
): Promise<any> => {
const endpoint = getEndpoint();
const fullEndpoint = `${endpoint}${slug}`;
const key = await getAdminApiKey();
const token = createJwt(key);
const f = Bun.file(path, { type });
const formData = new FormData();
formData.append("file", f);
const response = await fetch(fullEndpoint, {
method: "POST",
headers: {
Authorization: `Ghost ${token}`,
},
body: formData,
});
if (!response.ok) {
throw new Error(
`Failed to upload to ${fullEndpoint}: ${response.status} ${response.statusText}`,
);
}
return await response.json();
};
export const uploadImage = async (imagePath: string): Promise<string> => {
const slug = `/ghost/api/admin/images/upload`;
return (await upload(slug, imagePath, "image/jpeg")).images[0].url;
};
export const uploadFile = async (filePath: string): Promise<string> => {
const slug = `/ghost/api/admin/files/upload`;
return (await upload(slug, filePath, undefined)).files[0].url;
};
export const uploadPost = async (post: any): Promise<string> => {
const endpoint = getEndpoint();
const fullEndpoint = `${endpoint}/ghost/api/admin/posts`;
const key = await getAdminApiKey();
const token = createJwt(key);
const response = await fetch(fullEndpoint, {
method: "POST",
headers: {
Authorization: `Ghost ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
posts: [post],
}),
});
if (!response.ok) {
throw new Error(
`Failed to upload to ${fullEndpoint}: ${response.status} ${response.statusText}`,
);
}
return (await response.json()).posts[0].url;
};

48
src/exif.ts Normal file
View File

@@ -0,0 +1,48 @@
import { exiftool } from "exiftool-vendored";
import type { FileInfo } from "./files";
export interface ShootingConditions {
make: string;
model: string;
lensMake: string;
lensModel: string;
focalLength: string;
focalLength35: string;
shutterSpeed: string;
fStop: string;
iso: string;
timestamp: string;
}
export const extractShootingConditions = async (
fileInfo: FileInfo,
): Promise<ShootingConditions> => {
const path = fileInfo.rawPath ?? fileInfo.jpegPath;
try {
const exifData = await exiftool.read(path);
return {
make: exifData.Make ?? "Unknown",
model: exifData.Model ?? "Unknown",
lensMake: exifData.LensMake ?? "Unknown",
lensModel: exifData.LensModel ?? "Unknown",
focalLength: exifData.FocalLength ?? "Unknown",
focalLength35: exifData.FocalLengthIn35mmFormat ?? "Unknown",
shutterSpeed: exifData.ExposureTime ?? "Unknown",
fStop: exifData.FNumber?.toString() ?? "Unknown",
iso: exifData.ISO?.toString() ?? "Unknown",
timestamp: new Date(
(exifData.CreateDate?.toString() as string).replace(/\./g, ":"),
).toISOString(),
};
} catch (error: any) {
throw new Error(
`Failed to extract EXIF data from ${path}: ${error.message}`,
);
}
};
export const createImageCaption = (exif: ShootingConditions) => {
return `${exif.make} ${exif.model}, ${exif.lensMake} ${exif.lensModel} @ ${exif.focalLength} (${exif.focalLength35}), ${exif.shutterSpeed} s, f/${exif.fStop}, ISO ${exif.iso}`;
};

66
src/files.ts Normal file
View File

@@ -0,0 +1,66 @@
import { basename, extname } from "path";
export interface FileInfo {
jpegPath: string;
jpegSize: number;
rawPath?: string;
rawSize?: number;
}
export const getBasenameWithoutExtension = (path: string): string => {
const base = basename(path);
const extension = extname(path);
return base.slice(0, -extension.length);
};
export const getBasenameWithExtension = (path: string): string => {
return basename(path);
};
export const prepareFiles = async (files: string[]): Promise<FileInfo[]> => {
if (files.length > 10) {
throw new Error("Up to 10 files are allowed at a time.");
}
const parsedFiles: FileInfo[] = [];
for (const pair of files) {
const parts = pair.split(/(?<!\\):/);
const jpegPath = parts[0].replace(/\\:/g, ":");
const rawPath = parts[1]?.replace(/\\:/g, ":");
const jpegFile = Bun.file(jpegPath);
if (!(await jpegFile.exists())) {
throw new Error(`JPEG file not found: ${jpegPath}`);
}
const jpegSize = jpegFile.size;
if (!rawPath) {
parsedFiles.push({
jpegPath,
jpegSize,
rawPath: undefined,
rawSize: undefined,
});
continue;
}
const rawFile = Bun.file(rawPath);
if (!(await rawFile.exists())) {
throw new Error(`RAW file not found: ${rawPath}`);
}
const rawSize = rawFile.size;
parsedFiles.push({
jpegPath,
jpegSize,
rawPath: rawPath,
rawSize: rawSize,
});
}
return parsedFiles;
};

112
src/index.ts Normal file
View File

@@ -0,0 +1,112 @@
import { Command } from "commander";
import { createFileNode, createImageNode, createHeadingNode } from "./lexical";
import { extractShootingConditions, createImageCaption } from "./exif";
import { uploadFile, uploadImage, uploadPost } from "./api";
import { getBasenameWithExtension, prepareFiles } from "./files";
new Command()
.name("darktable-publish")
.description("Publish files to GHOST CMS with optional metadata.")
.option("-t, --title [string]", "Specify the title")
.option("-s, --slug [string]", "Specify the slug")
.option("-k, --keywords [string...]", "Specify blog post keywords (tags)")
.argument("<files...>", "Files to process")
.action(async (files, options) => {
if (!options.title) {
throw new Error("Please specify a title.");
}
if (!options.slug) {
throw new Error("Please specify a slug.");
}
const parsedFiles = await prepareFiles(files);
const [
shootingConditions,
uploadedJpegImages,
uploadedJpegFiles,
uploadedRawFiles,
] = await Promise.all([
Promise.all(parsedFiles.map(extractShootingConditions)),
Promise.all(parsedFiles.map((f) => uploadImage(f.jpegPath))),
Promise.all(parsedFiles.map((f) => uploadFile(f.jpegPath))),
Promise.all(
parsedFiles.map((f) =>
f.rawPath ? uploadFile(f.rawPath) : Promise.resolve(undefined),
),
),
]);
const aggregatedFiles = parsedFiles.map((file, index) => ({
...file,
shootingConditions: shootingConditions[index],
uploadedJpegImage: uploadedJpegImages[index],
uploadedJpegFile: uploadedJpegFiles[index],
uploadedRawFile: uploadedRawFiles[index],
}));
const result: any = {
root: {
children: [],
direction: "ltr",
format: "",
indent: 0,
type: "root",
version: 1,
},
};
if (aggregatedFiles.length > 1) {
aggregatedFiles.slice(1).forEach((file) =>
result.root.children.push(
createImageNode({
src: file.uploadedJpegImage,
caption: createImageCaption(file.shootingConditions),
}),
),
);
}
result.root.children.push(createHeadingNode("Downloads", "h2"));
aggregatedFiles.forEach((file) => {
result.root.children.push(
createFileNode({
src: file.uploadedJpegFile,
name: getBasenameWithExtension(file.jpegPath),
size: file.jpegSize,
}),
);
if (file.uploadedRawFile && file.rawPath && file.rawSize) {
result.root.children.push(
createFileNode({
src: file.uploadedRawFile,
name: getBasenameWithExtension(file.rawPath),
size: file.rawSize,
}),
);
}
});
const post = {
title: options.title,
slug: options.slug,
lexical: JSON.stringify(result),
feature_image: aggregatedFiles[0].uploadedJpegImage,
feature_image_caption: createImageCaption(
aggregatedFiles[0].shootingConditions,
),
status: "published",
visibility: "public",
tags: options.keywords,
published_at: aggregatedFiles[0].shootingConditions.timestamp,
};
const url = await uploadPost(post);
console.log(url);
process.exit(0);
})
.parse();

50
src/lexical.ts Normal file
View File

@@ -0,0 +1,50 @@
export const createTextNode = (text: string) => ({
detail: 0,
format: 0,
mode: "normal",
style: "",
text,
type: "extended-text",
version: 1,
});
export const createHeadingNode = (text: string, level: string) => ({
children: [createTextNode(text)],
direction: "ltr",
format: "",
indent: 0,
type: "extended-heading",
version: 1,
tag: level,
});
export interface ImageInput {
src: string;
caption: string;
}
export const createImageNode = (image: ImageInput) => {
return {
type: "image",
version: 1,
cardWidth: "wide",
...image,
};
};
export interface FileInput {
src: string;
name: string;
size: number;
}
export const createFileNode = (file: FileInput) => {
return {
type: "file",
src: file.src,
fileTitle: file.name,
fileName: file.name,
fileCaption: "",
fileSize: file.size,
};
};

27
tsconfig.json Normal file
View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
// Enable latest features
"lib": [
"ESNext",
"DOM"
],
"target": "ESNext",
"module": "ESNext",
"moduleDetection": "force",
"jsx": "react-jsx",
"allowJs": true,
// Bundler mode
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,
// Best practices
"strict": true,
"skipLibCheck": true,
"noFallthroughCasesInSwitch": true,
// Some stricter flags (disabled by default)
"noUnusedLocals": false,
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false
}
}