Device Storage API

この翻訳は不完全です。英語から この記事を翻訳 してください。

非標準
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

This API is available on Firefox OS for privileged or certified applications only.

概要

Device Storage API はwebアプリがファイルシステムへアクセスするために使われます。 ファイルシステムへのアクセスは非常に注意を要するため、このAPIはprivilleged アプリのみが使用できます。

Note: デバイスストレージへのアクセスは物理レベルの制限で遅いです。多くの場合、IndexedDB を使用することで高速化できます。

デバイスストレージへのアクセス

このセクションはデバイスストレージへのアクセスに必要なことを説明します。

エントリーポイント

記憶領域へのアクセスは次のように記述することができます。

navigator.getDeviceStorage()
navigator.getDeviceStorages()

  • navigator.getDeviceStorage()
  • アクセス先の記憶領域を代表した名前を文字列で渡すことができます。このメソッドは関連した記憶領域へアクセスするための DeviceStorage オブジェクトをリターンします。オブジェクトの .default 属性は true になります。 これはユーザの次の手順を通してコントロールされます。
    Settings App > Media Storage > Default media location
  • navigator.getDeviceStorages()
  • 記憶領域へのアクセスが許可される DeviceStorage オブジェクトの Array が返されます。記憶領域毎にひとつのオブジェクトです。

Firefox OS は次の記憶領域名を定めています。:

  • apps: この記憶領域はアプリが必要とするユーザデータを格納します。 これは重要なデータなのでこの記憶領域へのアクセスには特別な権限が要求されます。 (下記参照) これは certified アプリケーションのみが使用可能です。
  • music: ミュージックとサウンドが保存される記憶領域です。
  • pictures: 写真が保存される記憶領域です。
  • sdcard: SDカードデバイスにアクセスできます。
  • videos: 動画が保存される記憶領域です
var pics = navigator.getDeviceStorage('pictures');

When using navigator.getDeviceStorages(), if there is more than one storage area then the internal one will be named for example sdcard and the physical storage area will be called something else (sometimes it's extsdcard, sometimes it's sdcard1). This varies by device manufacturer. The names of files on the sdcard storage area will be /sdcard/path/filename, and the names of files on the sdcard1 storage area will be /sdcard1/path/filename, or whatever.

Note that the /sdcard and /sdcard1 are storage names. Their actual mount points on the system are determined via vold and/or /system/etc/volume.cfg file.) DeviceStorage transparently maps the storageName into the actual mountPoint (so you don't need the mount point if you're just accessing the files through device storage).

If you want to determine the mount point to examine the filesystem from an adb shell, then you can determine the vold mount points by using the command adb shell vdc volume list  (this requires a root shell).

On the Flame, you'll see something like this:

110 0 sdcard /storage/sdcard 4
110 0 sdcard1 /storage/sdcard1 4
200 0 Volumes listed.

For volumes that aren't managed by vold (for example, the sdcard volume on a Nexus 4/5), the mount point is found in /system/etc/volume.cfg.

Note: In Gaia engineering builds there is a ds-test app, which is useful for device storage testing.

 

デバイスストレージのパーミッション

これらの記憶領域を使用するためにアプリケーションはマニフェストにて宣言しておく必要があります。たとえばもしアプリケーションが sdcard 領域にアクセスしたい場合、マニフェストの permissionに "device-storage:sdcard" を記述しなければなりません。

"permissions": {
  "device-storage:videos":{ "access": "readonly" },
  "device-storage:pictures":{ "access": "readwrite" }
}

前述のように、 device-storage:apps は特別な権限が必要です。open web apps のインストールを管理する navigator.mozApps.mgmt APIを使うために  webapps-manage permissionが必要となります。

"permissions": {
  "device-storage:apps":{ "access": "readwrite" },
  "webapps-manage":{ }
}

appsを除くすべての device-storage 記憶領域は privileged level の権限を必要とします。 apps は certifiedです。webapps-manage は certified levelの権限で使用できます。

ストレージの利用

アプリケーションは記憶領域へのアクセスを取得すると、その記憶領域内のファイルを追加、取得、および削除することが可能です。

ファイルの追加

Adding a file is done using the addNamed or add methods. The former allows to set an explicit name when storing a file while the latter creates a name automatically when the file is stored. Both methods are asynchronous and return a DOMRequest object to handle the success or error of the operation. This is very important as writing and reading files on a physical support is a slow process.

Those two methods expect a Blob as their first parameter. This object will be turned into a file under the hood and stored. When creating a Blob object, it's mandatory to give it a type. This type, which is a mime type, is important because some storage areas have restrictions based on the type:

  • music only accepts Blob with a valid audio mime type
  • pictures only accepts Blob with a valid image mime type
  • videos only accepts Blob with a valid video mime type
var sdcard = navigator.getDeviceStorage("sdcard");
var file   = new Blob(["This is a text file."], {type: "text/plain"});

var request = sdcard.addNamed(file, "my-file.txt");

request.onsuccess = function () {
  var name = this.result;
  console.log('File "' + name + '" successfully wrote on the sdcard storage area');
}

// An error typically occur if a file with the same name already exist
request.onerror = function () {
  console.warn('Unable to write the file: ' + this.error);
}

Note: Repository in a storage area are implicit. It's not possible to create explicitly an empty repository. If you want to use a repository structure you have to make it part of the name of the file to store. So if you want to store the file bar inside the foo repository, you have to use the addNamed method with the complete path name of the file addNamed(blob, "foo/bar"). This is also true when you want to retrieve a file using it's name (see below).

As file are added in a given restricted storage area for security reason, a file path name cannot start with "/" nor "../" (and "./" is pointless).

ファイルの取得

Retrieving a file can be done in both ways: by using its name or by iterating the whole list of files.

The easiest way is to retrieve a file by its name using the get and getEditable methods. The former provides a File object (which act like a read only file) when the latter provides a FileHandle object (which allows updating the underlaying file). Both methods are asynchronous and return a DOMRequest object to handle the success or error of the operation.

var sdcard = navigator.getDeviceStorage('sdcard');

var request = sdcard.get("my-file.txt");

request.onsuccess = function () {
  var file = this.result;
  console.log("Get the file: " + file.name);
}

request.onerror = function () {
  console.warn("Unable to get the file: " + this.error);
}

The other way to retrieve files is by browsing the content of the storage area. This is possible using the enumerate and enumerateEditable methods. The former provides File objects when the latter provides FileHandle objects. Both methods are asynchronous and return a DOMCursor object to iterate along the list of files. A DOMCursor is nothing less than a DOMRequest with extra power to iterate asynchronously along a list of things (files in that case).

var pics = navigator.getDeviceStorage('pictures');

// Let's browse all the images available
var cursor = pics.enumerate();

cursor.onsuccess = function () {
  var file = this.result;
  console.log("File found: " + file.name);

  // Once we found a file we check if there is other results
  if (!this.done) {
    // Then we move to the next result, which call the cursor
    // success with the next file as result.
    this.continue();
  }
}

cursor.onerror = function () {
  console.warn("No file found: " + this.error);
}

It's possible to limit the number of result by passing two optional parameters to the enumerate and enumerateEditable methods.

The first parameter can be a string representing a sub folder to search inside.

The second parameter can be an object with a since property, which allow to limit the search to a given time period.

var pics = navigator.getDeviceStorage('pictures');

// Lets retrieve picture from the last week.
var param = {
  since: new Date((+new Date()) - 7*24*60*60*1000)
}

var cursor = pics.enumerate(param);

cursor.onsuccess = function () {
  var file = this.result;
  console.log("Picture taken on: " + file.lastModifiedDate);

  if (!this.done) {
    this.continue();
  }
}

ファイルの削除

A file can be removed from the storage area by simply using the delete method. This method just need the name of the file to delete. As all the other methods from the DeviceStorage interface, this one is also asynchronous and return a DOMRequest object to handle the success or error of the operation.

var sdcard = navigator.getDeviceStorage('sdcard');

var request = sdcard.delete("my-file.txt");

request.onsuccess = function () {
  console.log("File deleted");
}

request.onerror = function () {
  console.log("Unable to delete the file: " + this.error);
}

ストレージ情報

Beyond accessing files, a storage area provide a few methods to easily reach some important information

利用可能領域

One of the most important thing to know when storing files on a device is the amount of space available. The DeviceStorage interface provide two useful function dedicated to space:

  • freeSpace() to get the amount of free space available to store new files;
  • usedSpace() to get the amount of space used to store the files;

As those methods are asynchronous, they return a DOMRequest object to handle the success or error of the operation.

var videos = navigator.getDeviceStorage('videos');

var request = videos.usedSpace();

request.onsuccess = function () {
  // The result is express in bytes, lets turn it into megabytes
  var size = this.result / 1048576;
  console.log("The videos on your device use a total of " + size.toFixed(2) + "Mo of space.");
}

request.onerror = function () {
  console.warn("Unable to get the space used by videos: " + this.error);
}

変更の監視

As many applications can use a same storage area at the same time, it's sometime useful for an application to be aware of a change in that storage area. It's also useful for an application who want to perform asynchronous action without relaying on all the DOMRequest objects return by each method of the DeviceStorage interface.

To that end, a change event is triggered each time a file is created, modified or deleted. This event can be capture using the onchange property or the addEventListener() method. The event handler get a DeviceStorageChangeEvent object which is a regular Event object with two extra properties:

var sdcard = navigator.getDeviceStorage('sdcard');

sdcard.onchange = function (change) {
  var reason = change.reason;
  var path   = change.path;

  console.log('The file "' + path + '" has been ' + reason);
}

仕様

Not part of any specification.

ブラウザ互換性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support ? ? 未サポート 未サポート 未サポート
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? ? 未サポート 未サポート 未サポート

関連項目

ドキュメントのタグと貢献者

 このページの貢献者: Shinji.Ueno, chikoski
 最終更新者: Shinji.Ueno,