Skip to content
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

Add background fetch functionality. #235

Open
wants to merge 1 commit into
base: 1.3.x
Choose a base branch
from
Open
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
7 changes: 7 additions & 0 deletions assets/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@
"fetch": "eager",
"enabled": true
},
"backgroundfetch": {
"main": "src/backgroundfetch_controller.js",
"name": "pwa/backgroundfetch",
"webpackMode": "eager",
"fetch": "eager",
"enabled": true
},
"backgroundsync-form": {
"main": "src/backgroundsync-form_controller.js",
"name": "pwa/backgroundsync-form",
Expand Down
61 changes: 61 additions & 0 deletions assets/src/backgroundfetch_controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
'use strict';

import { Controller } from '@hotwired/stimulus';

/* stimulusFetch: 'lazy' */
export default class extends Controller {
download = async ({params}) => {
const { id, requests, title, icons, downloadTotal } = params;
if (!requests) {
return;
}
const processId = id || self.crypto.randomUUID();
await this.fetch(processId, requests, {
title,
icons,
downloadTotal
});
}

fetch = async (id, requests, options) => {
try {
const registration = await navigator.serviceWorker.ready;
const bgFetch = await registration.backgroundFetch.fetch(id, requests, options);
bgFetch.addEventListener('progress', () => this.dispatchStatus(bgFetch));

} catch (error) {
this.dispatchEvent('error', { error });
}
}

status = async () => {
const registration = await navigator.serviceWorker.ready;
const ids = await registration.backgroundFetch.getIds();
this.dispatchEvent('ids', ids);
const promises = ids.map(async (id) => {
const bgFetch = await registration.backgroundFetch.get(id);
if (!bgFetch) {
return;
}
bgFetch.addEventListener('progress', () => this.dispatchStatus(bgFetch));
});
await Promise.all(promises);
}

dispatchStatus = (bgFetch) => {
this.dispatchEvent('status', {
id: bgFetch.id,
uploadTotal: bgFetch.uploadTotal,
uploaded: bgFetch.uploaded,
downloadTotal: bgFetch.downloadTotal,
downloaded: bgFetch.downloaded,
result: bgFetch.result,
failureReason: bgFetch.failureReason,
recordsAvailable: bgFetch.recordsAvailable,
});
}

dispatchEvent = (name, payload) => {
this.dispatch(name, { detail: payload });
}
}
Empty file modified link
100644 → 100755
Empty file.
1 change: 1 addition & 0 deletions src/CachingStrategy/AssetCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Symfony\Component\Serializer\Encoder\JsonEncode;
use Symfony\Component\Serializer\SerializerInterface;
use function count;
use function sprintf;
use const JSON_PRETTY_PRINT;
use const JSON_THROW_ON_ERROR;
use const JSON_UNESCAPED_SLASHES;
Expand Down
1 change: 1 addition & 0 deletions src/CachingStrategy/ImageCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use SpomkyLabs\PwaBundle\Service\CanLogInterface;
use Symfony\Component\AssetMapper\Path\PublicAssetsPathResolverInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use function sprintf;

final class ImageCache implements HasCacheStrategiesInterface, CanLogInterface
{
Expand Down
1 change: 1 addition & 0 deletions src/CachingStrategy/ManifestCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use SpomkyLabs\PwaBundle\Dto\Workbox;
use SpomkyLabs\PwaBundle\Service\CanLogInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use function sprintf;

final class ManifestCache implements HasCacheStrategiesInterface, CanLogInterface
{
Expand Down
1 change: 1 addition & 0 deletions src/CachingStrategy/PreloadUrlsGeneratorManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use SpomkyLabs\PwaBundle\Service\CanLogInterface;
use Symfony\Component\DependencyInjection\Attribute\TaggedIterator;
use function array_key_exists;
use function sprintf;

final class PreloadUrlsGeneratorManager implements CanLogInterface
{
Expand Down
1 change: 1 addition & 0 deletions src/CachingStrategy/ResourceCaches.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Symfony\Component\Serializer\Encoder\JsonEncode;
use Symfony\Component\Serializer\SerializerInterface;
use function count;
use function sprintf;
use const JSON_PRETTY_PRINT;
use const JSON_THROW_ON_ERROR;
use const JSON_UNESCAPED_SLASHES;
Expand Down
1 change: 1 addition & 0 deletions src/CachingStrategy/WorkboxCacheStrategy.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use SpomkyLabs\PwaBundle\WorkboxPlugin\CachePluginInterface;
use function in_array;
use function sprintf;
use const JSON_PRETTY_PRINT;
use const JSON_THROW_ON_ERROR;
use const JSON_UNESCAPED_SLASHES;
Expand Down
1 change: 1 addition & 0 deletions src/Command/CreateIconsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Symfony\Component\Mime\MimeTypes;
use Symfony\Component\Yaml\Yaml;
use function is_string;
use function sprintf;

#[AsCommand(name: 'pwa:create:icons', description: 'Generate icons for your PWA')]
final class CreateIconsCommand extends Command
Expand Down
1 change: 1 addition & 0 deletions src/Command/CreateScreenshotCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use function assert;
use function is_int;
use function is_string;
use function sprintf;

#[AsCommand(
name: 'pwa:create:screenshot',
Expand Down
1 change: 1 addition & 0 deletions src/CompilerPass/PreloadUrlCompilerPass.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Throwable;
use function array_key_exists;
use function is_string;
use function sprintf;

/**
* @internal
Expand Down
27 changes: 27 additions & 0 deletions src/Dto/BackgroundFetch.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

namespace SpomkyLabs\PwaBundle\Dto;

use Symfony\Component\Serializer\Attribute\SerializedName;

final class BackgroundFetch
{
public bool $enabled;

#[SerializedName('cache_name')]
public string $cacheName;

#[SerializedName('progress_url')]
public null|Url $progressUrl = null;

#[SerializedName('success_url')]
public null|Url $successUrl = null;

#[SerializedName('success_message')]
public null|string $successMessage = null;

#[SerializedName('failure_message')]
public null|string $failureMessage = null;
}
3 changes: 3 additions & 0 deletions src/Dto/ServiceWorker.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,7 @@ final class ServiceWorker
public bool $skipWaiting = false;

public Workbox $workbox;

#[SerializedName('background_fetch')]
public null|BackgroundFetch $backgroundFetch = null;
}
1 change: 1 addition & 0 deletions src/ImageProcessor/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use InvalidArgumentException;
use Stringable;
use function sprintf;

final readonly class Configuration implements Stringable
{
Expand Down
9 changes: 4 additions & 5 deletions src/ImageProcessor/GDImageProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,10 @@ private function createMainImage(string $image, Configuration $configuration): G
}

/*if ($configuration->width === $configuration->height) {
$mainImage = imagescale($mainImage, $configuration->width, $configuration->height);
assert($mainImage !== false);

return $mainImage;
}*/
* $mainImage = imagescale($mainImage, $configuration->width, $configuration->height);
* assert($mainImage !== false);
* return $mainImage;
* }*/

$srcWidth = imagesx($mainImage);
$srcHeight = imagesy($mainImage);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use SpomkyLabs\PwaBundle\Service\CanLogInterface;
use function sprintf;

final class DestinationMatchCallbackHandler implements MatchCallbackHandlerInterface, CanLogInterface
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use SpomkyLabs\PwaBundle\Service\CanLogInterface;
use function sprintf;

final class ExactPathnameMatchCallbackHandler implements MatchCallbackHandlerInterface, CanLogInterface
{
Expand Down
1 change: 1 addition & 0 deletions src/MatchCallbackHandler/OriginMatchCallbackHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use SpomkyLabs\PwaBundle\Service\CanLogInterface;
use function sprintf;

final class OriginMatchCallbackHandler implements MatchCallbackHandlerInterface, CanLogInterface
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use SpomkyLabs\PwaBundle\Service\CanLogInterface;
use function sprintf;

final class PathnameEndsWithMatchCallbackHandler implements MatchCallbackHandlerInterface, CanLogInterface
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use SpomkyLabs\PwaBundle\Service\CanLogInterface;
use function sprintf;

final class PathnameStartsWithMatchCallbackHandler implements MatchCallbackHandlerInterface, CanLogInterface
{
Expand Down
1 change: 1 addition & 0 deletions src/MatchCallbackHandler/RouteMatchCallbackHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Psr\Log\NullLogger;
use SpomkyLabs\PwaBundle\Service\CanLogInterface;
use Symfony\Component\Routing\RouterInterface;
use function sprintf;

final class RouteMatchCallbackHandler implements MatchCallbackHandlerInterface, CanLogInterface
{
Expand Down
1 change: 1 addition & 0 deletions src/Normalizer/ScreenshotNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use function assert;
use function sprintf;

final class ScreenshotNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
Expand Down
22 changes: 22 additions & 0 deletions src/Resources/config/definition/service_worker.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,28 @@
->defaultTrue()
->info('Whether the service worker should use the cache.')
->end()
->arrayNode('background_fetch')
->canBeEnabled()
->children()
->scalarNode('cache_name')
->isRequired()
->info('The name of the cache where files should be saved.')
->example(['downloads'])
->end()
->append(getUrlNode('progress_url', 'The URL of the progress page.'))
->append(getUrlNode('success_url', 'The URL of the success page.'))
->scalarNode('success_message')
->info('The message to display on success. This message can be translated.')
->defaultNull()
->example(['The download is complete.'])
->end()
->scalarNode('failure_message')
->info('The message to display on success. This message can be translated.')
->defaultNull()
->example(['The download is complete.'])
->end()
->end()
->end()
->arrayNode('workbox')
->info('The configuration of the workbox.')
->canBeDisabled()
Expand Down
1 change: 1 addition & 0 deletions src/Service/FaviconsCompiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
use function assert;
use function sprintf;
use const PHP_EOL;

final class FaviconsCompiler implements FileCompilerInterface, CanLogInterface
Expand Down
1 change: 1 addition & 0 deletions src/Service/IconResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use function assert;
use function count;
use function is_array;
use function sprintf;

final readonly class IconResolver
{
Expand Down
1 change: 1 addition & 0 deletions src/Service/ServiceWorkerCompiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use function in_array;
use function is_array;
use function is_string;
use function sprintf;

final class ServiceWorkerCompiler implements FileCompilerInterface, CanLogInterface
{
Expand Down
1 change: 1 addition & 0 deletions src/ServiceWorkerRule/AppendCacheStrategies.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use SpomkyLabs\PwaBundle\CachingStrategy\HasCacheStrategiesInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\DependencyInjection\Attribute\TaggedIterator;
use function sprintf;
use const PHP_EOL;

final readonly class AppendCacheStrategies implements ServiceWorkerRuleInterface
Expand Down
Loading
Loading