analogGallery/fetchImages.js

119 lines
4.2 KiB
JavaScript

import axios from 'axios';
import fs from 'fs';
import path from 'path';
import { pipeline } from 'stream/promises';
const config = {
apiKey: 'w7bVb1xk3mTQg4RuAHR0000lWnv0iaJD2Rq4M0Y1SLU',
albumId: 'f6303d3d-5343-4579-a92e-c1eb37518ae7',
baseUrl: 'https://photos.ghost.tel',
outputDir: './images' // Directory to store downloaded images
};
async function downloadImage(imageUrl, fileName, apiKey) {
const response = await axios({
method: 'GET',
url: imageUrl,
responseType: 'stream',
headers: {
'x-api-key': apiKey
}
});
const outputPath = path.join(config.outputDir, fileName);
await pipeline(response.data, fs.createWriteStream(outputPath));
return outputPath;
}
async function getAlbumAssets() {
try {
// Create output directory if it doesn't exist
if (!fs.existsSync(config.outputDir)) {
fs.mkdirSync(config.outputDir, { recursive: true });
}
// Load existing images.json if it exists
let existingImages = [];
const imagesJsonPath = './images.json';
if (fs.existsSync(imagesJsonPath)) {
existingImages = JSON.parse(fs.readFileSync(imagesJsonPath, 'utf8'));
}
const url = `${config.baseUrl}/api/albums/${config.albumId}`;
console.log('Fetching album data from:', url);
const response = await axios.get(url, {
headers: {
'Accept': 'application/json',
'x-api-key': config.apiKey
}
});
if (!response.data) {
throw new Error('No data received from the API');
}
console.log('First asset metadata sample:', JSON.stringify(response.data.assets[0], null, 2));
console.log(`Found ${response.data.assets.length} assets in album`);
const images = [];
for (const asset of response.data.assets) {
const originalUrl = `${config.baseUrl}/api/assets/${asset.id}/original`;
const fileName = `${asset.id}_${asset.originalFileName || 'untitled'}`;
const outputPath = path.join(config.outputDir, fileName);
// Check if file already exists and is in our metadata
const existingImage = existingImages.find(img => img.id === asset.id);
if (existingImage && fs.existsSync(existingImage.localPath)) {
console.log(`Skipping existing file: ${fileName}`);
images.push(existingImage);
continue;
}
console.log(`Downloading: ${fileName}`);
try {
const localPath = await downloadImage(originalUrl, fileName, config.apiKey);
images.push({
id: asset.id,
originalUrl,
localPath,
name: asset.originalFileName || 'Untitled',
thumbnailUrl: `${config.baseUrl}/api/asset/thumbnail/${asset.id}`,
description: asset.exifInfo?.description || '',
metadata: {
createdAt: asset.createdAt,
fileCreatedAt: asset.fileCreatedAt,
deviceAssetId: asset.deviceAssetId,
type: asset.type
}
});
console.log(`Successfully downloaded: ${fileName}`);
} catch (downloadError) {
console.error(`Failed to download ${fileName}:`, downloadError.message);
}
}
// Save the metadata
fs.writeFileSync('./images.json', JSON.stringify(images, null, 2));
console.log(`Successfully processed ${images.length} images`);
return images;
} catch (error) {
console.error('Error fetching album assets:', error.message);
if (error.response) {
console.error('Response status:', error.response.status);
console.error('Response data:', error.response.data);
}
throw error;
}
}
// Execute the function
getAlbumAssets().catch(error => {
console.error('Failed to fetch images:', error);
process.exit(1);
});