mirror of
https://github.com/willmiao/ComfyUI-Lora-Manager.git
synced 2026-10-05 17:35:33 -03:00
CivitAI's public API deliberately omits prices — paidAccess is trimmed to
{permanent, endsAt} because "pricing belongs to the purchase flow" — but the
public model page embeds the site's own model.getById result, including
paidAccess.terms, in its server-rendered payload. That is read anonymously
(no API key, no internal endpoint, no forged Origin), one request per gated
model, so only the ~2% of models that actually carry a gate pay for it.
- optional capture, off by default: price_tracking_enabled,
price_alert_threshold_buzz (0 = alert on "became free" only) and
price_check_ttl_hours; prices refresh on their own TTL and immediately when a
gate changes, and a failed fetch keeps the stored price instead of blanking it
- versions that stop carrying a gate are marked free (persisted gate_lapsed_at)
and gate transitions are reported as events on the refresh response, so a
version already in the library can announce that it became free
- price_alert_state plus a price_drop edge event; new
GET /api/lm/{type}/updates/price-alerts lists what is under the threshold
- versions tab shows the price (effective, with the list price struck through
and a Blue Buzz note) and a Free Now badge; an update check toasts the
transitions in one message
- the parser and the alerts query are unit-tested against a trimmed page
fixture, and every route definition is now asserted to resolve to a handler
Plan, verification notes and the deviations from it are in
docs/plans/paid-model-price-tracking.md.
368 lines
13 KiB
JavaScript
368 lines
13 KiB
JavaScript
import { state } from '../state/index.js';
|
|
import { translate } from './i18nHelpers.js';
|
|
import { showToast } from './uiHelpers.js';
|
|
import { getCompleteApiConfig, getCurrentModelType } from '../api/apiConfig.js';
|
|
import { resetAndReload, getModelApiClient } from '../api/modelApiFactory.js';
|
|
import { getStorageItem, setStorageItem } from './storageHelpers.js';
|
|
import { modalManager } from '../managers/ModalManager.js';
|
|
|
|
const CHECK_UPDATES_CONFIRMATION_KEY = 'ack_check_updates_for_all_models';
|
|
|
|
/**
|
|
* Count the gate/price transitions reported by an update refresh.
|
|
* @param {Array} events - `events` array from the refresh response.
|
|
* @returns {{becameFree: number, newGate: number, priceDrop: number, total: number}}
|
|
*/
|
|
export function summarizeGateEvents(events) {
|
|
const list = Array.isArray(events) ? events : [];
|
|
return {
|
|
becameFree: list.filter((event) => event?.kind === 'became_free').length,
|
|
newGate: list.filter((event) => event?.kind === 'new_gate').length,
|
|
priceDrop: list.filter((event) => event?.kind === 'price_drop').length,
|
|
total: list.length
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Toast the gate/price transitions of an update refresh, if any. Kept to a single
|
|
* toast so a large refresh cannot bury the user in notifications.
|
|
* @param {Array} events
|
|
*/
|
|
export function showGateEventsToast(events) {
|
|
const { becameFree, newGate, priceDrop } = summarizeGateEvents(events);
|
|
if (!becameFree && !newGate && !priceDrop) {
|
|
return;
|
|
}
|
|
|
|
const parts = [];
|
|
if (becameFree) {
|
|
parts.push(
|
|
translate(
|
|
'globalContextMenu.checkModelUpdates.gateEvents.becameFree',
|
|
{ count: becameFree },
|
|
`${becameFree} version(s) became free`
|
|
)
|
|
);
|
|
}
|
|
if (priceDrop) {
|
|
parts.push(
|
|
translate(
|
|
'globalContextMenu.checkModelUpdates.gateEvents.priceDrop',
|
|
{ count: priceDrop },
|
|
`${priceDrop} version(s) dropped below your price threshold`
|
|
)
|
|
);
|
|
}
|
|
if (newGate) {
|
|
parts.push(
|
|
translate(
|
|
'globalContextMenu.checkModelUpdates.gateEvents.newGate',
|
|
{ count: newGate },
|
|
`${newGate} version(s) are now paid`
|
|
)
|
|
);
|
|
}
|
|
|
|
showToast(parts.join(' · '), {}, becameFree || priceDrop ? 'success' : 'info');
|
|
}
|
|
|
|
/**
|
|
* Perform a model update check using the shared backend endpoint.
|
|
* @param {Object} [options]
|
|
* @param {Function} [options.onStart] - Callback invoked before the request is sent.
|
|
* @param {Function} [options.onComplete] - Callback invoked after the request settles.
|
|
* @returns {Promise<{status: 'success' | 'error' | 'unsupported', displayName: string, records: Array, error: Error | null}>}
|
|
*/
|
|
export async function performModelUpdateCheck({ onStart, onComplete } = {}) {
|
|
const modelType = getCurrentModelType();
|
|
const apiConfig = getCompleteApiConfig(modelType);
|
|
const apiClient = getModelApiClient(modelType);
|
|
const displayName = apiConfig?.config?.displayName ?? 'Model';
|
|
|
|
if (!apiConfig?.endpoints?.refreshUpdates) {
|
|
console.warn('Refresh updates endpoint not configured for model type:', modelType);
|
|
onComplete?.({ status: 'unsupported', displayName, records: [], error: null });
|
|
return { status: 'unsupported', displayName, records: [], error: null };
|
|
}
|
|
|
|
const proceed = await ensureCheckUpdatesConfirmation(displayName);
|
|
if (!proceed) {
|
|
onComplete?.({ status: 'cancelled', displayName, records: [], error: null });
|
|
return { status: 'cancelled', displayName, records: [], error: null };
|
|
}
|
|
|
|
const loadingMessage = translate(
|
|
'globalContextMenu.checkModelUpdates.loading',
|
|
{ type: displayName },
|
|
`Checking for ${displayName} updates...`
|
|
);
|
|
|
|
onStart?.({ displayName, loadingMessage });
|
|
|
|
state.loadingManager?.showSimpleLoading?.(loadingMessage);
|
|
|
|
const abortController = new AbortController();
|
|
state.loadingManager?.showCancelButton?.(() => {
|
|
apiClient.cancelTask();
|
|
abortController.abort();
|
|
});
|
|
|
|
let status = 'success';
|
|
let records = [];
|
|
let error = null;
|
|
|
|
try {
|
|
const response = await fetch(apiConfig.endpoints.refreshUpdates, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
signal: abortController.signal,
|
|
body: JSON.stringify({ force: false })
|
|
});
|
|
|
|
let payload = {};
|
|
try {
|
|
payload = await response.json();
|
|
} catch {
|
|
payload = {};
|
|
}
|
|
|
|
if (!response.ok || payload.success !== true) {
|
|
if (payload?.status === 'cancelled') {
|
|
showToast('toast.api.operationCancelled', {}, 'info');
|
|
return { status: 'cancelled', displayName, records: [], error: null };
|
|
}
|
|
const errorMessage = payload?.error || response.statusText || 'Unknown error';
|
|
throw new Error(errorMessage);
|
|
}
|
|
|
|
records = Array.isArray(payload.records) ? payload.records : [];
|
|
|
|
if (records.length > 0) {
|
|
showToast('globalContextMenu.checkModelUpdates.success', { count: records.length, type: displayName }, 'success');
|
|
} else {
|
|
showToast('globalContextMenu.checkModelUpdates.none', { type: displayName }, 'info');
|
|
}
|
|
|
|
showGateEventsToast(payload.events);
|
|
|
|
await resetAndReload(false);
|
|
} catch (err) {
|
|
if (err?.name === 'AbortError') {
|
|
showToast('toast.api.operationCancelled', {}, 'info');
|
|
status = 'cancelled';
|
|
return { status: 'cancelled', displayName, records: [], error: null };
|
|
}
|
|
status = 'error';
|
|
error = err instanceof Error ? err : new Error(String(err));
|
|
console.error('Error checking model updates:', error);
|
|
showToast(
|
|
'globalContextMenu.checkModelUpdates.error',
|
|
{ message: error?.message ?? 'Unknown error', type: displayName },
|
|
'error'
|
|
);
|
|
} finally {
|
|
state.loadingManager?.hide?.();
|
|
if (typeof state.loadingManager?.restoreProgressBar === 'function') {
|
|
state.loadingManager.restoreProgressBar();
|
|
}
|
|
onComplete?.({ status, displayName, records, error });
|
|
}
|
|
|
|
return { status, displayName, records, error };
|
|
}
|
|
|
|
/**
|
|
* Perform a model update check scoped to a specific folder.
|
|
* @param {string} folderPath - The relative folder path to check.
|
|
* @param {Object} [options]
|
|
* @param {Function} [options.onComplete] - Callback invoked after the request settles.
|
|
* @returns {Promise<{status: string, records: Array, error: Error | null}>}
|
|
*/
|
|
export async function performFolderUpdateCheck(folderPath, { onComplete } = {}) {
|
|
const modelType = getCurrentModelType();
|
|
const apiConfig = getCompleteApiConfig(modelType);
|
|
const apiClient = getModelApiClient(modelType);
|
|
const displayName = apiConfig?.config?.displayName ?? 'Model';
|
|
|
|
if (!apiConfig?.endpoints?.refreshUpdates) {
|
|
console.warn('Refresh updates endpoint not configured for model type:', modelType);
|
|
onComplete?.({ status: 'unsupported', records: [], error: null });
|
|
return { status: 'unsupported', records: [], error: null };
|
|
}
|
|
|
|
const loadingMessage = translate(
|
|
'sidebar.folderUpdateCheck.loading',
|
|
{ type: displayName },
|
|
`Checking ${displayName} updates for this folder...`
|
|
);
|
|
|
|
state.loadingManager?.showSimpleLoading?.(loadingMessage);
|
|
|
|
const abortController = new AbortController();
|
|
state.loadingManager?.showCancelButton?.(() => {
|
|
apiClient.cancelTask();
|
|
abortController.abort();
|
|
});
|
|
|
|
let status = 'success';
|
|
let records = [];
|
|
let error = null;
|
|
|
|
try {
|
|
const response = await fetch(apiConfig.endpoints.refreshUpdates, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
signal: abortController.signal,
|
|
body: JSON.stringify({ folder_path: folderPath, force: false })
|
|
});
|
|
|
|
let payload = {};
|
|
try {
|
|
payload = await response.json();
|
|
} catch {
|
|
payload = {};
|
|
}
|
|
|
|
if (!response.ok || payload.success !== true) {
|
|
if (payload?.status === 'cancelled') {
|
|
showToast('toast.api.operationCancelled', {}, 'info');
|
|
return { status: 'cancelled', records: [], error: null };
|
|
}
|
|
const errorMessage = payload?.error || response.statusText || 'Unknown error';
|
|
throw new Error(errorMessage);
|
|
}
|
|
|
|
records = Array.isArray(payload.records) ? payload.records : [];
|
|
|
|
if (records.length > 0) {
|
|
showToast('sidebar.folderUpdateCheck.success', { count: records.length, type: displayName }, 'success');
|
|
} else {
|
|
showToast('sidebar.folderUpdateCheck.none', { type: displayName }, 'info');
|
|
}
|
|
|
|
showGateEventsToast(payload.events);
|
|
|
|
await resetAndReload(false);
|
|
} catch (err) {
|
|
if (err?.name === 'AbortError') {
|
|
showToast('toast.api.operationCancelled', {}, 'info');
|
|
status = 'cancelled';
|
|
return { status: 'cancelled', records: [], error: null };
|
|
}
|
|
status = 'error';
|
|
error = err instanceof Error ? err : new Error(String(err));
|
|
console.error('Error checking folder model updates:', error);
|
|
showToast(
|
|
'sidebar.folderUpdateCheck.error',
|
|
{ message: error?.message ?? 'Unknown error', type: displayName },
|
|
'error'
|
|
);
|
|
} finally {
|
|
state.loadingManager?.hide?.();
|
|
if (typeof state.loadingManager?.restoreProgressBar === 'function') {
|
|
state.loadingManager.restoreProgressBar();
|
|
}
|
|
onComplete?.({ status, records, error });
|
|
}
|
|
|
|
return { status, records, error };
|
|
}
|
|
|
|
function getTypePlural(displayName) {
|
|
if (!displayName) {
|
|
return 'models';
|
|
}
|
|
|
|
const lower = displayName.toLowerCase();
|
|
if (lower.endsWith('s')) {
|
|
return displayName;
|
|
}
|
|
|
|
return `${displayName}s`;
|
|
}
|
|
|
|
async function ensureCheckUpdatesConfirmation(displayName) {
|
|
const hasConfirmed = getStorageItem(CHECK_UPDATES_CONFIRMATION_KEY, false);
|
|
if (hasConfirmed) {
|
|
return true;
|
|
}
|
|
|
|
const modalElement = document.getElementById('checkUpdatesConfirmModal');
|
|
if (!modalElement) {
|
|
return true;
|
|
}
|
|
|
|
const typePlural = getTypePlural(displayName);
|
|
|
|
const titleElement = modalElement.querySelector('[data-role="title"]');
|
|
if (titleElement) {
|
|
titleElement.textContent = translate(
|
|
'modals.checkUpdates.title',
|
|
{ type: displayName, typePlural },
|
|
`Check updates for all ${typePlural}?`
|
|
);
|
|
}
|
|
|
|
const messageElement = modalElement.querySelector('[data-role="message"]');
|
|
if (messageElement) {
|
|
messageElement.textContent = translate(
|
|
'modals.checkUpdates.message',
|
|
{ type: displayName, typePlural },
|
|
`This checks every ${typePlural} in your library for updates. Large collections may take a little longer.`
|
|
);
|
|
}
|
|
|
|
const tipElement = modalElement.querySelector('[data-role="tip"]');
|
|
if (tipElement) {
|
|
tipElement.textContent = translate(
|
|
'modals.checkUpdates.tip',
|
|
{ type: displayName, typePlural },
|
|
'To work in smaller batches, switch to bulk mode, pick the ones you need, then use "Check Updates for Selected".'
|
|
);
|
|
}
|
|
|
|
const confirmButton = modalElement.querySelector('[data-action="confirm-check-updates"]');
|
|
const cancelButton = modalElement.querySelector('[data-action="cancel-check-updates"]');
|
|
|
|
if (!confirmButton || !cancelButton) {
|
|
return true;
|
|
}
|
|
|
|
return new Promise((resolve) => {
|
|
let resolved = false;
|
|
|
|
const cleanup = () => {
|
|
confirmButton.removeEventListener('click', handleConfirm);
|
|
cancelButton.removeEventListener('click', handleCancel);
|
|
};
|
|
|
|
const finalize = (proceed) => {
|
|
if (resolved) {
|
|
return;
|
|
}
|
|
|
|
resolved = true;
|
|
cleanup();
|
|
resolve(proceed);
|
|
};
|
|
|
|
const handleConfirm = (event) => {
|
|
event.preventDefault();
|
|
setStorageItem(CHECK_UPDATES_CONFIRMATION_KEY, true);
|
|
finalize(true);
|
|
modalManager.closeModal('checkUpdatesConfirmModal');
|
|
};
|
|
|
|
const handleCancel = (event) => {
|
|
event.preventDefault();
|
|
finalize(false);
|
|
modalManager.closeModal('checkUpdatesConfirmModal');
|
|
};
|
|
|
|
confirmButton.addEventListener('click', handleConfirm);
|
|
cancelButton.addEventListener('click', handleCancel);
|
|
|
|
modalManager.showModal('checkUpdatesConfirmModal', null, () => finalize(false));
|
|
});
|
|
}
|