|
import axios from 'axios';
|
|
import { GITHUB_CONFIG } from '../config/users.js';
|
|
import memoryStorageService from './memoryStorageService.js';
|
|
|
|
class GitHubService {
|
|
constructor() {
|
|
this.apiUrl = GITHUB_CONFIG.apiUrl;
|
|
this.token = GITHUB_CONFIG.token;
|
|
this.repositories = GITHUB_CONFIG.repositories;
|
|
this.useMemoryStorage = !this.token;
|
|
|
|
console.log('=== GitHub Service Configuration ===');
|
|
console.log('Token configured:', !!this.token);
|
|
console.log('Token preview:', this.token ? `${this.token.substring(0, 8)}...` : 'Not set');
|
|
console.log('Repositories:', this.repositories);
|
|
console.log('Using memory storage:', this.useMemoryStorage);
|
|
|
|
if (!this.token) {
|
|
console.warn('GitHub token not configured, using memory storage for development');
|
|
}
|
|
}
|
|
|
|
|
|
async validateConnection() {
|
|
if (this.useMemoryStorage) {
|
|
return { valid: false, reason: 'No GitHub token configured' };
|
|
}
|
|
|
|
try {
|
|
|
|
const response = await axios.get(`${this.apiUrl}/user`, {
|
|
headers: {
|
|
'Authorization': `token ${this.token}`,
|
|
'Accept': 'application/vnd.github.v3+json'
|
|
}
|
|
});
|
|
|
|
console.log('GitHub API connection successful:', response.data.login);
|
|
|
|
|
|
const repoResults = [];
|
|
for (const repoUrl of this.repositories) {
|
|
try {
|
|
const { owner, repo } = this.parseRepoUrl(repoUrl);
|
|
const repoResponse = await axios.get(`${this.apiUrl}/repos/${owner}/${repo}`, {
|
|
headers: {
|
|
'Authorization': `token ${this.token}`,
|
|
'Accept': 'application/vnd.github.v3+json'
|
|
}
|
|
});
|
|
repoResults.push({ url: repoUrl, accessible: true, name: repoResponse.data.full_name });
|
|
} catch (error) {
|
|
repoResults.push({ url: repoUrl, accessible: false, error: error.message });
|
|
}
|
|
}
|
|
|
|
return { valid: true, user: response.data.login, repositories: repoResults };
|
|
} catch (error) {
|
|
console.error('GitHub connection validation failed:', error.message);
|
|
return { valid: false, reason: error.message };
|
|
}
|
|
}
|
|
|
|
|
|
parseRepoUrl(repoUrl) {
|
|
const match = repoUrl.match(/github\.com\/([^\/]+)\/([^\/]+)/);
|
|
if (!match) throw new Error('Invalid GitHub repository URL');
|
|
return { owner: match[1], repo: match[2] };
|
|
}
|
|
|
|
|
|
async getFile(userId, fileName, repoIndex = 0) {
|
|
|
|
if (this.useMemoryStorage) {
|
|
return await memoryStorageService.getFile(userId, fileName);
|
|
}
|
|
|
|
|
|
try {
|
|
const repoUrl = this.repositories[repoIndex];
|
|
const { owner, repo } = this.parseRepoUrl(repoUrl);
|
|
const path = `users/${userId}/${fileName}`;
|
|
|
|
const response = await axios.get(
|
|
`${this.apiUrl}/repos/${owner}/${repo}/contents/${path}`,
|
|
{
|
|
headers: {
|
|
'Authorization': `token ${this.token}`,
|
|
'Accept': 'application/vnd.github.v3+json'
|
|
}
|
|
}
|
|
);
|
|
|
|
const content = Buffer.from(response.data.content, 'base64').toString('utf8');
|
|
return {
|
|
content: JSON.parse(content),
|
|
sha: response.data.sha
|
|
};
|
|
} catch (error) {
|
|
if (error.response?.status === 404) {
|
|
return null;
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
|
|
async saveFile(userId, fileName, data, repoIndex = 0) {
|
|
|
|
if (this.useMemoryStorage) {
|
|
return await memoryStorageService.saveFile(userId, fileName, data);
|
|
}
|
|
|
|
|
|
const repoUrl = this.repositories[repoIndex];
|
|
const { owner, repo } = this.parseRepoUrl(repoUrl);
|
|
const path = `users/${userId}/${fileName}`;
|
|
|
|
console.log(`Attempting to save file: ${path} to repo: ${owner}/${repo}`);
|
|
|
|
|
|
let sha = null;
|
|
try {
|
|
const existing = await this.getFile(userId, fileName, repoIndex);
|
|
if (existing) {
|
|
sha = existing.sha;
|
|
console.log(`Found existing file with SHA: ${sha}`);
|
|
}
|
|
} catch (error) {
|
|
console.log(`No existing file found: ${error.message}`);
|
|
}
|
|
|
|
const content = Buffer.from(JSON.stringify(data, null, 2)).toString('base64');
|
|
|
|
const payload = {
|
|
message: `${sha ? 'Update' : 'Create'} ${fileName} for user ${userId}`,
|
|
content: content,
|
|
branch: 'main'
|
|
};
|
|
|
|
if (sha) {
|
|
payload.sha = sha;
|
|
}
|
|
|
|
try {
|
|
console.log(`Saving to GitHub: ${this.apiUrl}/repos/${owner}/${repo}/contents/${path}`);
|
|
|
|
const response = await axios.put(
|
|
`${this.apiUrl}/repos/${owner}/${repo}/contents/${path}`,
|
|
payload,
|
|
{
|
|
headers: {
|
|
'Authorization': `token ${this.token}`,
|
|
'Accept': 'application/vnd.github.v3+json'
|
|
}
|
|
}
|
|
);
|
|
|
|
console.log(`Successfully saved to GitHub: ${response.data.commit.sha}`);
|
|
return response.data;
|
|
} catch (error) {
|
|
console.error(`GitHub save failed:`, error.response?.data || error.message);
|
|
|
|
|
|
if (error.response?.status === 404) {
|
|
console.log('404 error - attempting to create directory structure...');
|
|
|
|
try {
|
|
|
|
const repoCheckResponse = await axios.get(`${this.apiUrl}/repos/${owner}/${repo}`, {
|
|
headers: {
|
|
'Authorization': `token ${this.token}`,
|
|
'Accept': 'application/vnd.github.v3+json'
|
|
}
|
|
});
|
|
console.log(`Repository exists: ${repoCheckResponse.data.full_name}`);
|
|
|
|
|
|
try {
|
|
await axios.get(`${this.apiUrl}/repos/${owner}/${repo}/contents/users`, {
|
|
headers: {
|
|
'Authorization': `token ${this.token}`,
|
|
'Accept': 'application/vnd.github.v3+json'
|
|
}
|
|
});
|
|
console.log('Users directory exists');
|
|
} catch (usersDirError) {
|
|
console.log('Users directory does not exist, creating...');
|
|
|
|
|
|
const usersReadmePath = 'users/README.md';
|
|
const usersReadmeContent = Buffer.from('# Users Directory\n\nThis directory contains user-specific PPT files.\n').toString('base64');
|
|
|
|
await axios.put(
|
|
`${this.apiUrl}/repos/${owner}/${repo}/contents/${usersReadmePath}`,
|
|
{
|
|
message: 'Create users directory',
|
|
content: usersReadmeContent,
|
|
branch: 'main'
|
|
},
|
|
{
|
|
headers: {
|
|
'Authorization': `token ${this.token}`,
|
|
'Accept': 'application/vnd.github.v3+json'
|
|
}
|
|
}
|
|
);
|
|
console.log('Users directory created');
|
|
}
|
|
|
|
|
|
try {
|
|
await axios.get(`${this.apiUrl}/repos/${owner}/${repo}/contents/users/${userId}`, {
|
|
headers: {
|
|
'Authorization': `token ${this.token}`,
|
|
'Accept': 'application/vnd.github.v3+json'
|
|
}
|
|
});
|
|
console.log(`User directory exists: users/${userId}`);
|
|
} catch (userDirError) {
|
|
console.log(`User directory does not exist, creating: users/${userId}`);
|
|
|
|
|
|
const userReadmePath = `users/${userId}/README.md`;
|
|
const userReadmeContent = Buffer.from(`# PPT Files for User ${userId}\n\nThis directory contains PPT files for user ${userId}.\n`).toString('base64');
|
|
|
|
await axios.put(
|
|
`${this.apiUrl}/repos/${owner}/${repo}/contents/${userReadmePath}`,
|
|
{
|
|
message: `Create user directory for ${userId}`,
|
|
content: userReadmeContent,
|
|
branch: 'main'
|
|
},
|
|
{
|
|
headers: {
|
|
'Authorization': `token ${this.token}`,
|
|
'Accept': 'application/vnd.github.v3+json'
|
|
}
|
|
}
|
|
);
|
|
console.log(`User directory created: users/${userId}`);
|
|
}
|
|
|
|
|
|
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
|
|
|
|
console.log('Retrying PPT file save...');
|
|
const retryResponse = await axios.put(
|
|
`${this.apiUrl}/repos/${owner}/${repo}/contents/${path}`,
|
|
payload,
|
|
{
|
|
headers: {
|
|
'Authorization': `token ${this.token}`,
|
|
'Accept': 'application/vnd.github.v3+json'
|
|
}
|
|
}
|
|
);
|
|
|
|
console.log(`Successfully saved to GitHub after retry: ${retryResponse.data.commit.sha}`);
|
|
return retryResponse.data;
|
|
|
|
} catch (retryError) {
|
|
console.error(`Comprehensive retry also failed:`, retryError.response?.data || retryError.message);
|
|
|
|
|
|
console.log('GitHub save completely failed, falling back to memory storage...');
|
|
try {
|
|
const memoryResult = await memoryStorageService.saveFile(userId, fileName, data);
|
|
console.log('Successfully saved to memory storage as fallback');
|
|
return {
|
|
...memoryResult,
|
|
warning: 'Saved to temporary memory storage due to GitHub issues'
|
|
};
|
|
} catch (memoryError) {
|
|
console.error('Memory storage fallback also failed:', memoryError.message);
|
|
throw new Error(`All storage methods failed. GitHub: ${retryError.message}, Memory: ${memoryError.message}`);
|
|
}
|
|
}
|
|
} else if (error.response?.status === 403) {
|
|
throw new Error(`GitHub permission denied. Check if the token has 'repo' permissions: ${error.response.data.message}`);
|
|
} else {
|
|
throw new Error(`GitHub API error (${error.response?.status}): ${error.response?.data?.message || error.message}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
async getUserPPTList(userId) {
|
|
|
|
if (this.useMemoryStorage) {
|
|
return await memoryStorageService.getUserPPTList(userId);
|
|
}
|
|
|
|
|
|
const results = [];
|
|
|
|
for (let i = 0; i < this.repositories.length; i++) {
|
|
try {
|
|
const repoUrl = this.repositories[i];
|
|
const { owner, repo } = this.parseRepoUrl(repoUrl);
|
|
const path = `users/${userId}`;
|
|
|
|
const response = await axios.get(
|
|
`${this.apiUrl}/repos/${owner}/${repo}/contents/${path}`,
|
|
{
|
|
headers: {
|
|
'Authorization': `token ${this.token}`,
|
|
'Accept': 'application/vnd.github.v3+json'
|
|
}
|
|
}
|
|
);
|
|
|
|
const files = response.data
|
|
.filter(item => item.type === 'file' && item.name.endsWith('.json'));
|
|
|
|
|
|
for (const file of files) {
|
|
try {
|
|
const pptId = file.name.replace('.json', '');
|
|
const fileContent = await this.getFile(userId, file.name, i);
|
|
|
|
if (fileContent && fileContent.content) {
|
|
results.push({
|
|
name: pptId,
|
|
title: fileContent.content.title || '未命名演示文稿',
|
|
lastModified: fileContent.content.updatedAt || fileContent.content.createdAt,
|
|
repoIndex: i,
|
|
repoUrl: repoUrl
|
|
});
|
|
}
|
|
} catch (error) {
|
|
|
|
console.warn(`Failed to read PPT content for ${file.name}:`, error.message);
|
|
results.push({
|
|
name: file.name.replace('.json', ''),
|
|
title: file.name.replace('.json', ''),
|
|
lastModified: new Date().toISOString(),
|
|
repoIndex: i,
|
|
repoUrl: repoUrl
|
|
});
|
|
}
|
|
}
|
|
} catch (error) {
|
|
if (error.response?.status !== 404) {
|
|
console.error(`Error fetching files from repo ${i}:`, error.message);
|
|
}
|
|
}
|
|
}
|
|
|
|
return results;
|
|
}
|
|
|
|
|
|
async deleteFile(userId, fileName, repoIndex = 0) {
|
|
|
|
if (this.useMemoryStorage) {
|
|
return await memoryStorageService.deleteFile(userId, fileName);
|
|
}
|
|
|
|
|
|
const existing = await this.getFile(userId, fileName, repoIndex);
|
|
if (!existing) {
|
|
throw new Error('File not found');
|
|
}
|
|
|
|
const repoUrl = this.repositories[repoIndex];
|
|
const { owner, repo } = this.parseRepoUrl(repoUrl);
|
|
const path = `users/${userId}/${fileName}`;
|
|
|
|
const response = await axios.delete(
|
|
`${this.apiUrl}/repos/${owner}/${repo}/contents/${path}`,
|
|
{
|
|
data: {
|
|
message: `Delete ${fileName} for user ${userId}`,
|
|
sha: existing.sha,
|
|
branch: 'main'
|
|
},
|
|
headers: {
|
|
'Authorization': `token ${this.token}`,
|
|
'Accept': 'application/vnd.github.v3+json'
|
|
}
|
|
}
|
|
);
|
|
|
|
return response.data;
|
|
}
|
|
}
|
|
|
|
export default new GitHubService(); |