Upload audio/video to Note and follow processing from native ArkTS apps. Requires HarmonyOS 5.0+ (API 12). An API key can query recordings uploaded with that same key. View transcripts, summaries and playback in Note.
Run this command in your app module:
ohpm install @olares/note-sdkFor a specific published version, use ohpm install @olares/note-sdk@<version>.
Declare network permission in the app module's module.json5:
"requestPermissions": [{ "name": "ohos.permission.INTERNET" }]Your app needs read access to the selected file. Use HTTPS in production.
Install an offline HAR
If the version you need is not on OHPM, place olares-note-harmony-sdk-0.2.5.har in the app module's
libs/ directory. Set the dependency to "file:./libs/olares-note-harmony-sdk-0.2.5.har"
and run ohpm install.
Create an API key in Note → Settings → API Key. It includes the service address.
Your app supplies apiKey and filePath below. Generate an idempotencyKey once per new upload
and save it with the file reference before uploading. Reuse the saved value when resuming.
Run inside an async method:
import { util } from '@kit.ArkTS';
import { NoteClient, NoteCancellation, RecordingStatus } from '@olares/note-sdk';
const client = NoteClient.fromApiKey(apiKey);
const signal = new NoteCancellation();
const idempotencyKey = util.generateRandomUUID();
// Save idempotencyKey with the file reference before uploading.
const recording = await client.upload(filePath, {
title: 'Weekly meeting',
idempotencyKey: idempotencyKey,
signal: signal,
onProgress: (sent: number, total: number): void => { /* Confirmed bytes / total bytes. */ }
});
// Save recording.recordingId for later queries.
const result = await client.waitForCompletion(recording.recordingId, {
signal: signal,
onStatus: (status: RecordingStatus): void => { /* Show status.processing.currentStage. */ }
});Upload success means Note has accepted the file; processing may still be running.
Save the returned recording ID and query it. Processing failures are returned as statuses;
check processing.status.
Network methods return Promise<RecordingStatus> except getStatuses, which returns a result list. Request failures reject.
RequestOptions accepts an optional cancellation signal.
| Method | Parameters and result |
|---|---|
fromApiKey |
apiKey: string; optional ClientOverrides: endpoint, retries = 3, connectTimeout = 10000, requestTimeout = 300000 (milliseconds). Returns NoteClient. Old keys without an address need endpoint; the first request verifies authorization |
upload / uploadUri |
upload(input: string | ArrayBuffer, options?) accepts a file path or bytes. uploadUri(uri, cacheDir, options) accepts a picker URI. Uploads in chunks and returns upload status |
uploadRecording / uploadRecordingUri |
Same inputs as the corresponding chunk method. Sends one multipart request, without chunk progress or resumable chunks |
createUpload |
fileName: string, totalBytes: number, optional UploadOptions. Creates or recovers a session |
uploadChunk |
recordingId: string, offset: number, bytes: ArrayBuffer, optional RequestOptions. Sends a chunk at an absolute byte offset and returns updated status |
getUpload |
recordingId: string, optional RequestOptions. Returns upload state, confirmed offset and chunk size |
getStatus |
recordingId: string, optional RequestOptions. Returns upload and processing state |
getStatuses (0.2.5+) |
recordingIds: string[], options?: RequestOptions → Promise<RecordingStatusResult[]> |
waitForCompletion |
recordingId: string, optional WaitOptions. Polls and returns a terminal status, including failure |
Byte buffers and URI uploads require fileName with an extension. URI uploads copy to cache
and need free space equal to the file size; keep read permission. For manual chunks, use
the server's upload.offset and upload.chunkSize; the last chunk may be smaller.
const recording = await client.uploadUri(uri, context.cacheDir, {
fileName: 'meeting.m4a', idempotencyKey: idempotencyKey, signal: signal
});
const status = await client.getStatus(recording.recordingId, { signal: signal });UploadOptions accepts these optional fields. Omitted recording settings use Note defaults.
| Field | Meaning |
|---|---|
title |
Recording title |
language / targetLanguage |
Spoken language / output language for translations and summaries. Omit language for detection |
speakerHint |
Expected speakers, 0–50; 0 means unknown |
translateEnabled / summarizeEnabled |
Enable translation / summaries |
summaryTemplateId |
Summary template ID |
sourceClient / sourceDevice |
Source app name/version / device label |
idempotencyKey |
Saved identifier for this upload; reuse it to resume |
fileName |
File name with an extension; required for byte buffers and URI uploads |
onProgress(sent, total) |
Confirmed bytes / total bytes, for chunk uploads |
signal |
NoteCancellation for local cancellation |
Title, language, target language, source app/device and file name allow up to 2,000 characters each;
longer values return field_too_long.
WaitOptions accepts interval = 5000, optional timeout, onStatus and signal.
Times are nonnegative safe-integer milliseconds; the default wait is unlimited.
The timeout is checked between requests and does not interrupt a request in flight.
Use signal.cancel() to stop local work. A zero timeout still permits the first query.
RecordingStatus contains:
| Field | Meaning |
|---|---|
recordingId, title, statusUrl |
Recording ID, title and status address |
upload |
state, offset, chunkSize, totalBytes, optional error; byte counts are safe integers |
processing |
status, optional currentStage, outcome, errorCode, error, waiting |
Import isFinished(status) to check for a terminal outcome. Read upload.error when upload state
is failed. Processing ends at completed, failed or canceled; outcome = no_speech means
no speech was detected.
processing.waiting describes a model wait. Its reason is model_unavailable, model_warming,
model_busy or model_stalled; use a generic message for unknown values. It also carries
capability, RFC 3339 timestamps since / nextProbeAt, and optional message.
Keep querying: model recovery can continue processing without another upload.
Available since SDK 0.2.5. Requires a Note server with the batch status endpoint. Query 1–50 known recording IDs in one request. This creates no upload session and returns no history list. Results follow input order, including duplicates.
Exactly one of recording or error is present in each result:
| Field | Meaning |
|---|---|
recordingId |
Requested recording ID |
recording |
The same RecordingStatus returned by getStatus |
error.code, error.status, error.message |
Per-record error code, status and description |
| Case | Result | Action |
|---|---|---|
| Accessible recording | Item has recording | Read its upload and processing state |
| Missing, trashed or owned by another key | Item error: 404 / not_found | Mark the cloud recording unavailable; do not automatically upload again |
| Invalid individual ID | Item error: 400 / invalid_id | Correct that ID; other results remain usable |
| Individual service failure | Item error: 500 / internal, 503 / database_unavailable, or another server code | Retry that item later |
| Empty list / more than 50 IDs | Whole call fails: 400 / invalid_request or field_too_long | Supply IDs or split the batch |
| Invalid response fields, result count or ID correspondence | Whole call fails: invalid_response (status 0) | Retain the request ID; do not reconcile local records |
| Invalid API key or whole-request failure | Whole call throws / invokes the failure callback | Handle as a request error |
error.status describes an individual failure, not the HTTP response status of the batch. HTTP 200 means the batch request completed, not that every item succeeded. Missing recordings do not fail the SDK call; check each item's error. The SDK does not automatically retry item errors; query those IDs again when needed.
not_found does not distinguish deletion, a nonexistent ID or lack of access. An old ID also returns not_found after permanent deletion.
const recordingIds: string[] = [
'11111111-1111-4111-8111-111111111111',
'22222222-2222-4222-8222-222222222222'
];
const results = await client.getStatuses(recordingIds);
for (const result of results) {
if (result.recording !== undefined) {
console.info('%s: %s', result.recordingId, result.recording.processing.status);
} else if (result.error !== undefined) {
console.info('%s: %s', result.recordingId, result.error.code);
}
}- Resume with the same file, API key and saved idempotency key. Keep the file unchanged and readable.
After upload returns, save
recordingIdand query directly. - Your app owns upload records, key storage and task queues. The SDK does not save them or schedule work after restart.
- Create one
NoteCancellationper operation; a canceled token cannot be reused.signal.cancel()rejects withNoteCanceledError. It stops local work, without deleting recordings or stopping processing in Note. - Request failures reject with
NoteApiError. Client creation can also fail on an invalid key or address. Handlecode; usestatus(see the error codes below),requestIdandretryablefor diagnostics and retry decisions. Never log API keys. - Each request has at most 3 attempts by default, with backoff starting at 500 ms. POST requests retry only with a nonblank idempotency key.
These errors are generated by the SDK during validation or upload. Server error.code values are also passed through; codes are strings, not a closed enum.
For HTTP failures, status preserves the response status. SDK-generated errors usually use 0, but also use 409, 422 and 500; status alone does not identify the source.
Automatic chunked upload() runs in this order:
- Prepare the file before the request: prepare the file source, determine its name and obtain its byte count. API key format is checked when creating the client.
- Create or resume the session: call
POST /v1/uploadsto obtain the session's total byte count and upload state. - Compare sizes in the SDK: when the returned session total is nonzero, compare it with the local size. A mismatch throws
idempotency_mismatch(SDK status 409) and stops the upload without sending chunks. This check runs before testing whether the upload is complete. - Continue according to upload state: after validation,
readyreturns the existing recording status,pending/activeuploads chunks, andfailedthrowsupload_failed.
When resuming a completed session, step 3 still runs after HTTP 200. Its 409 is assigned by the SDK, not returned by the endpoint. The comparison uses exact byte counts, not duration or content hashes.
Local validation and file preparation:
| code | status | Trigger | Action |
|---|---|---|---|
invalid_api_key_format |
0 |
Invalid API key format, metadata or endpoint | Check the key and HTTP(S) endpoint |
api_key_too_new |
0 |
Key version is newer than this SDK supports | Update the SDK |
api_key_without_endpoint |
0 |
Neither the key nor configuration provides an endpoint | Create a new key or supply an endpoint |
missing_file_name |
0 |
File name is missing and cannot be inferred | Provide fileName with an extension |
file_unreadable |
0 |
File cannot be read or changes during upload | Check access; finish Bluetooth sync and stop writing before upload |
idempotency_mismatch |
409 |
upload() receives a nonzero session total that differs from the local file size, including completed uploads | Restore the original file; use a new key to create a recording for a changed file |
invalid_options |
0 |
Time, retry configuration or byte counts fail numeric validation | Check options: positive integer timeouts; nonnegative safe integer polling times and byte counts |
Upload and request errors:
| code | status | Trigger | Action |
|---|---|---|---|
network_error |
0 |
Request could not complete | Check connection and service; retain the file and key for resume |
timeout |
0 |
Local processing wait timed out | Query the existing recording ID; do not create another recording |
upload_failed |
422 |
upload() observes upload.state = failed | Read the description; check the file and Note service |
upload_stalled |
500 |
Upload offset does not advance or chunk/session state is invalid | Query status first; resume with the same file and key |
invalid_response |
0 |
Response cannot be decoded as supported status data | Check the service version; retain the request ID when available |
Server errors retain their original code and HTTP status, for example invalid_api_key (401: configure a valid key) and quota_exceeded (507: free storage).
An HTTP failure without error.code uses http_<status>, such as http_503. Handle unknown codes with a generic message and retain the code and optional request ID. Never branch on descriptions or log API keys.
Cancellation uses NoteCanceledError, not an upload failure.
The ArkUI demo in olares-note-harmony-demo-0.2.5-source.zip has ArkTS examples, file selection and local history separated by API key.
It demonstrates manual recovery after restart.