mirror of
https://github.com/n8n-io/n8n-nodes-starter.git
synced 2025-10-30 14:52:27 -05:00
Jules was unable to complete the task in time. Please review the work done so far and provide feedback for Jules to continue.
This commit is contained in:
parent
6c69a287fe
commit
18768ebb98
5 changed files with 592 additions and 256 deletions
|
|
@ -3,21 +3,29 @@ import type {
|
|||
INodeTypeDescription,
|
||||
ITriggerFunctions,
|
||||
ITriggerResponse,
|
||||
ICredentialDataDecryptedObject, // Added
|
||||
} from 'n8n-workflow';
|
||||
import { NodeOperationError } from 'n8n-workflow'; // Added
|
||||
|
||||
import {
|
||||
pollJobStatus,
|
||||
listPreviousSongs,
|
||||
loginWithCredentials,
|
||||
} from '../../utils/sunoApi';
|
||||
|
||||
export class SunoTrigger implements INodeType {
|
||||
description: INodeTypeDescription = {
|
||||
displayName: 'Suno Trigger',
|
||||
name: 'sunoTrigger',
|
||||
icon: 'file:suno.svg', // Re-use the icon
|
||||
icon: 'file:suno.svg',
|
||||
group: ['trigger', 'ai'],
|
||||
version: 1,
|
||||
description: 'Triggers when a Suno AI event occurs',
|
||||
description: 'Triggers when a Suno AI event occurs (polling)',
|
||||
defaults: {
|
||||
name: 'Suno Trigger',
|
||||
},
|
||||
inputs: [], // Triggers usually do not have inputs
|
||||
outputs: ['main'], // Main output for triggered data
|
||||
inputs: [],
|
||||
outputs: ['main'],
|
||||
credentials: [
|
||||
{
|
||||
name: 'sunoApi',
|
||||
|
|
@ -25,7 +33,6 @@ export class SunoTrigger implements INodeType {
|
|||
},
|
||||
],
|
||||
properties: [
|
||||
// Define properties for the trigger
|
||||
{
|
||||
displayName: 'Trigger Event',
|
||||
name: 'triggerEvent',
|
||||
|
|
@ -46,7 +53,7 @@ export class SunoTrigger implements INodeType {
|
|||
description: 'The Suno event that will trigger this node',
|
||||
},
|
||||
{
|
||||
displayName: 'Track ID',
|
||||
displayName: 'Track ID (for Track Generation Complete)',
|
||||
name: 'trackId',
|
||||
type: 'string',
|
||||
default: '',
|
||||
|
|
@ -61,72 +68,102 @@ export class SunoTrigger implements INodeType {
|
|||
displayName: 'Polling Interval (minutes)',
|
||||
name: 'pollingInterval',
|
||||
type: 'number',
|
||||
default: 5,
|
||||
description: 'How often to check for new songs (if applicable)',
|
||||
displayOptions: {
|
||||
show: {
|
||||
triggerEvent: ['newSongAvailable'],
|
||||
},
|
||||
},
|
||||
default: 5, // Default to 5 minutes
|
||||
description: 'How often to check for events. n8n will manage the actual polling schedule based on this.',
|
||||
// displayOptions: { // Not strictly needed to show for both, but can be kept
|
||||
// show: {
|
||||
// triggerEvent: ['newSongAvailable', 'trackGenerationComplete'],
|
||||
// },
|
||||
// },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// Placeholder for trigger methods
|
||||
/**
|
||||
* The `trigger` method is called when the workflow is activated.
|
||||
* For polling triggers using `manualTriggerFunction`, this method can be used
|
||||
* for initial setup, like setting the polling interval or initial authentication.
|
||||
*/
|
||||
async trigger(this: ITriggerFunctions): Promise<ITriggerResponse | undefined> {
|
||||
// const credentials = await this.getCredentials('sunoApi');
|
||||
// const triggerEvent = this.getNodeParameter('triggerEvent') as string;
|
||||
// const trackId = this.getNodeParameter('trackId') as string;
|
||||
// const pollingInterval = this.getNodeParameter('pollingInterval') as number;
|
||||
const pollingIntervalMinutes = this.getNodeParameter('pollingInterval', 5) as number;
|
||||
this.setPollingInterval(pollingIntervalMinutes * 60 * 1000); // Set n8n's polling interval
|
||||
|
||||
// TODO: Implement actual trigger logic based on triggerEvent
|
||||
// For 'trackGenerationComplete', this might involve polling pollJobStatus(trackId)
|
||||
// For 'newSongAvailable', this might involve polling listPreviousSongs() and checking for new entries
|
||||
|
||||
// If webhook based, this method would be different,
|
||||
// this.emit([this.helpers.returnJsonArray([{ eventData: 'example' }])]);
|
||||
// this.on('close', () => { /* remove webhook */ });
|
||||
// return { webhookId: 'your-webhook-id' };
|
||||
|
||||
// For polling triggers, this method might not be used directly if using manualTriggerFunction
|
||||
if (this.manualTriggerFunction) { // Corrected placeholder name
|
||||
// Manual trigger logic for polling
|
||||
// This will be called by n8n based on the schedule if `manualTriggerFunction` is defined
|
||||
// Example:
|
||||
// const items = await pollSunoApiForUpdates();
|
||||
// if (items.length > 0) {
|
||||
// return {
|
||||
// items: this.helpers.returnJsonArray(items),
|
||||
// };
|
||||
// }
|
||||
// return undefined; // No new items
|
||||
try {
|
||||
const credentials = await this.getCredentials('sunoApi') as ICredentialDataDecryptedObject;
|
||||
if (!credentials || !credentials.email || !credentials.password) {
|
||||
throw new NodeOperationError(this.getNode(), 'Suno API credentials are not configured or incomplete.');
|
||||
}
|
||||
// Perform an initial login to ensure credentials are valid and API is reachable
|
||||
await loginWithCredentials(credentials.email as string, credentials.password as string);
|
||||
console.log('SunoTrigger: Initial authentication successful for polling setup.');
|
||||
} catch (error) {
|
||||
console.error('SunoTrigger: Initial authentication or setup failed.', error);
|
||||
// Depending on how n8n handles this, we might throw or just log.
|
||||
// For a trigger, throwing here might prevent it from starting.
|
||||
if (error instanceof NodeOperationError) throw error;
|
||||
throw new NodeOperationError(this.getNode(), `Initial setup failed: ${error.message || String(error)}`);
|
||||
}
|
||||
|
||||
// For now, returning undefined as it's a placeholder
|
||||
// For a polling trigger, you might set up an interval here or use manualTriggerFunction
|
||||
// For a webhook trigger, you would register the webhook here.
|
||||
return undefined;
|
||||
// For pure polling, manualTriggerFunction will handle the periodic checks.
|
||||
// If specific cleanup is needed when the workflow deactivates, return a closeFunction.
|
||||
return {
|
||||
closeFunction: async () => {
|
||||
console.log('SunoTrigger: Polling stopped.');
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Example of how a manual trigger function might be structured for polling
|
||||
// async manualTrigger(this: ITriggerFunctions): Promise<INodeExecutionData[][] | undefined> {
|
||||
// const triggerEvent = this.getNodeParameter('triggerEvent') as string;
|
||||
// // ... get other params and credentials
|
||||
//
|
||||
// if (triggerEvent === 'newSongAvailable') {
|
||||
// console.log('Polling for new songs...');
|
||||
// // const newSongs = await sunoApi.listPreviousSongs(credentials, /* potential pagination params */);
|
||||
// // Check against previously seen songs (requires state management, complex for this scaffold)
|
||||
// // For now, let's simulate finding one new song:
|
||||
// // const simulatedNewSong = [{ id: 'new_track_123', title: 'A New Song', status: 'complete' }];
|
||||
// // return [this.helpers.returnJsonArray(simulatedNewSong)];
|
||||
// } else if (triggerEvent === 'trackGenerationComplete') {
|
||||
// // const trackId = this.getNodeParameter('trackId') as string;
|
||||
// // const status = await sunoApi.pollJobStatus(credentials, trackId);
|
||||
// // if (status && status.status === 'complete') {
|
||||
// // return [this.helpers.returnJsonArray([status])];
|
||||
// // }
|
||||
// }
|
||||
// return undefined; // No trigger event
|
||||
// }
|
||||
/**
|
||||
* `manualTriggerFunction` is called by n8n at the defined polling interval.
|
||||
* It should fetch data and emit items if new events are found.
|
||||
*/
|
||||
public async manualTrigger(this: ITriggerFunctions): Promise<void> {
|
||||
const triggerEvent = this.getNodeParameter('triggerEvent') as string;
|
||||
|
||||
try {
|
||||
const credentials = await this.getCredentials('sunoApi') as ICredentialDataDecryptedObject;
|
||||
if (!credentials || !credentials.email || !credentials.password) {
|
||||
console.error('SunoTrigger: Credentials not available for polling.');
|
||||
// Optionally emit an error to the workflow execution log, but be careful not to flood it.
|
||||
// this.emit([this.helpers.returnJsonArray([{ error: 'Credentials missing for polling' }])]);
|
||||
return; // Stop further execution for this poll if creds are missing
|
||||
}
|
||||
|
||||
// Ensure we are "logged in" for each poll execution, as the token state is managed in sunoApi.ts
|
||||
// and might "expire" or the trigger instance could be new.
|
||||
await loginWithCredentials(credentials.email as string, credentials.password as string);
|
||||
|
||||
if (triggerEvent === 'trackGenerationComplete') {
|
||||
const trackId = this.getNodeParameter('trackId', '') as string;
|
||||
if (!trackId) {
|
||||
console.warn('SunoTrigger: Track ID not provided for "Track Generation Complete" event. Skipping poll.');
|
||||
return;
|
||||
}
|
||||
const jobStatus = await pollJobStatus(trackId);
|
||||
// Simple mock: emit if the job is 'complete' and has a trackId.
|
||||
// A real implementation would need state to avoid re-emitting for the same completed track.
|
||||
if (jobStatus && jobStatus.status === 'complete' && jobStatus.trackId) {
|
||||
console.log(`SunoTrigger: Track ${jobStatus.trackId} (Job ID: ${jobStatus.id}) is complete. Emitting.`);
|
||||
this.emit([this.helpers.returnJsonArray([jobStatus])]);
|
||||
} else {
|
||||
console.log(`SunoTrigger: Track ID ${trackId} status: ${jobStatus.status || 'unknown'}. Not emitting.`);
|
||||
}
|
||||
} else if (triggerEvent === 'newSongAvailable') {
|
||||
const songs = await listPreviousSongs();
|
||||
// Simple mock: if songs are found, emit the first one.
|
||||
// A real implementation needs sophisticated state management to detect "new" songs
|
||||
// (e.g., comparing against IDs seen in the previous poll).
|
||||
if (songs && songs.length > 0) {
|
||||
console.log('SunoTrigger: New songs found (mock implementation). Emitting the first song from the list.');
|
||||
this.emit([this.helpers.returnJsonArray([songs[0]])]);
|
||||
} else {
|
||||
console.log('SunoTrigger: No new songs found (mock implementation).');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('SunoTrigger: Error during polling execution:', error);
|
||||
// Optionally emit an error item to the workflow execution log
|
||||
// this.emit([this.helpers.returnJsonArray([{ error: `Polling error: ${error.message || String(error)}` }])]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue