# MASV Web Downloader

## About

MASV Web Downloader uses the power of your web browser to download files of any size to a destination folder. It preserves folder structures and even supports empty folders.

**Note**: This package relies on [showDirectoryPicker()](https://developer.mozilla.org/en-US/docs/Web/API/Window/showDirectoryPicker), a Web API method that is currently only supported by Chromium-based browsers like Chrome or Edge. It does **not** work on Firefox or Safari.

## Installation

```bash
yarn add @masvio/downloader
```

## Usage

### Downloading Files

#### 1. Instantiate the Downloader

Each downloader is initialized with a [MASV download link](https://developer.massive.io/masv-api/links/). A password may be required by the link owner.

Each download attempt requires a new `Downloader` instance.

```javascript
import { Downloader } from "@masvio/downloader";

const downloader = new Downloader(masvLink, linkPassword);

await downloader.initialize();
```

#### 2. Monitor Downloader Events

The `Downloader` emits statuses and events throughout the download process. Callback methods can be attached beforehand to monitor these events.

```javascript
downloader.on(Downloader.States.Paused, () => {
  console.log("Received Downloader Status: Paused");
});

downloader.on(Downloader.States.Terminated, () => {
  console.log("Received Downloader Status: Terminated");
});

downloader.on(Downloader.DownloaderEvents.Progress, ({ data }) => {
  console.log("Received Downloader Event: Finished");
  console.log("Received data:", data.performanceStats);
});

downloader.on(Downloader.DownloaderEvents.Error, ({ data }) => {
  console.log("Received Downloader Event: Error");
  console.log("Received data:", data.performanceStats, data.error);
});
```

#### 3. Retrieve the Download Directory

The `showDirectoryPicker()` method from Window interface allows users to select a directory for downloads. The method returns a `FileSystemDirectoryHandle` object, which is used for the download process.

Please refer to the [MDN Web Docs on showDirectoryPicker()](https://developer.mozilla.org/en-US/docs/Web/API/Window/showDirectoryPicker) for more information.

HTML:

```html
<button id="download">Download</button>
```

JavaScript:

```javascript
const downloadButton = document.getElementById("download");
downloadButton.addEventListener("click", async () => {
  directoryHandle = await showDirectoryPicker({
    id: "MASV",
    mode: "readwrite",
    startIn: "downloads",
  });
});
```

#### 4. Start Download

To download all contents from the MASV download link, call the `start` method with a `FileSystemDirectoryHandle` object.

```javascript
await downloader.start(directoryHandle);
```

---

> For more information, visit the [MASV Developer Documentation page](https://developer.massive.io/).
