Skip to content

[General] Images offline cache #1732

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions electron/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ const userInfo = join(legendaryConfigPath, 'user.json')
const heroicInstallPath = join(homedir(), 'Games', 'Heroic')
const heroicDefaultWinePrefix = join(homedir(), 'Games', 'Heroic', 'Prefixes')
const heroicAnticheatDataPath = join(heroicFolder, 'areweanticheatyet.json')
const imagesCachePath = join(heroicFolder, 'images-cache')

const { currentLogFile: currentLogFile, lastLogFile: lastLogFile } =
createNewLogFileAndClearOldOnces()
Expand Down Expand Up @@ -194,6 +195,7 @@ export {
heroicToolsPath,
heroicDefaultWinePrefix,
heroicAnticheatDataPath,
imagesCachePath,
userHome,
flatPakHome,
kofiPage,
Expand Down
34 changes: 34 additions & 0 deletions electron/images_cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { existsSync, createWriteStream, mkdirSync } from 'graceful-fs'
import { createHash } from 'crypto'
import { imagesCachePath } from './constants'
import { join } from 'path'
import axios from 'axios'
import { protocol } from 'electron'

export const initImagesCache = () => {
// make sure we have a folder to store the cache
if (!existsSync(imagesCachePath)) {
mkdirSync(imagesCachePath)
}

// use a fake protocol for images we want to cache
protocol.registerFileProtocol('imagecache', (request, callback) => {
callback({ path: getImageFromCache(request.url) })
})
}

const getImageFromCache = (url: string) => {
const realUrl = url.replace('imagecache://', '')
// digest of the image url for the file name
const digest = createHash('sha256').update(realUrl).digest('hex')
const cachePath = join(imagesCachePath, digest)

if (!existsSync(cachePath)) {
// if not found, download in the background
axios
.get(realUrl, { responseType: 'stream' })
.then((response) => response.data.pipe(createWriteStream(cachePath)))
}

return join(cachePath)
}
3 changes: 3 additions & 0 deletions electron/main.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { initImagesCache } from './images_cache'
import { downloadAntiCheatData } from './anticheat/utils'
import {
InstallParams,
Expand Down Expand Up @@ -328,6 +329,8 @@ if (!gotTheLock) {
app.whenReady().then(async () => {
const systemInfo = await getSystemInfo()

initImagesCache()

logInfo(
['Legendary location:', join(...Object.values(getLegendaryBin()))],
LogPrefix.Legendary
Expand Down
33 changes: 33 additions & 0 deletions src/components/UI/CachedImage/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import React, { useState } from 'react'

interface CachedImageProps {
src: string
fallback?: string
}

type Props = React.ImgHTMLAttributes<HTMLImageElement> & CachedImageProps

const CachedImage = (props: Props) => {
const [useCache, setUseCache] = useState(true)
const [useFallback, setUseFallback] = useState(false)

const onError = () => {
// if not cached, tried with the real
if (useCache) {
setUseCache(false)
} else {
// if not cached and can't access real, try with the fallback
if (props.fallback) {
setUseFallback(true)
setUseCache(true)
}
}
}

let src = useFallback ? props.fallback : props.src
src = useCache ? `imagecache://${src}` : src

return <img {...props} src={src} onError={onError} />
}

export default CachedImage
1 change: 1 addition & 0 deletions src/components/UI/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ export { default as ToggleSwitch } from './ToggleSwitch'
export { default as UpdateComponent } from './UpdateComponent'
export { default as SvgButton } from './SvgButton'
export { default as ControllerHints } from './ControllerHints'
export { default as CachedImage } from './CachedImage'
19 changes: 16 additions & 3 deletions src/screens/Game/GamePicture/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import React from 'react'
import { CachedImage } from 'src/components/UI'

import './index.css'
import fallbackImage from 'src/assets/fallback-image.jpg'

type Props = {
art_square: string
store: string
Expand All @@ -10,15 +13,25 @@ function GamePicture({ art_square, store }: Props) {
function getImageFormatting() {
if (art_square === 'fallback') return fallbackImage
if (store === 'legendary') {
return `${art_square}?h=800&resize=1&w=600`
return [
`${art_square}?h=800&resize=1&w=600`,
`${art_square}?h=400&resize=1&w=300`
]
} else {
return art_square
return [art_square, '']
}
}

const [src, fallback] = getImageFormatting()

return (
<div className="gamePicture">
<img alt="cover-art" src={getImageFormatting()} className="gameImg" />
<CachedImage
alt="cover-art"
className="gameImg"
src={src}
fallback={fallback}
/>
</div>
)
}
Expand Down
6 changes: 3 additions & 3 deletions src/screens/Library/components/GameCard/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { useTranslation } from 'react-i18next'
import ContextProvider from 'src/state/ContextProvider'
import fallbackImage from 'src/assets/fallback-image.jpg'
import { uninstall, updateGame } from 'src/helpers/library'
import { SvgButton } from 'src/components/UI'
import { CachedImage, SvgButton } from 'src/components/UI'
import ContextMenu, { Item } from '../ContextMenu'
import { hasProgress } from 'src/hooks/hasProgress'

Expand Down Expand Up @@ -337,9 +337,9 @@ const GameCard = ({
}
>
{showStoreLogos()}
<img src={imageSrc} className={imgClasses} alt="cover" />
<CachedImage src={imageSrc} className={imgClasses} alt="cover" />
{logo && (
<img
<CachedImage
alt="logo"
src={`${logo}?h=400&resize=1&w=300`}
className={logoClasses}
Expand Down