Skip to content

Add LocalStorage cloud support #3106

Open

Description

@vanlooverenkoen

Is your feature request related to a problem? Please describe.
Right now it is possible to save files on AWS & GCP but if you want to save files on disk (during development or on a Synology NAS or Docker) it is quite hard to do right now because of missing documentation.

Better documentation is tracked here #3081

But having native support for LocalStorage that saves to disk would be very nice!

Describe the solution you'd like
Exposing this the the ServerPod implementation directly so we don't need to write our own implementation

Describe alternatives you've considered
I created one myself (with the help of @Isakdl)
#3081 (comment)

  1. Change the max request size to the size of your file
    I set it to 200mb because I don't know what the file size will be for now
    You change this in config/development.yaml and the other configuration files
maxRequestSize: 200000000
  1. Create a LocalStorage class that extends CloudDatabase
import 'dart:io';
import 'dart:typed_data';

import 'package:path/path.dart';
import 'package:app_server/src/generated/protocol.dart';
import 'package:serverpod/serverpod.dart';

enum LocalStorageId {
  public('public'),
  private('private');

  final String storageId;

  const LocalStorageId(
    this.storageId,
  );
}

class LocalStorage extends DatabaseCloudStorage {
  final String? publicStorageUrl;
  final String pathPrefix;

  LocalStorage({
    required LocalStorageId storageId,
    required this.pathPrefix,
    this.publicStorageUrl,
  }) : super(storageId.storageId);

  File _getFileByPath(String path) {
    final fileName = basename(path);
    final parentDirectoryPath = dirname(path);
    final directoryPath = join(pathPrefix, parentDirectoryPath);
    final directory = Directory(directoryPath);
    if (!directory.existsSync()) {
      directory.createSync(recursive: true);
    }
    return File(join(directoryPath, fileName));
  }

  @override
  Future<void> deleteFile({
    required Session session,
    required String path,
  }) async {
    final file = _getFileByPath(path);
    if (!file.existsSync()) {
      throw LocalizedError(
        message: LocalizedMessage(en: 'File not found'),
        statusCode: 404,
      );
    }
    file.deleteSync();
  }

  @override
  Future<bool> fileExists({
    required Session session,
    required String path,
  }) async {
    print('Checking if file exists at $path');
    final file = _getFileByPath(path);
    return file.existsSync();
  }

  @override
  Future<Uri?> getPublicUrl({
    required Session session,
    required String path,
  }) async {
    final prefix = publicStorageUrl;
    if (prefix == null) {
      throw LocalizedError(
        message: LocalizedMessage(en: 'Public storage URL is allowed for LocalStorage with id $storageId'),
        statusCode: 400,
      );
    }

    final file = _getFileByPath(path);
    if (!file.existsSync()) {
      throw LocalizedError(
        message: LocalizedMessage(
          en: 'File not found',
        ),
        statusCode: 404,
      );
    }
    if (prefix.startsWith('http')) {
      return Uri.parse('$prefix$path');
    }
    return Uri.file('$prefix$path');
  }

  @override
  Future<ByteData?> retrieveFile({
    required Session session,
    required String path,
  }) async {
    final file = _getFileByPath(path);
    if (!file.existsSync()) {
      throw LocalizedError(
        message: LocalizedMessage(en: 'File not found'),
        statusCode: 404,
      );
    }
    final data = file.readAsBytesSync();
    return ByteData.view(data.buffer);
  }

  @override
  Future<void> storeFile({
    required Session session,
    required String path,
    required ByteData byteData,
    DateTime? expiration,
    bool verified = true,
  }) async {
    final file = _getFileByPath(path);
    final data = byteData.buffer.asUint8List();
    file.writeAsBytesSync(data);
  }

  @override
  Future<bool> verifyDirectFileUpload({required Session session, required String path}) async {
    final file = _getFileByPath(path);
    return file.existsSync();
  }
}
  1. Register the LocalStorage on your server

I am saving it in my repository (in the root under storage)

    pod.addCloudStorage(LocalStorage(
      publicStorageUrl: publicStorageUrl,
      storageId: LocalStorageId.public,
      pathPrefix: join(Directory.current.path, '..', 'storage', 'private'),
    ));
    pod.addCloudStorage(LocalStorage(
      storageId: LocalStorageId.private,
      pathPrefix: join(Directory.current.path, '..', 'storage', 'public'),
    ));

The reason I have not created a PR is because a this might all change in the future so first we need beter documenation on how to create custom cloud storage

Activity

  1. changed the title [-]Add LocalStorage cloud suppot[/-] [+]Add LocalStorage cloud suppoet[/+] on Jan 8, 2025
  2. changed the title [-]Add LocalStorage cloud suppoet[/-] [+]Add LocalStorage cloud support[/+] on Jan 8, 2025
  3. added
    area: storage
    enhancement
    on Jan 8, 2025
  4. iampopal commented on Jan 8, 2025

    @iampopal

    This will be awesome

  5. vanlooverenkoen commented on Jan 8, 2025

    @vanlooverenkoen
    ContributorAuthor

    @iampopal make sure to upvote as well, becuase it is easier to track upvotes than comments ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: storageenhancement

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions