import { promises as fs } from 'fs';
import path from 'path';
import os from 'os';
import { Config, StoredFeed } from '../types/index.js';
const DEFAULT_CONFIG: Config = {
feeds: [],
defaultLimit: 10,
timeout: 10000,
userAgent: 'RSS-Feed-MCP-Server/1.0.0'
};
export class ConfigManager {
private configPath: string;
private config: Config;
constructor(configPath?: string) {
this.configPath = configPath || path.join(os.homedir(), '.config', 'rss-feed-mcp', 'config.json');
this.config = { ...DEFAULT_CONFIG };
}
async load(): Promise<void> {
try {
const configDir = path.dirname(this.configPath);
await fs.mkdir(configDir, { recursive: true });
const data = await fs.readFile(this.configPath, 'utf-8');
this.config = { ...DEFAULT_CONFIG, ...JSON.parse(data) };
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
throw new Error(`設定ファイルの読み込みに失敗しました: ${error}`);
}
await this.save();
}
}
async save(): Promise<void> {
try {
const configDir = path.dirname(this.configPath);
await fs.mkdir(configDir, { recursive: true });
await fs.writeFile(this.configPath, JSON.stringify(this.config, null, 2));
} catch (error) {
throw new Error(`設定ファイルの保存に失敗しました: ${error}`);
}
}
getConfig(): Config {
return { ...this.config };
}
getFeeds(): StoredFeed[] {
return [...this.config.feeds];
}
getFeed(id: string): StoredFeed | undefined {
return this.config.feeds.find(feed => feed.id === id);
}
async addFeed(name: string, url: string): Promise<string> {
const id = this.generateFeedId();
const feed: StoredFeed = {
id,
name,
url,
addedDate: new Date().toISOString()
};
this.config.feeds.push(feed);
await this.save();
return id;
}
async removeFeed(id: string): Promise<boolean> {
const index = this.config.feeds.findIndex(feed => feed.id === id);
if (index === -1) {
return false;
}
this.config.feeds.splice(index, 1);
await this.save();
return true;
}
async updateFeedLastFetched(id: string): Promise<void> {
const feed = this.config.feeds.find(f => f.id === id);
if (feed) {
feed.lastFetched = new Date().toISOString();
await this.save();
}
}
private generateFeedId(): string {
return `feed_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
}