MASV Web Downloader
For browser-based integrations where you want to download files from MASV using your own web app, you can use the MASV Web Downloader. It simplifies file downloading by taking care of the complexities of dealing with the MASV API while giving you the flexibility of designing your own file picker and integration workflows.
Setting up
First, install the MASV Web Downloader in your project:
yarn add @masvio/downloader
Adding the Web Downloader to Your Web App
1. Instantiate the Downloader
Each Downloader
instance is initialized with a MASV download link and a password, if required by the link owner.
Each download attempt requires a new Downloader
instance.
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 must be attached before download start to monitor these events.
You can find definitions of all Downloader
events and statuses in the Interfaces section.
downloader.on(Downloader.States.Downloading, () => {
console.log("State changed: Downloading");
})
downloader.on(Downloader.States.Paused, () => {
console.log("State changed: Paused");
})
downloader.on(Downloader.States.Cancelled, () => {
console.log("State changed: Cancelled");
})
downloader.on(Downloader.DownloaderEvents.Progress, ({ data }) => {
console.log("Received Downloader progress update. Stats:", data.performanceStats);
});
downloader.on(Downloader.States.Terminated, () => {
console.log("State changed: Terminated");
})
downloader.on(Downloader.DownloaderEvents.Finished, () => {
console.log("Download successful!");
});
downloader.on(Downloader.DownloaderEvents.Error, ({ data }) => {
console.log("Download failed");
console.error(data.errorMsg);
})
downloader.on(Downloader.DownloaderEvents.PartialFinished, ({ data }) => {
console.log("Partial finish. Failed files:", data.failedFiles);
})
downloader.on(Downloader.DownloaderEvents.ParentDirectoryCreated, ({ data }) => {
console.log(`Successfully created the destination folder: ${data.parentDirectoryName}`);
})
3. Get a Directory Handle
The showDirectoryPicker()
method from the Window interface allows selecting a directory for downloads. The method returns a FileSystemDirectoryHandle
object.
Note that browsers do not allow end users to choose system folders (Downloads, Documents, Desktop, etc.) due to security concerns, but nested folders are allowed.
It is recommended for end users to create a dedicated download folder.
Please refer to the MDN Web Docs on showDirectoryPicker() for more information.
<button id="download">Download</button>
let directoryHandle;
const downloadButton = document.getElementById('download');
downloadButton.addEventListener("click", async () => {
directoryHandle = await showDirectoryPicker({
id: "masv-web-downloader",
mode: "readwrite",
startIn: "downloads",
});
});
4. Start Download
To download all contents from the MASV download link associated with the downloader instance, call the start
method with a FileSystemDirectoryHandle
object.
await downloader.start(directoryHandle);
API Reference
Constructor
new Downloader(masvLink, linkPassword, userToken, apiBaseURL, chunkSize);
Param | Type | Description | Required |
---|---|---|---|
masvLink | string | The download link of the package being downloaded. This is obtained from the package download page. After it is instantiated, the downloader can download contents from this package only. A new downloader must be instantiated for each download attempt (not including pause and resume). | Yes. |
linkPassword | string | The password for the MASV download link. | Yes, but only if a password has been set for the download link. |
userToken | string | A MASV user token used for download links that require user authentication. | Yes, but only if user authentication is required for the download link. |
apiBaseURL | string | The base URL of the MASV API. Default: https://api.massive.app . |
No. |
chunkSize | number | The size of each download chunk. Default: 104857600 (100 MiB). | No. |
Methods
initialize
Required for bootstrapping the Downloader instance. Implicitly calls loadFiles.
await downloader.initialize();
start
Start the download or resume a paused download.
await downloader.start(directoryHandle, fileList);
Param | Type | Description | Required |
---|---|---|---|
directoryHandle | FileSystemDirectoryHandle |
The directory where the package contents are being downloaded to. | Yes. |
fileList | BaseFile[] |
An array of files from the package download link that the downloader is instantiated with. If no fileList is provided, all files from the download link will be downloaded. | No. |
pause
Pause the download.
downloader.pause();
retry
Resume the download and retry any failed files. Only valid if the Downloader instance is currently in the PartialFinished state.
await downloader.retry();
cancel
Cancel the download. The download cannot perform any downloads after cancel.
downloader.cancel();
terminate
Terminate the downloader and all it’s workers. The downloader cannot perform any other actions after termination.
downloader.terminate();
loadFiles
Retrieve all files from the download link the Downloader is instantiated with. An array of files that fit the BaseFile
interface is returned.
const files:BaseFile[] = await downloader.loadFiles();
Interfaces
BaseFile
Param | Type | Description |
---|---|---|
id | File | ID string that uniquely identifies each file. |
kind | string | Possible values: [file , directory , metadata , zip_windows , zip_mac ] |
last_modified | string | |
name | string | |
path | string | The relative file path. Used to preserve folder structures. Might be undefined. |
size | number | The size of the file in bytes. Might be undefined. |
virus_detected | boolean | Indicates whether a virus has been detected. Files with this field set to true will not be downloaded and the downloader will emit a FileErrored event. |
completed | boolean | Indicates that the file is ready for download. Only relevant for MASV-generated zip files. |
EventPayloads
Property | Type | Description |
---|---|---|
event | string | One of the possible events listed below |
data | object | An object representing data relevant to the event |
time | number | A unix timestamp indicating when the event was fired |
target | object | The module of the uploader that fired the original event |
DownloaderEvents
Name | Event | Data | Description |
---|---|---|---|
Abort | download:abort | fileId: string ; |
The download has been aborted after pausing or cancelling the transfer. |
Error | download:error | performanceStats: PerformanceResults ; error: Error ; |
An error has occurred with the downloader. The download cannot continue. |
FileDownloaded | download:file-downloaded | fileId: string ; |
A file has been successfully downloaded. |
FileErrored | download:file-errored | fileId: string ; error: Error ; |
An error has occurred with the download of a specific file. Errored files are automatically skipped, allowing the download to continue. |
FileQueued | download:file-queued | fileId: string ; |
A file has be queued for the downloader. |
Finished | download:finish | performanceStats: PerformanceResults ; |
All files have been successfully downloaded. |
ParentDirectoryCreated | download:parent-directory-created | parentDirectoryName: string ; |
A parent directory named after the package has been successfully created. This is done before any files are downloaded. |
PartialFinished | download:partial-finish | performanceStats: PerformanceResults ; failedFiles: BaseFile[] ; |
An error has occurred with one or more files in the download. The affected files were skipped and the rest of the download has been completed successfully. Errored files can be retried. |
Progress | download:progress | performanceStats: PerformanceResults ; |
Download progress report. |
Retry | download:retry | performanceStats: PerformanceResults ; error: Error ; |
The downloader is retrying a request, usually due to a network issue. |
PerformanceResults
Property | Type | Description |
---|---|---|
duration | number | Milliseconds elapsed since the download started. |
speed | number | Average download speed calculated using the total progress and duration. Measured in bits per second. |
instant | number | Most recent download speed measurement. Measured in bits per second. |
moving | number | Download speed over a recent period, or a short-term average. Measured in bits per second. |
total | number | Size of the entire download. Measured in bytes. |
progress | number | Total bytes processed from network requests. Might decrease after pausing since unwritten data will be discarded and some progress will be lost. |
chunkProgress | number | Total bytes written to disk. Might decrease when a file fails and partial chunk progress is lost. |
fileProgress | number | Total bytes from fully downloaded files. |
totalFiles | number | Number of files included in the transfer. |
finalizedFiles | number | Number of successfully downloaded files. |