Skip to content

A games launcher for GOG, Amazon and Epic Games for Linux, Windows and macOS.

[Feat] Sync Itch.io bundles and Free Games (#6134)

Flávio Fearnac82ee74e151
diff --git a/public/locales/en/gamepage.json b/public/locales/en/gamepage.json
index bfb62e743..1278d09b9 100644
--- a/public/locales/en/gamepage.json
+++ b/public/locales/en/gamepage.json
@@ -253,8 +253,28 @@
"wineversion": "Wine version"
},
"itchio": {
+ "catalog": {
+ "added": {
+ "message": "The game was added to your \"heroic\" collection on itch.io.",
+ "title": "Added to your catalog"
+ },
+ "failed": {
+ "title": "Could not add to your catalog"
+ }
+ },
"import": {
"warning": "Folders installed by the itch.io app are fully imported, including updates. For any other folder, Heroic cannot check for updates and uninstalling will not delete the game files."
+ },
+ "locked": {
+ "add": "Add to catalog",
+ "message": "Heroic can't install this game because you don't own it and it isn't free on itch.io. You can add it to your itch.io catalog to keep it in this library.",
+ "open": "Open on itch.io",
+ "title": "Not available in Heroic"
+ },
+ "status": {
+ "bundle": "Bundle",
+ "free": "Free",
+ "unowned": "Not owned"
}
},
"label": {
diff --git a/public/locales/en/translation.json b/public/locales/en/translation.json
index e34a14c4d..5c2d1fd20 100644
--- a/public/locales/en/translation.json
+++ b/public/locales/en/translation.json
@@ -656,7 +656,9 @@
"platforms": "Platforms",
"reset": "Reset",
"select_all": "Select all",
+ "show_bundles_only": "From bundles",
"show_favourites_only": "Show favourites only",
+ "show_free_only": "Free",
"show_installed_only": "Show installed only",
"show_steam_owned_only": "Show Steam owned games only",
"show_support_offline_only": "Show offline-supported only",
diff --git a/src/backend/main.ts b/src/backend/main.ts
index b8d12b7fa..655bc451b 100644
--- a/src/backend/main.ts
+++ b/src/backend/main.ts
@@ -44,6 +44,7 @@ import { LegendaryUser } from 'backend/storeManagers/legendary/user'
import { GOGUser } from './storeManagers/gog/user'
import gogPresence from './storeManagers/gog/presence'
import { NileUser } from './storeManagers/nile/user'
+import { addGameToCatalog } from './storeManagers/itchio/library'
import { ItchioUser } from './storeManagers/itchio/user'
import { ITCHIO_OAUTH_REDIRECT_URI } from 'common/types/itchio'
import { ZoomUser } from './storeManagers/zoom/user'
@@ -911,6 +912,12 @@ addHandler('authItchioOAuth', async (_event, data) =>
ItchioUser.loginWithOAuthCode(data)
)
addHandler('logoutItchio', async () => ItchioUser.logout())
+addHandler('itchioAddGameToCatalog', async (_event, appName) => {
+ const result = await addGameToCatalog(appName)
+ return result.error
+ ? { status: 'failed' as const, error: result.error }
+ : { status: 'done' as const }
+})
addHandler('authZoom', async (event, url) => {
const login = await ZoomUser.login(url)
diff --git a/src/backend/storeManagers/itchio/__tests__/library.test.ts b/src/backend/storeManagers/itchio/__tests__/library.test.ts
new file mode 100644
index 000000000..59b3ba25a
--- /dev/null
+++ b/src/backend/storeManagers/itchio/__tests__/library.test.ts
@@ -0,0 +1,349 @@
+import type { GameInfo } from 'common/types'
+import type { ItchioGame } from 'common/types/itchio'
+import { sendFrontendMessage } from 'backend/ipc'
+
+import ItchioLibraryManager, { addGameToCatalog } from '../library'
+
+const mockCall = jest.fn<Promise<unknown>, [string, Record<string, unknown>]>()
+const mockLibrarySet = jest.fn<void, [string, unknown]>()
+const mockGetNodefault = jest.fn<number | undefined, [string]>()
+
+jest.mock('../butlerd', () => ({
+ getClient: () => Promise.resolve({ call: mockCall })
+}))
+jest.mock('../electronStores', () => ({
+ configStore: {
+ get_nodefault: (key: string) => mockGetNodefault(key)
+ },
+ installStore: { get: jest.fn(), set: jest.fn() },
+ libraryStore: {
+ get: () => [],
+ set: (key: string, value: unknown) => mockLibrarySet(key, value)
+ }
+}))
+jest.mock('../user', () => ({
+ ItchioUser: { isLoggedIn: () => true }
+}))
+jest.mock('../setup', () => ({ __esModule: true, default: jest.fn() }))
+jest.mock('../games', () => ({ __esModule: true, default: class {} }))
+jest.mock('../constants', () => ({
+ butlerDbPath: '/tmp/itchio/butler.db',
+ itchioStoreConfigPath: '/tmp/itchio/config.json'
+}))
+jest.mock('backend/ipc', () => ({ sendFrontendMessage: jest.fn() }))
+jest.mock('backend/logger', () => ({
+ logInfo: jest.fn(),
+ logDebug: jest.fn(),
+ logWarning: jest.fn(),
+ logError: jest.fn(),
+ LogPrefix: { Itchio: 'Itchio' }
+}))
+jest.mock('backend/constants/environment', () => ({ isLinux: true }))
+jest.mock('backend/importExport/constants', () => ({ BACKUP_PATHS: {} }))
+
+type ButlerdHandler = (params: Record<string, unknown>) => unknown
+
+function mockButlerd(handlers: Record<string, ButlerdHandler>) {
+ mockCall.mockImplementation((method, params) => {
+ const handler = handlers[method]
+ if (!handler) {
+ return Promise.reject(new Error(`unexpected butlerd method ${method}`))
+ }
+ return Promise.resolve(handler(params))
+ })
+}
+
+function makeGame(id: number, title: string): ItchioGame {
+ return {
+ id,
+ title,
+ url: `https://example.itch.io/${id}`,
+ user: { id: 1, username: 'dev', url: 'https://example.itch.io' },
+ platforms: { windows: true },
+ owned_dlc: []
+ }
+}
+
+function refreshedLibrary(): GameInfo[] {
+ const call = mockLibrarySet.mock.calls.find(([key]) => key === 'library')
+ expect(call).toBeDefined()
+ return call![1] as GameInfo[]
+}
+
+function libraryEntry(library: GameInfo[], title: string): GameInfo {
+ const entry = library.find((game) => game.title === title)
+ expect(entry).toBeDefined()
+ return entry!
+}
+
+const winUpload = {
+ id: 5,
+ filename: 'game.zip',
+ size: 1234,
+ platforms: { windows: true }
+}
+
+beforeEach(() => {
+ mockGetNodefault.mockReturnValue(42)
+})
+
+describe('itch.io library refresh', () => {
+ it('merges owned keys, bundle games and the named discovery collections', async () => {
+ mockButlerd({
+ 'Fetch.ProfileOwnedKeys': () => ({
+ items: [{ id: 1, gameId: 10, game: makeGame(10, 'Owned') }]
+ }),
+ 'Fetch.ProfileBundleOwnerships': () => ({}),
+ 'Fetch.ProfileOwnedBundles': () => ({
+ items: [{ bundleId: 100, bundle: { id: 100, title: 'Bundle' } }]
+ }),
+ 'Fetch.BundleGames': () => ({
+ items: [{ bundleId: 100, gameId: 11, game: makeGame(11, 'Bundled') }]
+ }),
+ 'Fetch.ProfileCollections': () => ({
+ items: [
+ { id: 7, title: 'jams' },
+ { id: 8, title: ' Heroic ' }
+ ]
+ }),
+ 'Fetch.Collection.Games': (params) => {
+ expect(params.collectionId).toBe(8)
+ return {
+ items: [
+ { collectionId: 8, gameId: 12, game: makeGame(12, 'Collected') }
+ ]
+ }
+ }
+ })
+
+ await new ItchioLibraryManager().refresh()
+
+ const library = refreshedLibrary()
+ expect(library.map((game) => game.title).sort()).toEqual([
+ 'Bundled',
+ 'Collected',
+ 'Owned'
+ ])
+ expect(libraryEntry(library, 'Owned').itchio_source).toBe('owned')
+ expect(libraryEntry(library, 'Bundled').itchio_source).toBe('bundle')
+ expect(libraryEntry(library, 'Bundled').itchio_status).toBe('owned')
+ expect(libraryEntry(library, 'Collected').itchio_source).toBe('collection')
+ expect(libraryEntry(library, 'Collected').itchio_status).toBe('free')
+ })
+
+ it('marks unowned paid collection games as not installable', async () => {
+ mockButlerd({
+ 'Fetch.ProfileOwnedKeys': () => ({ items: [] }),
+ 'Fetch.ProfileBundleOwnerships': () => ({}),
+ 'Fetch.ProfileOwnedBundles': () => ({ items: [] }),
+ 'Fetch.ProfileCollections': () => ({
+ items: [{ id: 8, title: 'heroic' }]
+ }),
+ 'Fetch.Collection.Games': () => ({
+ items: [
+ {
+ collectionId: 8,
+ gameId: 30,
+ game: {
+ ...makeGame(30, 'Paid'),
+ canBeBought: true,
+ minPrice: 499
+ }
+ }
+ ]
+ })
+ })
+
+ await new ItchioLibraryManager().refresh()
+
+ const paid = libraryEntry(refreshedLibrary(), 'Paid')
+ expect(paid.itchio_status).toBe('unowned')
+ expect(paid.installable).toBe(false)
+ })
+
+ it('dedupes a game that is both an owned key and a bundle game', async () => {
+ mockButlerd({
+ 'Fetch.ProfileOwnedKeys': () => ({
+ items: [{ id: 1, gameId: 10, game: makeGame(10, 'Owned') }]
+ }),
+ 'Fetch.ProfileBundleOwnerships': () => ({}),
+ 'Fetch.ProfileOwnedBundles': () => ({
+ items: [{ bundleId: 100, bundle: { id: 100, title: 'Bundle' } }]
+ }),
+ 'Fetch.BundleGames': () => ({
+ items: [{ bundleId: 100, gameId: 10, game: makeGame(10, 'Owned') }]
+ }),
+ 'Fetch.ProfileCollections': () => ({
+ items: [
+ { id: 8, title: 'lutris' },
+ { id: 9, title: 'not-ours' }
+ ]
+ }),
+ 'Fetch.Collection.Games': () => ({
+ items: [{ collectionId: 8, gameId: 10, game: makeGame(10, 'Owned') }]
+ })
+ })
+
+ await new ItchioLibraryManager().refresh()
+
+ expect(refreshedLibrary()).toHaveLength(1)
+ })
+
+ it('keeps the owned games when the bundle/collection sources fail', async () => {
+ mockButlerd({
+ 'Fetch.ProfileOwnedKeys': () => ({
+ items: [{ id: 1, gameId: 10, game: makeGame(10, 'Owned') }]
+ }),
+ 'Fetch.ProfileBundleOwnerships': () => {
+ throw new Error('Method not found')
+ },
+ 'Fetch.ProfileOwnedBundles': () => {
+ throw new Error('Method not found')
+ },
+ 'Fetch.ProfileCollections': () => ({
+ items: [{ id: 8, title: 'heroic' }]
+ }),
+ 'Fetch.Collection.Games': () => ({
+ items: [
+ { collectionId: 8, gameId: 12, game: makeGame(12, 'Collected') }
+ ]
+ })
+ })
+
+ await new ItchioLibraryManager().refresh()
+
+ expect(
+ refreshedLibrary()
+ .map((game) => game.title)
+ .sort()
+ ).toEqual(['Collected', 'Owned'])
+ })
+})
+
+describe('itch.io catalog collection', () => {
+ it('adds the game to the existing heroic collection', async () => {
+ let added: Record<string, unknown> | undefined
+ mockCall.mockImplementation((method, params) => {
+ if (method === 'Fetch.ProfileCollections') {
+ return Promise.resolve({
+ items: [
+ { id: 7, title: 'jams' },
+ { id: 8, title: 'Heroic' }
+ ]
+ })
+ }
+ if (method === 'Collections.AddGame') {
+ added = params
+ return Promise.resolve({})
+ }
+ return Promise.reject(new Error(`unexpected butlerd method ${method}`))
+ })
+
+ const result = await addGameToCatalog('itchio-12')
+
+ expect(result.error).toBeUndefined()
+ expect(added).toEqual({ profileId: 42, collectionId: 8, gameId: 12 })
+ })
+
+ it('creates a private heroic collection when none exists', async () => {
+ let created: Record<string, unknown> | undefined
+ mockCall.mockImplementation((method, params) => {
+ if (method === 'Fetch.ProfileCollections') {
+ return Promise.resolve({ items: [{ id: 7, title: 'jams' }] })
+ }
+ if (method === 'Collections.Create') {
+ created = params
+ return Promise.resolve({})
+ }
+ return Promise.reject(new Error(`unexpected butlerd method ${method}`))
+ })
+
+ const result = await addGameToCatalog('itchio-12')
+
+ expect(result.error).toBeUndefined()
+ expect(created).toEqual({
+ profileId: 42,
+ title: 'heroic',
+ private: true,
+ gameId: 12
+ })
+ })
+})
+
+describe('itch.io install info', () => {
+ async function seedLibrary(gameId: number) {
+ mockButlerd({
+ 'Fetch.ProfileOwnedKeys': () => ({
+ items: [{ id: 2, gameId, game: makeGame(gameId, 'Bundled') }]
+ }),
+ 'Fetch.ProfileBundleOwnerships': () => ({}),
+ 'Fetch.ProfileOwnedBundles': () => ({ items: [] }),
+ 'Fetch.ProfileCollections': () => ({ items: [] })
+ })
+ await new ItchioLibraryManager().refresh()
+ mockLibrarySet.mockClear()
+ }
+
+ it('materializes the bundle download key when the view path lists no uploads', async () => {
+ await seedLibrary(20)
+ const methods: string[] = []
+ mockCall.mockImplementation((method: string) => {
+ methods.push(method)
+ if (method === 'Fetch.GameUploads')
+ return Promise.resolve({ uploads: [] })
+ if (method === 'Fetch.GameOwnership') {
+ return Promise.resolve({ owned: true, bundleId: 9 })
+ }
+ if (method === 'Install.GetUploads') {
+ return Promise.resolve({
+ uploads: [],
+ incompatibleUploads: [winUpload]
+ })
+ }
+ return Promise.reject(new Error(`unexpected butlerd method ${method}`))
+ })
+
+ const info = await new ItchioLibraryManager().getInstallInfo(
+ 'itchio-20',
+ 'Windows'
+ )
+
+ expect((info as { upload?: unknown } | undefined)?.upload).toEqual(
+ winUpload
+ )
+ expect(methods).toContain('Install.GetUploads')
+ expect(sendFrontendMessage).toHaveBeenCalledWith(
+ 'pushGameToLibrary',
+ expect.objectContaining({
+ app_name: 'itchio-20',
+ itchio_source: 'owned',
+ itchio_status: 'owned',
+ installable: true
+ })
+ )
+ })
+
+ it('does not claim anything when the uploads are already listed', async () => {
+ await seedLibrary(21)
+ const methods: string[] = []
+ mockCall.mockImplementation((method: string) => {
+ methods.push(method)
+ if (method === 'Fetch.GameUploads') {
+ return Promise.resolve({ uploads: [winUpload] })
+ }
+ return Promise.reject(new Error(`unexpected butlerd method ${method}`))
+ })
+
+ const info = await new ItchioLibraryManager().getInstallInfo(
+ 'itchio-21',
+ 'Windows'
+ )
+
+ expect((info as { upload?: unknown } | undefined)?.upload).toEqual(
+ winUpload
+ )
+ expect(methods).not.toContain('Install.GetUploads')
+ expect(methods).not.toContain('Fetch.GameOwnership')
+ expect(sendFrontendMessage).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/backend/storeManagers/itchio/library.ts b/src/backend/storeManagers/itchio/library.ts
index 3ea7d9a7c..18200e43f 100644
--- a/src/backend/storeManagers/itchio/library.ts
+++ b/src/backend/storeManagers/itchio/library.ts
@@ -7,6 +7,8 @@ import {
} from 'common/types'
import {
ItchioGame,
+ ItchioGameSource,
+ ItchioGameStatus,
ItchioInstallInfo,
ItchioUpload
} from 'common/types/itchio'
@@ -20,9 +22,16 @@ import {
import { join, relative } from 'path'
import { readFileSync } from 'graceful-fs'
-import { LogPrefix, logDebug, logError, logInfo } from 'backend/logger'
+import {
+ LogPrefix,
+ logDebug,
+ logError,
+ logInfo,
+ logWarning
+} from 'backend/logger'
import { isLinux } from 'backend/constants/environment'
import { BACKUP_PATHS } from 'backend/importExport/constants'
+import { sendFrontendMessage } from 'backend/ipc'
import { getClient } from './butlerd'
import { configStore, installStore, libraryStore } from './electronStores'
@@ -30,6 +39,7 @@ import { butlerDbPath, itchioStoreConfigPath } from './constants'
import { ItchioUser } from './user'
import ItchioGameManager from './games'
import setupItchio from './setup'
+import type { ButlerdClient } from './butlerdClient'
interface DownloadKeyRecord {
id: number
@@ -37,16 +47,52 @@ interface DownloadKeyRecord {
game: ItchioGame
}
-interface FetchProfileOwnedKeysResult {
- items: DownloadKeyRecord[]
+interface FetchGameUploadsResult {
+ uploads: ItchioUpload[]
+}
+
+interface PagedResult<T> {
+ items?: T[]
stale?: boolean
nextCursor?: string
}
-interface FetchGameUploadsResult {
- uploads: ItchioUpload[]
+interface ButlerdBundleKey {
+ bundleId: number
+ bundle?: { id: number; title: string }
+}
+
+interface ButlerdBundleGame {
+ bundleId: number
+ game?: ItchioGame
+}
+
+interface ButlerdCollection {
+ id: number
+ title: string
+}
+
+interface ButlerdCollectionGame {
+ collectionId: number
+ game?: ItchioGame
+}
+
+interface FetchGameOwnershipResult {
+ owned: boolean
+ bundleId?: number
}
+interface InstallGetUploadsResult {
+ uploads?: ItchioUpload[]
+ incompatibleUploads?: ItchioUpload[]
+}
+
+// Lutris-compatible escape hatch for games the owned-keys list misses.
+const DISCOVERY_COLLECTION_NAMES = ['heroic', 'lutris']
+const CATALOG_COLLECTION_NAME = 'heroic'
+
+const MAX_PAGES = 50
+
const inMemoryLibrary: Map<string, ItchioGameInfo> = new Map()
function gameToAppName(game: ItchioGame): string {
@@ -58,6 +104,15 @@ export function gameIdFromAppName(appName: string): number | undefined {
return Number.isNaN(id) ? undefined : id
}
+function discoveryStatus(
+ game: ItchioGame,
+ source: ItchioGameSource
+): ItchioGameStatus {
+ if (source !== 'collection') return 'owned'
+ const isFree = !game.canBeBought || (game.minPrice ?? 0) === 0
+ return isFree ? 'free' : 'unowned'
+}
+
function gameToGameInfo(game: ItchioGame): ItchioGameInfo {
const cover = game.coverUrl ?? game.stillCoverUrl ?? ''
const platforms = game.platforms ?? {}
@@ -111,6 +166,191 @@ async function initItchioLibraryManager(): Promise<void> {
}
}
+async function fetchAllPages<T>(
+ client: ButlerdClient,
+ method: string,
+ params: Record<string, unknown>,
+ forceFresh: boolean
+): Promise<T[]> {
+ const items: T[] = []
+ let cursor: string | undefined
+ let pages = 0
+ let fresh = forceFresh
+
+ do {
+ let result = await client.call<PagedResult<T>>(method, {
+ ...params,
+ cursor,
+ fresh
+ })
+ if (pages === 0 && !fresh && result.stale) {
+ result = await client.call<PagedResult<T>>(method, {
+ ...params,
+ cursor,
+ fresh: true
+ })
+ }
+ items.push(...(result.items ?? []))
+ cursor = result.nextCursor
+ fresh = false
+ pages += 1
+ if (pages > MAX_PAGES) {
+ logError(
+ `${method} bailed out after ${MAX_PAGES} pages`,
+ LogPrefix.Itchio
+ )
+ break
+ }
+ } while (cursor)
+
+ return items
+}
+
+async function fetchOwnedKeyGames(
+ client: ButlerdClient,
+ profileId: number
+): Promise<ItchioGame[]> {
+ // Not Fetch.ProfileGames: that one lists games the user develops.
+ const keys = await fetchAllPages<DownloadKeyRecord>(
+ client,
+ 'Fetch.ProfileOwnedKeys',
+ { profileId },
+ true
+ )
+ return keys.flatMap((key) => (key.game ? [key.game] : []))
+}
+
+// Bundle games only get a download key when claimed, so they need their own source.
+async function fetchBundleGames(
+ client: ButlerdClient,
+ profileId: number
+): Promise<ItchioGame[]> {
+ // Best effort: older butler builds don't expose bundle ownership.
+ await client
+ .call('Fetch.ProfileBundleOwnerships', { profileId, fresh: true })
+ .catch((err: Error) => {
+ logDebug(
+ ['itch.io bundle ownership sync skipped:', err.message],
+ LogPrefix.Itchio
+ )
+ })
+
+ const bundleKeys = await fetchAllPages<ButlerdBundleKey>(
+ client,
+ 'Fetch.ProfileOwnedBundles',
+ { profileId },
+ true
+ )
+
+ const games: ItchioGame[] = []
+ const seenBundles = new Set<number>()
+ for (const bundleKey of bundleKeys) {
+ if (seenBundles.has(bundleKey.bundleId)) continue
+ seenBundles.add(bundleKey.bundleId)
+ const bundleGames = await fetchAllPages<ButlerdBundleGame>(
+ client,
+ 'Fetch.BundleGames',
+ { profileId, bundleId: bundleKey.bundleId },
+ false
+ )
+ for (const item of bundleGames) {
+ if (item.game) games.push(item.game)
+ }
+ }
+ return games
+}
+
+// Lutris-style discovery from a collection the user named "heroic"/"lutris".
+async function fetchCollectionGames(
+ client: ButlerdClient,
+ profileId: number
+): Promise<ItchioGame[]> {
+ const collections = await fetchAllPages<ButlerdCollection>(
+ client,
+ 'Fetch.ProfileCollections',
+ { profileId },
+ true
+ )
+ const discovery = collections.filter((collection) =>
+ DISCOVERY_COLLECTION_NAMES.includes(
+ (collection.title ?? '').trim().toLowerCase()
+ )
+ )
+
+ const games: ItchioGame[] = []
+ for (const collection of discovery) {
+ const collectionGames = await fetchAllPages<ButlerdCollectionGame>(
+ client,
+ 'Fetch.Collection.Games',
+ { profileId, collectionId: collection.id },
+ false
+ )
+ for (const item of collectionGames) {
+ if (item.game) games.push(item.game)
+ }
+ }
+ return games
+}
+
+function findCatalogCollection(
+ collections: ButlerdCollection[]
+): ButlerdCollection | undefined {
+ for (const name of DISCOVERY_COLLECTION_NAMES) {
+ const found = collections.find(
+ (collection) => (collection.title ?? '').trim().toLowerCase() === name
+ )
+ if (found) return found
+ }
+ return undefined
+}
+
+// Adds a game to the itch.io collection the library syncs, creating it if needed.
+export async function addGameToCatalog(appName: string): Promise<ExecResult> {
+ const gameId = gameIdFromAppName(appName)
+ const profileId = configStore.get_nodefault('profileId')
+
+ if (gameId === undefined) {
+ return { stdout: '', stderr: '', error: `Unknown itch.io app ${appName}` }
+ }
+ if (profileId === undefined) {
+ return { stdout: '', stderr: '', error: 'Not logged in to itch.io' }
+ }
+
+ try {
+ const client = await getClient()
+ const collections = await fetchAllPages<ButlerdCollection>(
+ client,
+ 'Fetch.ProfileCollections',
+ { profileId },
+ true
+ )
+ const catalog = findCatalogCollection(collections)
+
+ if (catalog) {
+ await client.call('Collections.AddGame', {
+ profileId,
+ collectionId: catalog.id,
+ gameId
+ })
+ } else {
+ await client.call('Collections.Create', {
+ profileId,
+ title: CATALOG_COLLECTION_NAME,
+ private: true,
+ gameId
+ })
+ }
+
+ return { stdout: 'done', stderr: '' }
+ } catch (err) {
+ logError(
+ ['itch.io add to catalog failed:', (err as Error).message],
+ LogPrefix.Itchio
+ )
+ return { stdout: '', stderr: '', error: (err as Error).message }
+ }
+}
+
async function refresh(): Promise<ExecResult | null> {
const profileId = configStore.get_nodefault('profileId')
if (profileId === undefined) {
@@ -122,38 +362,41 @@ async function refresh(): Promise<ExecResult | null> {
}
const client = await getClient()
- const games: ItchioGame[] = []
- let cursor: string | undefined
- let pages = 0
+ const ownedGames = await fetchOwnedKeyGames(client, profileId)
- // Fetch.ProfileOwnedKeys = games bought / claimed / gifted (NOT
- // Fetch.ProfileGames, which is developer-uploaded titles).
- do {
- const result = await client.call<FetchProfileOwnedKeysResult>(
- 'Fetch.ProfileOwnedKeys',
- { profileId, cursor, fresh: pages === 0 }
- )
- for (const item of result.items ?? []) {
- if (item.game) games.push(item.game)
- }
- cursor = result.nextCursor
- pages += 1
- if (pages > 50) {
- logError(
- 'itch.io Fetch.ProfileOwnedKeys bailed out after 50 pages',
+ // Best effort: a failing source must not empty the library.
+ const [bundleGames, collectionGames] = await Promise.all([
+ fetchBundleGames(client, profileId).catch((err: Error) => {
+ logWarning(
+ ['itch.io bundle games fetch failed:', err.message],
LogPrefix.Itchio
)
- break
- }
- } while (cursor)
+ return []
+ }),
+ fetchCollectionGames(client, profileId).catch((err: Error) => {
+ logWarning(
+ ['itch.io collection games fetch failed:', err.message],
+ LogPrefix.Itchio
+ )
+ return []
+ })
+ ])
+ const games: Array<{ game: ItchioGame; source: ItchioGameSource }> = [
+ ...ownedGames.map((game) => ({ game, source: 'owned' as const })),
+ ...bundleGames.map((game) => ({ game, source: 'bundle' as const })),
+ ...collectionGames.map((game) => ({ game, source: 'collection' as const }))
+ ]
// A game owned through several download keys (e.g. bought directly AND
// via a bundle) comes back once per key — dedupe by app_name so the
// library doesn't render duplicate entries.
const merged = new Map<string, ItchioGameInfo>()
- for (const game of games) {
+ for (const { game, source } of games) {
const info = gameToGameInfo(game)
if (merged.has(info.app_name)) continue
+ info.itchio_source = source
+ info.itchio_status = discoveryStatus(game, source)
+ info.installable = info.itchio_status !== 'unowned'
const existing = inMemoryLibrary.get(info.app_name)
if (existing?.is_installed) {
info.install = existing.install
@@ -174,7 +417,12 @@ async function refresh(): Promise<ExecResult | null> {
inMemoryLibrary.clear()
for (const [appName, info] of merged) inMemoryLibrary.set(appName, info)
libraryStore.set('library', Array.from(merged.values()))
- logInfo(`itch.io library refreshed: ${merged.size} games`, LogPrefix.Itchio)
+ logInfo(
+ `itch.io library refreshed: ${merged.size} games ` +
+ `(${ownedGames.length} owned keys, ${bundleGames.length} bundle games, ` +
+ `${collectionGames.length} collection games)`,
+ LogPrefix.Itchio
+ )
return { stdout: '', stderr: '' }
}
@@ -219,6 +467,53 @@ function pickUploadForPlatform(
return uploads.slice().sort((a, b) => b.size - a.size)[0]
}
+function markGameAsOwned(gameId: number): void {
+ const appName = `itchio-${gameId}`
+ const info = inMemoryLibrary.get(appName)
+ if (!info) return
+ info.itchio_source = 'owned'
+ info.itchio_status = 'owned'
+ info.installable = true
+ libraryStore.set('library', Array.from(inMemoryLibrary.values()))
+ sendFrontendMessage('pushGameToLibrary', info)
+}
+
+// Paid uploads stay hidden until the bundle's key is claimed; this claims it.
+async function fetchBundleOwnedUpload(
+ client: ButlerdClient,
+ gameId: number,
+ profileId: number | undefined,
+ installPlatform: InstallPlatform,
+ strict: boolean
+): Promise<ItchioUpload | undefined> {
+ if (profileId === undefined) return undefined
+
+ const ownership = await client
+ .call<FetchGameOwnershipResult>('Fetch.GameOwnership', {
+ profileId,
+ gameId
+ })
+ .catch((err: Error) => {
+ logDebug(
+ ['itch.io ownership lookup skipped:', err.message],
+ LogPrefix.Itchio
+ )
+ return undefined
+ })
+ if (!ownership?.owned || !ownership.bundleId) return undefined
+
+ const result = await client.call<InstallGetUploadsResult>(
+ 'Install.GetUploads',
+ { gameId, profileId }
+ )
+ markGameAsOwned(gameId)
+ const uploads = [
+ ...(result.uploads ?? []),
+ ...(result.incompatibleUploads ?? [])
+ ]
+ return pickUploadForPlatform(uploads, installPlatform, strict)
+}
+
async function fetchInstallInfo(
appName: string,
installPlatform: InstallPlatform,
@@ -241,11 +536,20 @@ async function fetchInstallInfo(
'Fetch.GameUploads',
{ gameId, profileId, fresh: true }
)
- const upload = pickUploadForPlatform(
+ let upload = pickUploadForPlatform(
result.uploads ?? [],
installPlatform,
strict
)
+ if (!upload) {
+ upload = await fetchBundleOwnedUpload(
+ client,
+ gameId,
+ profileId,
+ installPlatform,
+ strict
+ )
+ }
if (!upload) {
if (!strict) {
logError(
diff --git a/src/common/types.ts b/src/common/types.ts
index 7ea050d63..00e54811b 100644
--- a/src/common/types.ts
+++ b/src/common/types.ts
@@ -9,7 +9,11 @@ import {
LegendaryInstallInfo
} from './types/legendary'
import { NileInstallInfo, NileInstallPlatform } from './types/nile'
-import { ItchioInstallInfo } from './types/itchio'
+import {
+ ItchioGameSource,
+ ItchioGameStatus,
+ ItchioInstallInfo
+} from './types/itchio'
import type { DisplayUnits } from './format'
import {
ZoomInstallPlatform,
@@ -265,6 +269,8 @@ export interface GameInfo {
is_linux_native?: boolean
// True for Steam games that come from a Steam Family member's library
isFamilyShare?: boolean
+ itchio_source?: ItchioGameSource
+ itchio_status?: ItchioGameStatus
// Steam game pulled from the store
storeStatus?: 'removed' | 'delisted'
browserUrl?: string
diff --git a/src/common/types/ipc.ts b/src/common/types/ipc.ts
index 8ef45061b..0fcd20be1 100644
--- a/src/common/types/ipc.ts
+++ b/src/common/types/ipc.ts
@@ -292,6 +292,10 @@ interface AsyncIPCFunctions {
status: 'done' | 'failed'
user: ItchioUserData | undefined
}>
+ itchioAddGameToCatalog: (appName: string) => Promise<{
+ status: 'done' | 'failed'
+ error?: string
+ }>
getItchioOAuthUrl: () => Promise<ItchioOAuthLoginData>
authItchioOAuth: (data: ItchioOAuthCodeData) => Promise<{
status: 'done' | 'failed'
diff --git a/src/common/types/itchio.ts b/src/common/types/itchio.ts
index da3122328..27a7d9092 100644
--- a/src/common/types/itchio.ts
+++ b/src/common/types/itchio.ts
@@ -19,6 +19,15 @@ import type { LaunchOption } from 'common/types'
// itch.io upload platforms exposed by butlerd. Lower-case in the wire format.
type ItchioInstallPlatform = 'windows' | 'linux' | 'osx'
+// Where a library entry came from. Owned keys are games with a materialized
+// download key, bundles are owned but not claimed yet, collections are the
+// user's own lists (which may contain games they don't own).
+export type ItchioGameSource = 'owned' | 'bundle' | 'collection'
+
+// Whether Heroic can install the game: owned (key or bundle), free (no payment
+// needed) or unowned (paid and not owned).
+export type ItchioGameStatus = 'owned' | 'free' | 'unowned'
+
export interface ItchioUserData {
id: number
username: string
@@ -78,6 +87,9 @@ export interface ItchioGame {
// | 'osx'. Values can be booleans or arch strings ("all", "x64"); we
// treat any truthy value as supported.
platforms?: Partial<Record<ItchioInstallPlatform, unknown>>
+ // Price in cents; `canBeBought` is true when payments are accepted.
+ minPrice?: number
+ canBeBought?: boolean
// itch.io has no DLC concept; declared as a required empty array so
// the generic `InstallInfo['game'].owned_dlc` access in DownloadDialog
// narrows cleanly across all union variants.
diff --git a/src/frontend/components/UI/LibraryFilters/index.tsx b/src/frontend/components/UI/LibraryFilters/index.tsx
index bbf5afba4..c3ed9c449 100644
--- a/src/frontend/components/UI/LibraryFilters/index.tsx
+++ b/src/frontend/components/UI/LibraryFilters/index.tsx
@@ -37,6 +37,10 @@ export default function LibraryFilters() {
setPlatformsFilters,
showSupportOfflineOnly,
setShowSupportOfflineOnly,
+ showBundlesOnly,
+ setShowBundlesOnly,
+ showFreeOnly,
+ setShowFreeOnly,
showThirdPartyManagedOnly,
setShowThirdPartyManagedOnly,
showUpdatesOnly,
@@ -165,6 +169,28 @@ export default function LibraryFilters() {
defaultChecked: false,
show: true
},
+ {
+ key: 'bundles',
+ label: t('header.show_bundles_only', 'From bundles'),
+ checked: showBundlesOnly,
+ set: setShowBundlesOnly,
+ defaultChecked: false,
+ // Hidden only when there is nothing to filter and it is not active, so
+ // the library can never stay filtered by an option that is not rendered.
+ show:
+ showBundlesOnly ||
+ itchio.library.some((game) => game.itchio_source === 'bundle')
+ },
+ {
+ key: 'free',
+ label: t('header.show_free_only', 'Free'),
+ checked: showFreeOnly,
+ set: setShowFreeOnly,
+ defaultChecked: false,
+ show:
+ showFreeOnly ||
+ itchio.library.some((game) => game.itchio_status === 'free')
+ },
{
key: 'steamOwned',
label: t('header.show_steam_owned_only', 'Steam owned only'),
diff --git a/src/frontend/screens/Library/LibraryContext.tsx b/src/frontend/screens/Library/LibraryContext.tsx
index a86c14e14..6061d8f6e 100644
--- a/src/frontend/screens/Library/LibraryContext.tsx
+++ b/src/frontend/screens/Library/LibraryContext.tsx
@@ -37,6 +37,10 @@ const initialContext: LibraryContextType = {
setShowSupportOfflineOnly: () => null,
showThirdPartyManagedOnly: false,
setShowThirdPartyManagedOnly: () => null,
+ showBundlesOnly: false,
+ setShowBundlesOnly: () => null,
+ showFreeOnly: false,
+ setShowFreeOnly: () => null,
showUpdatesOnly: false,
setShowUpdatesOnly: () => null,
showSteamOwnedOnly: false,
diff --git a/src/frontend/screens/Library/components/GameCard/index.css b/src/frontend/screens/Library/components/GameCard/index.css
index 0828beb0e..c37959b44 100644
--- a/src/frontend/screens/Library/components/GameCard/index.css
+++ b/src/frontend/screens/Library/components/GameCard/index.css
@@ -255,6 +255,17 @@
-webkit-line-clamp: 4;
}
+.gameCard .itchioTags {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-2xs-fixed);
+ align-self: flex-start;
+}
+
+.gameCard .itchioStatus {
+ align-self: flex-start;
+}
+
.gameCard .runner {
display: inline-block;
font-family: var(--primary-font-family);
diff --git a/src/frontend/screens/Library/components/GameCard/index.tsx b/src/frontend/screens/Library/components/GameCard/index.tsx
index c28af3b7b..e053b198a 100644
--- a/src/frontend/screens/Library/components/GameCard/index.tsx
+++ b/src/frontend/screens/Library/components/GameCard/index.tsx
@@ -177,6 +177,13 @@ const GameCard = ({
const isInstallable =
gameInfo.installable === undefined || gameInfo.installable // If it's undefined we assume it's installable
+ const itchioStatus = gameInfo.itchio_status
+ // Owned games need no tag; only hint when the game is free or not owned.
+ const showItchioStatus =
+ !!gameInfo.itchio_source &&
+ (itchioStatus === 'free' || itchioStatus === 'unowned')
+ const itchioLocked = itchioStatus === 'unowned' && !isInstalled
+
const [progress, previousProgress] = hasProgress(appName, runner)
const units = useDisplayUnits((state) => state.units)
const installSizeBytes = gameInstallInfo?.install_size_bytes
@@ -205,6 +212,67 @@ const GameCard = ({
updateGame({ appName, runner, gameInfo })
}
+ const itchioBundle = gameInfo.itchio_source === 'bundle'
+
+ const itchioStatusLabel =
+ itchioStatus === 'free'
+ ? t('itchio.status.free', 'Free')
+ : itchioStatus === 'unowned'
+ ? t('itchio.status.unowned', 'Not owned')
+ : ''
+
+ function openGameDetails() {
+ if (itchioLocked) {
+ openItchioLockedModal()
+ return
+ }
+ void navigate(`/gamepage/${runner}/${appName}`, { state: { gameInfo } })
+ }
+
+ async function addItchioGameToCatalog() {
+ const result = await window.api.itchioAddGameToCatalog(appName)
+ if (result.status === 'done') {
+ showDialogModal({
+ title: t('itchio.catalog.added.title', 'Added to your catalog'),
+ message: t(
+ 'itchio.catalog.added.message',
+ 'The game was added to your "heroic" collection on itch.io.'
+ ),
+ buttons: [{ text: t2('box.ok', 'OK') }]
+ })
+ return
+ }
+ showDialogModal({
+ title: t('itchio.catalog.failed.title', 'Could not add to your catalog'),
+ message: result.error ?? '',
+ buttons: [{ text: t2('box.ok', 'OK') }]
+ })
+ }
+
+ function openItchioLockedModal() {
+ showDialogModal({
+ title: t('itchio.locked.title', 'Not available in Heroic'),
+ message: t(
+ 'itchio.locked.message',
+ "Heroic can't install this game because you don't own it and it isn't free on itch.io. You can add it to your itch.io catalog to keep it in this library."
+ ),
+ buttons: [
+ {
+ text: t('itchio.locked.add', 'Add to catalog'),
+ onClick: () => void addItchioGameToCatalog()
+ },
+ {
+ text: t('itchio.locked.open', 'Open on itch.io'),
+ onClick: () => {
+ if (gameInfo.store_url)
+ window.api.openExternalUrl(gameInfo.store_url)
+ }
+ },
+ { text: t2('box.cancel', 'Cancel') }
+ ]
+ })
+ }
+
const grid = forceCard || layout === 'grid'
const {
@@ -410,8 +478,7 @@ const GameCard = ({
{
// open the game page
label: t('button.details', 'Details'),
- onclick: () =>
- navigate(`/gamepage/${runner}/${appName}`, { state: { gameInfo } }),
+ onclick: openGameDetails,
show: true,
icon: <Icon glyph={ExternalLink} size="md" />
},
@@ -551,6 +618,11 @@ const GameCard = ({
<Link
to={`/gamepage/${runner}/${appName}`}
state={{ gameInfo }}
+ onClick={(event) => {
+ if (!itchioLocked) return
+ event.preventDefault()
+ openItchioLockedModal()
+ }}
style={
{ '--installing-effect': installingGrayscale } as CSSProperties
}
@@ -613,6 +685,23 @@ const GameCard = ({
>
<span>{title}</span>
</span>
+ {(itchioBundle || (showItchioStatus && itchioStatusLabel)) && (
+ <div className="itchioTags">
+ {itchioBundle && (
+ <Badge variant="neutral" className="itchioStatus">
+ {t('itchio.status.bundle', 'Bundle')}
+ </Badge>
+ )}
+ {showItchioStatus && itchioStatusLabel && (
+ <Badge
+ variant={itchioStatus === 'unowned' ? 'warning' : 'info'}
+ className="itchioStatus"
+ >
+ {itchioStatusLabel}
+ </Badge>
+ )}
+ </div>
+ )}
<span
className={classNames('runner', {
active: haveStatus,
diff --git a/src/frontend/screens/Library/index.tsx b/src/frontend/screens/Library/index.tsx
index 816adf622..58a9a4bbc 100644
--- a/src/frontend/screens/Library/index.tsx
+++ b/src/frontend/screens/Library/index.tsx
@@ -213,6 +213,23 @@ export default React.memo(function Library(): JSX.Element {
setShowSteamOwnedOnly(value)
}
+ // Provenance of itch.io games: bundles and free games are owned like any
+ // other, so these narrow the list instead of adding a store.
+ const [showBundlesOnly, setShowBundlesOnly] = useState(
+ JSON.parse(storage.getItem('show_bundles_only') || 'false')
+ )
+ const handleShowBundlesOnly = (value: boolean) => {
+ storage.setItem('show_bundles_only', JSON.stringify(value))
+ setShowBundlesOnly(value)
+ }
+ const [showFreeOnly, setShowFreeOnly] = useState(
+ JSON.parse(storage.getItem('show_free_only') || 'false')
+ )
+ const handleShowFreeOnly = (value: boolean) => {
+ storage.setItem('show_free_only', JSON.stringify(value))
+ setShowFreeOnly(value)
+ }
+
const [showCategories, setShowCategories] = useState(false)
const [showAlphabetFilter, setShowAlphabetFilter] = useState(
@@ -544,6 +561,14 @@ export default React.memo(function Library(): JSX.Element {
library = library.filter((game) => !game.isFamilyShare)
}
+ if (showBundlesOnly) {
+ library = library.filter((game) => game.itchio_source === 'bundle')
+ }
+
+ if (showFreeOnly) {
+ library = library.filter((game) => game.itchio_status === 'free')
+ }
+
if (!showNonAvailable) {
const nonAvailbleGames = storage.getItem('nonAvailableGames') || '[]'
const nonAvailbleGamesArray = JSON.parse(nonAvailbleGames)
@@ -618,6 +643,7 @@ export default React.memo(function Library(): JSX.Element {
gog.library,
amazon.library,
zoom.library,
+ itchio.library,
steam.library,
steam.enabled,
sideloadedLibrary,
@@ -635,6 +661,8 @@ export default React.memo(function Library(): JSX.Element {
showThirdPartyManagedOnly,
showUpdatesOnly,
showSteamOwnedOnly,
+ showBundlesOnly,
+ showFreeOnly,
gameUpdates
])
@@ -730,6 +758,10 @@ export default React.memo(function Library(): JSX.Element {
setShowUpdatesOnly: handleShowUpdatesOnly,
showSteamOwnedOnly,
setShowSteamOwnedOnly: handleShowSteamOwnedOnly,
+ showBundlesOnly,
+ setShowBundlesOnly: handleShowBundlesOnly,
+ showFreeOnly,
+ setShowFreeOnly: handleShowFreeOnly,
sortDescending,
sortInstalled,
handleAddGameButtonClick: () => handleModal('', 'sideload', null),
diff --git a/src/frontend/types.ts b/src/frontend/types.ts
index b8247f785..f77267b4c 100644
--- a/src/frontend/types.ts
+++ b/src/frontend/types.ts
@@ -284,6 +284,10 @@ export interface LibraryContextType {
setShowSupportOfflineOnly: (value: boolean) => void
showThirdPartyManagedOnly: boolean
setShowThirdPartyManagedOnly: (value: boolean) => void
+ showBundlesOnly: boolean
+ setShowBundlesOnly: (value: boolean) => void
+ showFreeOnly: boolean
+ setShowFreeOnly: (value: boolean) => void
showUpdatesOnly: boolean
setShowUpdatesOnly: (value: boolean) => void
handleAddGameButtonClick: () => void
diff --git a/src/preload/api/misc.ts b/src/preload/api/misc.ts
index 9b189c931..b5859ee6c 100644
--- a/src/preload/api/misc.ts
+++ b/src/preload/api/misc.ts
@@ -42,6 +42,7 @@ export const authAmazon = makeHandlerInvoker('authAmazon')
export const logoutAmazon = makeHandlerInvoker('logoutAmazon')
export const getItchioLoginData = makeHandlerInvoker('getItchioLoginData')
export const getItchioUserInfo = makeHandlerInvoker('getItchioUserInfo')
+export const itchioAddGameToCatalog = makeHandlerInvoker('itchioAddGameToCatalog')
export const authItchio = makeHandlerInvoker('authItchio')
export const getItchioOAuthUrl = makeHandlerInvoker('getItchioOAuthUrl')
export const authItchioOAuth = makeHandlerInvoker('authItchioOAuth')