---
sidebar_position: 0
---

# cache

The `sos.offline.cache` API groups together methods used to download and save arbitrary files, which can be accessed even if the device is offline.

> Please refer to difference between `sos.offline.cache` and `sos.fileSystem` APIs in our [documentation](http://localhost:3000/sdk/sos/offline/).

:::warning
Emulator has certain limitations while handling offline files. [Read more here](https://docs.signageos.io/hc/en-us/articles/4405238997138)
:::

## Methods

### decompressFile()

The `decompressFile()` decompresses the file specified by `uid` into a new file specified by `destinationUid`.

```ts expandable
decompressFile(uid: string, destinationUid: string, method: 'zip'): Promise<void>;
```

#### Params

| Name             | Type     | Required         | Description                                                          |
|------------------|----------|------------------|----------------------------------------------------------------------|
| `uid`            | `string` |  <div>Yes</div>  | Unique file identifier of a previously downloaded ZIP file.          |
| `destinationUid` | `string` |  <div>Yes</div>  | Unique directory identifier (prefix of file) to extract ZIP file.    |
| `method`         | `"zip"`  |  <div>Yes</div>  | The decompression method to use. Currently, only 'zip' is supported. |

#### Return value

A promise that resolves when the file is decompressed.

#### Possible errors


- Error If the uid does not exist.
- Error If the destinationUid is not a valid string.
- Error If the method is not supported.

#### Example

```ts
// Save the ZIP file
await sos.offline.cache.saveFile('example-zip-file.zip', 'https://example.com/path/to/your/file.zip');

// Decompress the ZIP file into a directory
await sos.offline.cache.decompressFile('example-zip-file.zip', 'extracted-files/', 'zip');
	.then(() => { console.log('ZIP file extracted'); })
	.catch((error) => { console.error(error); });
```

:::note[GitHub Example]

- [ Example Applet with Offline ZIP Decompression](https://github.com/signageos/applet-examples/blob/master/examples/content-js-api/offline-zip-decompress)

:::

<Separator />

### deleteContent()

<Admonition type="info" icon="" title="">
  Learn more about using this API [here](https://developers.signageos.io/docs/sos-guides/key-value-storage)
</Admonition>

The `deleteContent()` method removes the value specified by `uid` key from the cache storage.

```ts expandable
deleteContent(uid: string): Promise<void>;
```

#### Params

| Name  | Type     | Required         | Description                                     |
|-------|----------|------------------|-------------------------------------------------|
| `uid` | `string` |  <div>Yes</div>  | Unique identifier of the content to be deleted. |

#### Return value

A promise that resolves when the content is deleted.

#### Possible errors


- Error If the uid does not exist.
- Error If the uid is not a valid string.
- Error If any other error occurs during deletion.

#### Example

```ts
//Store
sos.offline.cache.saveContent('ApplicationSecret', '123SuperSecretHash')
.then(() => {
    //Content was successfully saved, retrieve it.
    return sos.offline.cache.loadContent('ApplicationSecret');
})
.then((content) => {
    console.log('Loaded', content); // print 123SuperSecretHash

    // Let's delete the content now
    return sos.offline.cache.deleteContent('ApplicationSecret')
})
.then(() => {
    console.log("Deleted");
})
.catch((error) => { console.error(error); });
```

<Separator />

### deleteFile()

The `deleteFile()` method removes the file specified by `uid` from cache storage.

```ts expandable
deleteFile(uid: string): Promise<void>;
```

#### Params

| Name  | Type     | Required         | Description                                  |
|-------|----------|------------------|----------------------------------------------|
| `uid` | `string` |  <div>Yes</div>  | Unique identifier of the file to be deleted. |

#### Return value

A promise that resolves when the file is deleted.

#### Possible errors


- Error If the uid is not a valid string.
- Error If the uid is not found in the cache.

#### Example

```ts
// Save a file
await sos.offline.cache.saveFile('example-file.mp4', 'https://example.com/path/to/your/file.mp4');
// Later delete the file
await sos.offline.cache.deleteFile('example-file.mp4');
```

<Separator />

### getChecksumFile()

The `getChecksumFile()` computes a checksum of the file specified by `uid`.

```ts expandable
getChecksumFile(uid: string, hashType: HashAlgorithm): Promise<string>;
// show-more
/**
 * Represents the supported hash algorithms by Core Apps.
 */
type HashAlgorithm = 'md5' | 'crc32' | AnyString;

type AnyString = string & {};

```

#### Params

| Name       | Type            | Required         | Description                                                               |
|------------|-----------------|------------------|---------------------------------------------------------------------------|
| `uid`      | `string`        |  <div>Yes</div>  | Unique file identifier of a previously downloaded file.                   |
| `hashType` | `HashAlgorithm` |  <div>Yes</div>  | The hashing algorithm to use. Supported algorithms are `md5` and `crc32`. |

#### Return value

A promise that resolves to the computed checksum of the file.

#### Possible errors


- Error If the uid does not exist.
- Error If the hashing algorithm is not supported.

#### Example

```ts
const checksum = await sos.offline.cache.getChecksumFile('example-file.mp4', 'md5');
console.log('MD5 Checksum:', checksum); // Output: MD5 Checksum: d41d8cd98f00b204e9800998ecf8427e
```

:::note[GitHub Example]

- [ Example Applet with MD5 Checksum](https://github.com/signageos/applet-examples/tree/master/examples/content-js-api/md5-checksum)

:::

<Separator />

### listContents()

The `listContent()` method lists all values saved by `saveContent()` method.

```ts expandable
listContents(): Promise<string[]>;
```

#### Return value

A promise that resolves to an array of saved content.

#### Example

```ts
// Save some content and list all saved contents
await sos.offline.cache.saveContent('ApplicationSecret', '123SuperSecretHash');
await sos.offline.cache.saveContent('UserToken', 'abc123xyz');

// Later list the saved contents
const contents = await sos.offline.cache.listContents();
console.log('Saved contents:', contents); // Output: Saved contents: ['ApplicationSecret', 'UserToken']
```

<Separator />

### listFiles()

The `listFiles()` method list all currently cached files in internal storage, which was previously saved by `saveFile()` or `loadOrSaveFile()` methods.

```ts expandable
listFiles(): Promise<string[]>;
```

#### Return value

A promise that resolves to an array of unique identifiers (uids) of the saved files.

#### Possible errors


- Error If any error occurs during listing files.
- Error If the files cannot be listed.

#### Example

```ts
await sos.offline.cache.saveFile('example-file.mp4', 'https://example.com/path/to/your/file.mp4');
await sos.offline.cache.saveFile('another-file.jpg', 'https://example.com/path/to/your/image.jpg');

// Later list the saved files
const files = await sos.offline.cache.listFiles();
console.log('Saved files:', files); // Output: Saved files: ['example-file.mp4', 'another-file.jpg']
```

<Separator />

### loadContent()

<Admonition type="info" icon="" title="">
  Learn more about using this API [here](https://developers.signageos.io/docs/sos-guides/key-value-storage)
</Admonition>

The `loadContent()` method gets the value specified by `uid`, which was previously saved by `saveContent()`.

```ts expandable
loadContent(uid: string): Promise<string>;
```

#### Params

| Name  | Type     | Required         | Description                                    |
|-------|----------|------------------|------------------------------------------------|
| `uid` | `string` |  <div>Yes</div>  | Unique identifier of the content to be loaded. |

#### Return value

A promise that resolves to the loaded content.

#### Possible errors


- Error If the uid does not exist.
- Error If the uid is not a valid string.
- Error If the content is not a valid string.
- Error If any other error occurs during loading.

#### Example

```ts
// Previously saved content with uid 'ApplicationSecret'
await sos.offline.cache.saveContent('ApplicationSecret', '123SuperSecretHash');

// Load the content
const content = await sos.offline.cache.loadContent('ApplicationSecret');
console.log('Loaded content:', content); // Output: Loaded content: 123SuperSecretHash
```

<Separator />

### loadFile()

The `loadFile()` method loads cached file, which was previously saved by `saveFile()` or `loadOrSaveFile()` methods.

```ts expandable
loadFile(uid: string): Promise<IFile>;
// show-more
interface IFile {
    filePath: string;
}

```

#### Params

| Name  | Type     | Required         | Description                                 |
|-------|----------|------------------|---------------------------------------------|
| `uid` | `string` |  <div>Yes</div>  | Unique identifier of the file to be loaded. |

#### Return value

A promise that resolves to the loaded file.

#### Possible errors


- Error If the uid is not a valid string.
- Error If the uid does not exist

#### Example

```ts
// Save a file
await sos.offline.cache.saveFile('example-file.mp4', 'https://example.com/path/to/your/file.mp4');
// Later load the file
const file = await sos.offline.cache.loadFile('example-file.mp4');
console.log('Loaded file:', file); // Output: Loaded file: { uid: 'example-file.mp4', uri: 'file://path/to/your/file.mp4' }
```

<Separator />

### loadOrSaveFile()

Method `loadOrSaveFile()` is used for individual file retrieval & save in case when file is not saved in local storage yet. To get file from internal memory & save it when not yet exists we prepared `loadOrSaveFile()` method.

:::info
- The file URI has to return the file. If your URI leads to a 303 redirect (e.g. from http to https), the API will not work.
- Emulator has certain limitations while handling offline files. [Read more here](https://docs.signageos.io/hc/en-us/articles/4405238997138).
- Local device file path differs from device to device. It can point to `file://` or `http://localhost` etc.
:::

:::warning
`uid` should have the same file extension (e.g.: mp4, svg, jpg) as the original file
:::

```ts expandable
loadOrSaveFile(uid: string, uri: string, headers?: {
    [key: string]: string;
}): Promise<IFile>;
// show-more
interface IFile {
    filePath: string;
}

```

#### Params

| Name      | Type                         | Required         | Description                                                                                                                                                                     |
|-----------|------------------------------|------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `uid`     | `string`                     |  <div>Yes</div>  | Unique identifier of the file to be loaded or saved.                                                                                                                            |
| `uri`     | `string`                     |  <div>Yes</div>  | URI of the file to be downloaded if not cached.                                                                                                                                 |
| `headers` | `{ [key: string]: string; }` |  <div>No</div>   | Key, value pairs of HTTP headers to send along with the request. Used when the target file is protected by a password or if any other specific headers are needed to access it. |

#### Return value

A promise that resolves to the loaded or saved file.

#### Possible errors


- Error If the uid is not a valid string.
- Error If the uri is not a valid URI.
- Error If the headers are not a valid object with string values.
- Error If the file cannot be loaded or saved.
- AppletOfflineCacheError If the headers are not valid.

#### Example

```ts
await sos.offline.cache.loadOrSaveFile('example-file.mp4', 'https://example.com/path/to/your/file.mp4')
	.then((file) => {
		console.log('File loaded or saved:', file);
	})
	.catch((error) => {
		console.error('Error loading or saving file:', error);
});
```

:::note[GitHub Example]

- [ Example Applet with Offline Files](https://github.com/signageos/applet-examples/blob/master/examples/content-js-api/offline-files)
- [ Example Applet with Video Loop Offline](https://github.com/signageos/applet-examples/tree/master/examples/content-js-api/video-loop-offline)

:::

<Separator />

### saveContent()

<Admonition type="info" icon="" title="">
  Learn more about using this API [here](https://developers.signageos.io/docs/sos-guides/key-value-storage)
</Admonition>

The `saveContent()` method saves a string value to the cache with specified `uid`.

Use when you need to save some data into local memory. This API provides you with approach similar to the HTML5's Local Storage, but implemented internally via native device API and completely device-agnostic.

```ts expandable
saveContent(uid: string, content: string): Promise<void>;
```

#### Params

| Name      | Type     | Required         | Description                                   |
|-----------|----------|------------------|-----------------------------------------------|
| `uid`     | `string` |  <div>Yes</div>  | Unique identifier of the content to be saved. |
| `content` | `string` |  <div>Yes</div>  | The string content to be saved.               |

#### Return value

A promise that resolves when the content is saved.

#### Possible errors


- Error If the uid is not a valid string.
- Error If the content is not a valid string.
- Error If the uid already exists.
- Error If any other error occurs during saving.

#### Example

```ts
sos.offline.cache.saveContent('ApplicationSecret', '123SuperSecretHash')
.then(() => {
    //Content was successfully saved, retrieve it.
    return sos.offline.cache.loadContent('ApplicationSecret');
})
.then((content) => {
    console.log('Loaded', content); // print 123SuperSecretHash
})
```

:::note[GitHub Example]

- [ Example of Applet using saveContent()](https://github.com/signageos/applet-examples/tree/master/examples/content-js-api/offline-content)

:::

<Separator />

### saveFile()

Method `saveFile()` is used to save files from remote a destination into the device internal memory.

:::info
- Local device file path differs from device to device. It can point to `file://` or `http://localhost` etc.
:::

:::warning
- headers has to be a JSON object. If you are passing the value, make sure you use JSON.parse().
- `uid` should have the same file extension (e.g.: mp4, svg, jpg) as the original file.
:::

```ts expandable
saveFile(uid: string, uri: string, headers?: {
    [key: string]: string;
}): Promise<void>;
```

#### Params

| Name      | Type                         | Required         | Description                                                                                                                                                                     |
|-----------|------------------------------|------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `uid`     | `string`                     |  <div>Yes</div>  | Unique identifier of the file to be saved.                                                                                                                                      |
| `uri`     | `string`                     |  <div>Yes</div>  | URI of the file to be downloaded.                                                                                                                                               |
| `headers` | `{ [key: string]: string; }` |  <div>No</div>   | Key, value pairs of HTTP headers to send along with the request. Used when the target file is protected by a password or if any other specific headers are needed to access it. |

#### Possible errors


- Error If the network request fails.
- Error If the uid is not a valid string.
- Error If the uri is not a valid URI.
- Error File with the same uid is already cached.
- Error If the headers are not a valid object with string values.

#### Example

```ts
await sos.offline.cache.saveFile('example-file.mp4', 'https://example.com/path/to/your/file.mp4')
	.then(() => {
		console.log('File saved successfully');
 })
 .catch((error) => {
		console.error('Error saving file:', error);
});
```

<Separator />

### validateChecksumFile()

The `validateChecksumFile()` method validates whether the file, specified by `uid`, has the correct checksum.

```ts expandable
validateChecksumFile(uid: string, hash: string, hashType: HashAlgorithm): Promise<boolean>;
// show-more
/**
 * Represents the supported hash algorithms by Core Apps.
 */
type HashAlgorithm = 'md5' | 'crc32' | AnyString;

type AnyString = string & {};

```

#### Params

| Name       | Type            | Required         | Description                                                               |
|------------|-----------------|------------------|---------------------------------------------------------------------------|
| `uid`      | `string`        |  <div>Yes</div>  | Unique file identifier of a previously downloaded file.                   |
| `hash`     | `string`        |  <div>Yes</div>  | The expected checksum of the file.                                        |
| `hashType` | `HashAlgorithm` |  <div>Yes</div>  | The hashing algorithm to use. Supported algorithms are 'md5' and `crc32`. |

#### Return value

A promise that resolves to `true` if the checksum is valid, otherwise `false`.

#### Possible errors


- Error If the uid does not exist or the hashing algorithm is not supported.
- Error If the hash is not a valid string.
- Error If the hashType is not a valid string.

#### Example

```ts
// Validate the checksum of a file
const expectedHash = 'd41d8cd98f00b204e9800998ecf8427e'; // Example MD5 hash
// Previously saved file with uid 'example-file.mp4'
const isValid = await sos.offline.cache.validateChecksumFile('example-file.mp4', expectedHash, 'md5');
```