-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmediadb.js
2150 lines (1935 loc) · 80.9 KB
/
mediadb.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* globals indexedDB */
/* exported MediaDB */
'use strict';
/**
* MediaDB.js: a simple interface to DeviceStorage and IndexedDB that serves
* as a model of the filesystem and provides easy access to the
* user's media files and their metadata.
*
* Gaia's media apps (Gallery, Music, Videos) read media files from the phone
* using the DeviceStorage API. They need to keep track of the complete list of
* media files, as well as the metadata (image thumbnails, song titles, etc.)
* they have extracted from those files. It would be much too slow to scan the
* filesystem and read all the metadata from all files each time the apps starts
* up, so the apps need to store the list of files and metadata in an IndexedDB
* database. This library integrates both DeviceStorage and IndexedDB into a
* single API. It keeps the database in sync with the filesystem and provides
* notifications when files are added or deleted.
*
* CONSTRUCTOR
*
* Create a MediaDB object with the MediaDB() constructor. It takes three
* arguments:
*
* mediaType:
* one of the DeviceStorage media types: "pictures", "movies" or "music".
*
* metadataParser:
* your metadata parser function. This function should expect three
* arguments. It will be called with a file to parse and two callback
* functions. It should read metadata from the file and then pass an object
* of metadata to the first callback. If parsing fails it should pass an
* Error object or error message to the second callback. If you omit this
* argument or pass null, a dummy parser that invokes the callback with an
* empty object will be used instead.
*
* options:
* An optional object containing additional MediaDB options.
* Supported options are:
*
* mimeTypes:
* an array of MIME types that specifies the kind of files you are
* interested in and that your metadata parser function knows how to
* handle. DeviceStorage infers MIME type from filename extension and
* filters the files it returns based on their extension. Use this
* property if you want to restrict the set of mime types further.
*
* indexes:
* an array of IndexedDB key path specifications that specify which
* properties of each media record should be indexed. If you want to
* search or sort on anything other than the file name and date you
* should set this property. "size", and "type" are valid keypaths as
* is "metadata.x" where x is any metadata property returned by your
* metadata parser.
*
* version:
* The version of your IndexedDB database. The default value is 1
* Setting it to a larger value will delete all data in the database
* and rebuild it from scratch. If you ever change your metadata parser
* function or alter the array of indexes.
*
* autoscan:
* Whether MediaDB should automatically scan every time it becomes
* ready. The default is true. If you set this to false you are
* responsible for calling scan() in response to the 'ready' event.
*
* batchHoldTime:
* How long (in ms) to wait after finding a new file during a scan
* before reporting it. Longer hold times allow more batching of
* changes. The default is 100ms.
*
* batchSize:
* When batching changes, don't allow the batches to exceed this
* amount. The default is 0 which means no maximum batch size.
*
* updateRecord:
* When upgrading database, MediaDB uses this function to ask client
* app to update the metadata record of specified file. The return
* value of this function is the updated metadata. If client app does
* not update any metadata, client app still needs to return
* file.metadata. The client may also set file.needsReparse to indicate
* that the source file should be reparsed.
*
* reparsedRecord:
* If in updateRecord, a record has been marked with file.needsReparse,
* this function is called after the file has been reparsed to allow
* the client app to merge any old metadata (e.g. metadata set by the
* user). This function takes two arguments: the old metadata and the
* new metadata, and should return the merged metadata.
*
* excludeFilter:
* excludeFilter is used when client app wants MediaDB to filter out
* additional media files. It must be a regular expression object. The
* matched files are filtered out. The original filtering behavior of
* MediaDB will not be change even if excludeFilter is supplied.
*
* MediaDB STATE
*
* A MediaDB object must asynchronously open a connection to its database, and
* asynchronously check on the availability of device storage, which means that
* it is not ready for use when first created. After calling the MediaDB()
* constructor, register an event listener for 'ready' events with
* addEventListener() or by setting the onready property. You must not use
* the MediaDB object until the ready event has been delivered or until
* the state property is set to MediaDB.READY.
*
* The DeviceStorage API is not always available, and MediaDB is not usable if
* DeviceStorage is not usable. If the user removes the SD card from their
* phone, then DeviceStorage will not be able to read or write files,
* obviously. Also, when a USB Mass Storage session is in progress,
* DeviceStorage is not available either. If DeviceStorage is not available
* when a MediaDB object is created, an 'unavailable' event will be fired
* instead of a 'ready' event. Subsequently, a 'ready' event will be fired
* whenever DeviceStorage becomes available, and 'unavailable' will be fired
* whenever DeviceStorage becomes unavailable. Media apps can handle the
* unavailable case by displaying an informative message in an overlay that
* prevents all user interaction with the app.
*
* The 'ready' and 'unavailable' events signal changes to the state of a
* MediaDB object. The state is also available in the state property of the
* object. The possible values of this property are the following:
*
* Value Constant Meaning
* ----------------------------------------------------------------------
* 'opening' MediaDB.OPENING MediaDB is initializing itself
* 'upgrading' MediaDB.UPGRADING MediaDB is upgrading database
* 'enumerable' MediaDB.ENUMERABLE Not fully ready but can be enumerated
* 'ready' MediaDB.READY MediaDB is available and ready for use
* 'nocard' MediaDB.NOCARD Unavailable because there is no sd card
* 'unmounted' MediaDB.UNMOUNTED Unavailable because the card is unmounted
* 'closed' MediaDB.CLOSED Unavailable because close() was called
*
* When an 'unavailable' event is fired, the detail property of the event
* object specifies the reason that the MediaDB is unavailable. It is one of
* the state values 'nocard', 'unmounted' or 'closed'.
*
* The 'nocard' state occurs when device storage is not available because
* there is no SD card in the device. This is typically a permanent failure
* state, and media apps cannot run without an SD card. It can occur
* transiently, however, if the user is swapping SD cards while a media app is
* open.
*
* The 'unmounted' state occurs when the device's SD card is unmounted. This
* is generally a temporary condition that occurs when the user starts a USB
* Mass Storage transfer session by plugging their device into a computer. In
* this case, MediaDB will become available again as soon as the device is
* unplugged (it may have different files on it, though: see the SCANNING
* section below).
*
* DATABASE RECORDS
*
* MediaDB stores a record in its IndexedDB database for each DeviceStorage
* file of the appropriate media type and mime type. The records
* are objects of this form:
*
* {
* name: // the filename (relative to the DeviceStorage root)
* type: // the file MIME type (extension-based, from DeviceStorage)
* size: // the file size in bytes
* date: // file modification time (as ms since the epoch)
* metadata: // whatever object the metadata parser returned
* }
*
* Note that the database records do not include the file itself, but only its
* name. Use the getFile() method to get a File object (a Blob) by name.
*
* ENUMERATING FILES
*
* Typically, the first thing an app will do with a MediaDB object after the
* ready event is triggered is call the enumerate() method to obtain the list
* of files that MediaDB already knows about from previous app invocations.
* enumerate() gets records from the database and passes them to the specified
* callback. Each record that is passed to the callback is an object in the
* form shown above.
*
* If you pass only a callback to enumerate(), it calls the callback once for
* each entry in the database and then calls the callback with an argument of
* null to indicate that it is done.
*
* By default, entries are returned in alphabetical order by filename and all
* entries in the database are returned. You can specify other arguments to
* enumerate() to change the set of entries that are returned and the order that
* they are enumerated in. The full set of arguments are:
*
* key:
* A keypath specification that specifies what field to sort on. If you
* specify this argument, it must be 'name', 'date', or one of the values
* in the options.indexes array passed to the MediaDB() constructor. This
* argument is optional. If omitted, the default is to use the file name
* as the key.
*
* range:
* An IDBKeyRange object that optionally specifies upper and lower bounds on
* the specified key. This argument is optional. If omitted, all entries in
* the database are enumerated. See IndexedDB documentation for more on
* key ranges.
*
* direction:
* One of the IndexedDB direction string "next", "nextunique", "prev" or
* "prevunique". This argument is optional. If omitted, the default is
* "next", which enumerates entries in ascending order.
*
* callback:
* The function that database entries should be passed to. This argument is
* not optional, and is always passed as the last argument to enumerate().
*
* The enumerate() method returns database entries. These include file names,
* but not the files themselves. enumerate() interacts solely with the
* IndexedDB; it does not use DeviceStorage. If you want to use a media file
* (to play a song or display a photo, for example) call the getFile() method.
*
* enumerate() returns an object with a 'state' property that starts out as
* 'enumerating' and switches to 'complete' when the enumeration is done. You
* can cancel a pending enumeration by passing this object to the
* cancelEnumeration() method. This switches the state to 'cancelling' and then
* it switches to 'cancelled' when the cancellation is complete. If you call
* cancelEnumeration(), the callback function you passed to enumerate() is
* guaranteed not to be called again.
*
* In addition to enumerate(), there are two other methods you can use
* to enumerate database entries:
*
* enumerateAll() takes the same arguments and returns the same values
* as enumerate(), but it batches the results and passes them in an
* array to the callback function.
*
* getAll() takes a callback argument and passes it an array of all
* entries in the database, sorted by filename. It does not allow you
* to specify a key, range, or direction, but if you need all entries
* from the database, this method is is much faster than enumerating
* entries individually.
*
* FILESYSTEM CHANGES
*
* When media files are added or removed, MediaDB reports this by triggering
* 'created' and 'deleted' events.
*
* When a 'created' event is fired, the detail property of the event is an
* array of database record objects. When a single file is created (for
* example when the user takes a picture with the Camera app) this array has
* only a single element. But when MediaDB scans for new files (see SCANNING
* below) it may batch multiple records into a single created event. If a
* 'created' event has many records, apps may choose to simply rebuild their
* UI from scratch with a new call to enumerate() instead of handling the new
* files one at a time.
*
* When a 'deleted' event is fired, the detail property of the event is an
* array of the names of the files that have been deleted. As with 'created'
* events, the array may have a single element or may have many batched
* elements.
*
* If MediaDB detects that a file has been modified in place (because its
* size or date changes) it treats this as a deletion of the old version and
* the creation of a new version, and will fire a deleted event followed by
* a created event.
*
* The created and deleted events are not triggered until the corresponding
* files have actually been created and deleted and their database records
* have been updated.
*
* SCANNING
*
* MediaDB automatically scans for new and deleted files every time it enters
* the MediaDB.READY state. This happens when the MediaDB object is first
* created, and also when an SD card is removed and reinserted or when the
* user finishes a USB Mass Storage session. If the scan finds new files, it
* reports them with one or more 'created' events. If the scan finds that
* files have been deleted, it reports them with one or more 'deleted' events.
*
* MediaDB fires a 'scanstart' event when a scan begins and fires a 'scanend'
* event when the scan is complete. Apps can use these events to let the user
* know that a scan is in progress.
*
* The scan algorithm attempts to quickly look for new files and reports those
* first. It then begins a slower full scan phase where it checks that each of
* the files it already knows about is still present.
*
* EVENTS
*
* As described above, MediaDB sends events to communicate with the apps
* that use it. The event types and their meanings are:
*
* Event Meaning
* --------------------------------------------------------------------------
* ready MediaDB is ready for use. Also fired when new volumes added.
* enumerable Fired when DB can be enumerated but before fully ready
* unavailable MediaDB is unavailable (often because of USB file transfer)
* created One or more files were created
* deleted One or more files were deleted
* scanstart MediaDB is scanning
* scanend MediaDB has finished scanning
* cardremoved A volume became permanently unavailable.
* Only fired on devices that have internal storage and a card
*
* Because MediaDB is a JavaScript library, these are not real DOM events, but
* simulations.
*
* MediaDB defines two-argument versions of addEventListener() and
* removeEventListener() and also allows you to define event handlers by
* setting 'on' properties like 'onready' and 'onscanstart'.
*
* The objects passed on MediaDB event handlers are not true Event objects but
* simulate a CustomEvent by defining type, target, currentTarget, timestamp
* and detail properties. For MediaDB events, it is the detail property that
* always holds the useful information. These simulated event objects do not
* have preventDefault(), stopPropagation() or stopImmediatePropagation()
* methods.
*
* MediaDB events do not bubble and cannot be captured.
*
* INTERNAL AND EXTERNAL STORAGE
*
* Some devices have internal storage and also external (sdcard) storage.
* MediaDB hides this from apps, for the most part. There are some
* idiosyncracies to be aware of, however. With more than one device storage
* area available, MediaDB can remain available even when an sdcard is
* removed. When this happens we send a 'cardremoved' event instead of
* an 'unavailable' event. And if there were files on that card, the
* cardremoved event is followed by a series of deleted events for all of
* the files.
*
* If a card is inserted, we just send a 'ready' event, and start a new scan,
* even if we were already in the MediaDB.READY state.
*
* The situation is slightly different when one of the two storage areas is
* unmounted so it can be shared by USB, however. In this case, the files
* are only temporarily unavailable, and it doesn't make sense to delete
* them and then rescan everything when the volume is mounted again. So instead,
* when either of the storage areas is shared via USB, MediaDB sends its
* 'unavailable' event.
*
* METHODS
*
* MediaDB defines the following methods:
*
* - addEventListener(): register a function to call when an event is fired
*
* - removeEventListener(): unregister an event listener function
*
* - enumerate(): for each file that MediaDB knows about, pass its database
* record object to the specified callback. By default, records are returned
* in alphabetical order by name, but optional arguments allow you to
* specify a database index, a key range, and a sort direction.
*
* - cancelEnumeration(): stops an enumeration in progress. Pass the object
* returned by enumerate().
*
* - getFile(): given a filename and a callback, this method looks up the
* named file in DeviceStorage and passes it (a Blob) to the callback.
* An error callback is available as an optional third argument.
*
* - getFileInfo(): given a filename and a callback, this method looks up
* the database record for that file and passes it to the callback. If
* no such record exists and an error callback was passed as the 3rd
* argument, then an error message is passed to that error callback.
* Note that unlike getFile() this method does not return file content.
*
* - count(): count the number of records in the database and pass the value
* to the specified callback. Like enumerate(), this method allows you
* to specify the name of an index and a key range if you only want to
* count some of the records.
*
* - updateMetadata(): updates the metadata associated with a named file
*
* - addFile(): given a filename and a blob this method saves the blob as a
* named file to device storage.
*
* - deleteFile(): deletes the named file from device storage and the database
*
* - close(): closes the IndexedDB connections and stops listening to
* DeviceStorage events. This permanently puts the MediaDB object into
* the MediaDB.CLOSED state in which it is unusable.
*
* - freeSpace(): call the DeviceStorage freeSpace() method and pass the
* result to the specified callback
*/
(function(exports) {
function MediaDB(mediaType, metadataParser, options) {
this.mediaType = mediaType;
this.metadataParser = metadataParser;
if (!options) {
options = {};
}
this.indexes = options.indexes || [];
this.version = options.version || 1;
this.mimeTypes = options.mimeTypes;
this.autoscan = (options.autoscan !== undefined) ? options.autoscan : true;
this.state = MediaDB.OPENING;
this.scanning = false; // becomes true while scanning
this.initialScanComplete = false; // becomes true once endscan is called
this.parsingBigFiles = false;
// These are for data upgrade from the client.
this.updateRecord = options.updateRecord;
this.reparsedRecord = options.reparsedRecord;
if (options.excludeFilter && (options.excludeFilter instanceof RegExp)) {
// only regular expression object is accepted.
this.clientExcludeFilter = options.excludeFilter;
}
// While scanning, we attempt to send change events in batches.
// After finding a new or deleted file, we'll wait this long before
// sending events in case we find another new or deleted file right away.
this.batchHoldTime = options.batchHoldTime || 100;
// But we'll send a batch of changes right away if it gets this big
// A batch size of 0 means no maximum batch size
this.batchSize = options.batchSize || 0;
this.dbname = 'MediaDB/' + this.mediaType + '/';
var media = this; // for the nested functions below
// Private implementation details in this object
this.details = {
// This maps event type -> array of listeners
// See addEventListener and removeEventListener
eventListeners: {},
// Properties for queuing up db insertions and deletions and also
// for queueing up notifications to be sent
pendingInsertions: [], // Array of filenames to insert
pendingDeletions: [], // Array of filenames to remove
whenDoneProcessing: [], // Functions to run when queue is empty
pendingCreateNotifications: [], // Array of fileinfo objects
pendingDeleteNotifications: [], // Ditto
pendingNotificationTimer: null,
// This property holds the modification date of the newest file we have.
// We need to know the newest file in order to look for newer ones during
// scanning. We initialize newestFileModTime during initialization by
// actually checking the database (using the date index). We also update
// this property every time a new record is added to the database.
newestFileModTime: 0
};
// Define a dummy metadata parser if we're not given one
if (!this.metadataParser) {
this.metadataParser = function(file, callback) {
setTimeout(function() { callback({}); }, 0);
};
}
// Open the database
// Note that the user can upgrade the version and we can upgrade the version
// DB Version is a 32bits unsigned short: upper 16bits is client app db
// number, lower 16bits is MediaDB version number.
var dbVersion = (0xFFFF & this.version) << 16 | (0xFFFF & MediaDB.VERSION);
var openRequest = indexedDB.open(this.dbname,
dbVersion);
// This should never happen for Gaia apps
openRequest.onerror = function(e) {
console.error('MediaDB():', openRequest.error.name);
};
// This should never happen for Gaia apps
openRequest.onblocked = function(e) {
console.error('indexedDB.open() is blocked in MediaDB()');
};
// This is where we create (or delete and recreate) the database
openRequest.onupgradeneeded = function(e) {
var db = openRequest.result;
// read transaction from event for data manipulation (read/write).
var transaction = e.target.transaction;
var oldVersion = e.oldVersion;
// translate to db version and client version.
var oldDbVersion = 0xFFFF & oldVersion;
var oldClientVersion = 0xFFFF & (oldVersion >> 16);
// if client version is 0, oldVersion is the version number prior to
// bug 891797. The MediaDB.VERSION may be 2, and other parts is client
// version.
if (oldClientVersion === 0) {
oldDbVersion = 2;
oldClientVersion = oldVersion / oldDbVersion;
}
if (0 === db.objectStoreNames.length) {
// No objectstore found. It is the first time use MediaDB, we need to
// create it.
createObjectStores(db);
} else {
// ObjectStore found, we need to upgrade data for both client upgrade
// and mediadb upgrade.
handleUpgrade(db, transaction, oldDbVersion, oldClientVersion);
}
};
// This is called when we've got the database open and ready.
openRequest.onsuccess = function(e) {
media.db = openRequest.result;
// Log any errors that propagate up to here
media.db.onerror = function(event) {
console.error('MediaDB: ',
event.target.error && event.target.error.name);
};
// At this point, the db is open and can be queried. We have not
// checked device storage yet, so we are not fully ready, but apps
// that need to enumerate existing files before scanning for new files
// can start that enumeration now.
changeState(media, MediaDB.ENUMERABLE);
// Query the db to find the modification time of the newest file
var cursorRequest =
media.db.transaction('files', 'readonly')
.objectStore('files')
.index('date')
.openCursor(null, 'prev');
cursorRequest.onerror = function() {
// If anything goes wrong just display an error.
// If this fails, don't even attempt error recovery
console.error('MediaDB initialization error', cursorRequest.error);
};
cursorRequest.onsuccess = function() {
var cursor = cursorRequest.result;
if (cursor) {
media.details.newestFileModTime = cursor.value.date;
}
else {
// No files in the db yet, so use a really old time
media.details.newestFileModTime = 0;
}
// The DB is initialized, and we've got our mod time
// so move on and initialize device storage
initDeviceStorage();
};
};
// helper function to create all indexes
function createObjectStores(db) {
// Now build the database
var filestore = db.createObjectStore('files', { keyPath: 'name' });
// Always index the files by modification date
filestore.createIndex('date', 'date');
// And index them by any other file properties or metadata properties
// passed to the constructor
media.indexes.forEach(function(indexName) {
// Don't recreate indexes we've already got
if (indexName === 'name' || indexName === 'date') {
return;
}
// the index name is also the keypath
filestore.createIndex(indexName, indexName);
});
}
// helper function to list all files and invoke callback with db, trans,
// dbfiles, db version, client version as arguments.
function enumerateOldFiles(store, callback) {
var openCursorReq = store.openCursor();
openCursorReq.onsuccess = function() {
var cursor = openCursorReq.result;
if (cursor) {
callback(cursor.value);
cursor.continue();
}
};
}
function handleUpgrade(db, trans, oldDbVersion, oldClientVersion) {
// change state to upgrading that client apps may use it.
media.state = MediaDB.UPGRADING;
var evtDetail = {'oldMediaDBVersion': oldDbVersion,
'oldClientVersion': oldClientVersion,
'newMediaDBVersion': MediaDB.VERSION,
'newClientVersion': media.version};
// send upgrading event
dispatchEvent(media, 'upgrading', evtDetail);
// The upgrade contains upgrading indexes and upgrading data.
var store = trans.objectStore('files');
// Part 1: upgrading indexes
if (media.version != oldClientVersion) {
// upgrade indexes changes from client app.
upgradeIndexesChanges(store);
}
var clientUpgradeNeeded = (media.version != oldClientVersion) &&
media.updateRecord;
// checking if we need to enumerate all files. This may improve the
// performance of only changing indexes. If client app changes indexes,
// they may not need to update records. In this case, we don't need to
// enumerate all files.
if ((2 != oldDbVersion || 3 != MediaDB.VERSION) && !clientUpgradeNeeded) {
return;
}
// Part 2: upgrading data
enumerateOldFiles(store, function doUpgrade(dbfile) {
// handle mediadb upgrade from 2 to 3
if (2 == oldDbVersion && 3 == MediaDB.VERSION) {
upgradeDBVer2to3(store, dbfile);
}
// handle client upgrade
if (clientUpgradeNeeded) {
handleClientUpgrade(store, dbfile, oldClientVersion);
}
});
}
function upgradeIndexesChanges(store) {
var dbIndexes = store.indexNames; // note: it is DOMStringList not array.
var clientIndexes = media.indexes;
for (var i = 0; i < dbIndexes.length; i++) {
// indexes provided by mediadb, can't remove it.
if ('name' === dbIndexes[i] || 'date' === dbIndexes[i]) {
continue;
}
if (clientIndexes.indexOf(dbIndexes[i]) < 0) {
store.deleteIndex(dbIndexes[i]);
}
}
for (i = 0; i < clientIndexes.length; i++) {
if (!dbIndexes.contains(clientIndexes[i])) {
store.createIndex(clientIndexes[i], clientIndexes[i]);
}
}
}
function upgradeDBVer2to3(store, dbfile) {
// if record is already starting with '/', don't update them.
if (dbfile.name[0] === '/') {
return;
}
store.delete(dbfile.name);
dbfile.name = '/sdcard/' + dbfile.name;
store.add(dbfile);
}
function handleClientUpgrade(store, dbfile, oldClientVersion) {
try {
dbfile.metadata = media.updateRecord(dbfile, oldClientVersion,
media.version);
if (dbfile.needsReparse && !media.reparsedRecord) {
console.warn(
'client app requested reparse, but no reparsedRecord was set'
);
delete dbfile.needsReparse;
}
store.put(dbfile);
} catch (ex) {
// discard client upgrade error, client app should handle it.
console.warn('client app updates record, ' + dbfile.name +
', failed: ' + ex.message);
}
}
function initDeviceStorage() {
var details = media.details;
// Get the individual device storage objects, so that we can listen
// for events on the different volumes separately.
details.storages = navigator.getDeviceStorages(mediaType);
details.availability = {};
// Start off by getting the initial availablility of the storage areas
// This is an async function that will call the next initialization
// step when it is done.
getStorageAvailability();
// This is an asynchronous step in the db initialization process
function getStorageAvailability() {
var next = 0;
getNextAvailability();
function getNextAvailability() {
if (next >= details.storages.length) {
// We've gotten the availability of all storage areas, so
// move on to the next step.
setupHandlers();
return;
}
var s = details.storages[next++];
var name = s.storageName;
var req = s.available();
req.onsuccess = function(e) {
details.availability[name] = req.result;
getNextAvailability();
};
req.onerror = function(e) {
details.availability[name] = 'unavailable';
getNextAvailability();
};
}
}
function setupHandlers() {
// Now that we know the state of all of the storage areas, register
// an event listener to monitor changes to that state.
for (var i = 0; i < details.storages.length; i++) {
details.storages[i].addEventListener('change', changeHandler);
}
// Remember the listener so we can remove it in stop()
details.dsEventListener = changeHandler;
// Move on to the next step
sendInitialEvent();
}
function sendInitialEvent() {
// Get our current state based on the device storage availability
var state = getState(details.availability);
// Switch to that state and send an appropriate event
changeState(media, state);
// If the state is ready, and we're auto scanning then start a scan
if (media.autoscan) {
scan(media);
}
}
// Given a storage name -> availability map figure out what state
// the mediadb object should be in
function getState(availability) {
var n = 0; // total number of storages
var a = 0; // # that are available
var u = 0; // # that are unavailable
var s = 0; // # that are shared
for (var name in availability) {
n++;
switch (availability[name]) {
case 'available':
a++;
break;
case 'unavailable':
u++;
break;
case 'shared':
s++;
break;
}
}
// If any volume is shared, then behave as if they are all shared
// and make the entire MediaDB shared. This is because shared volumes
// are generally shared transiently and most files on the volume will
// probably still be there when the volume comes back. If we want to
// keep the MediaDB available while one volume is shared we have to
// rescan and discard all the files on the shared volume, which means
// it will take much longer to recover when the volume comes back. So
// it is better to just act as if all volumes are shared together
if (s > 0) {
return MediaDB.UNMOUNTED;
}
// If all volumes are unavailable, then MediaDB is unavailable
if (u === n) {
return MediaDB.NOCARD;
}
// Otherwise, there is at least one available volume, so MediaDB
// is available.
return MediaDB.READY;
}
function changeHandler(e) {
switch (e.reason) {
case 'modified':
case 'deleted':
fileChangeHandler(e);
return;
case 'available':
case 'unavailable':
case 'shared':
volumeChangeHandler(e);
return;
default: // we ignore created events and handle modified instead.
return;
}
}
function volumeChangeHandler(e) {
var storageName = e.target.storageName;
// If nothing changed, ignore this event
if (details.availability[storageName] === e.reason) {
return;
}
var oldState = media.state;
// Record the new availability of the volume that changed.
details.availability[storageName] = e.reason;
// And figure out what our new state is
var newState = getState(details.availability);
// If the state changed, send out an event about it
if (newState !== oldState) {
changeState(media, newState);
// Start scanning if we're available, and cancel scanning otherwise
if (newState === MediaDB.READY) {
if (media.autoscan) {
scan(media);
}
}
else {
endscan(media);
}
}
else if (newState === MediaDB.READY) {
// In this case, the state did not change. But we may still need to
// send out an event. If both states are READY, then the user
// just inserted or removed an sdcard. If the user just added a
// card, then we want to send another available event and start a
// scan. If the user just removed a card then we need to immediately
// tell the client that happened so the music app (for example) can
// stop playing. If it is playing a file that just disappeared it is
// in danger of crashing. Also, in this case we must delete the
// records (and send events) for all of the files on that card.
if (e.reason === 'available') {
// An SD card was just inserted, so send another ready event.
dispatchEvent(media, 'ready');
// And if we're automatically scanning, start the scan now.
// It would be more efficient if the scan() function could scan
// just one storage area at a time. But SD card insertion should
// be rare enough that efficiency is not so important.
if (media.autoscan) {
scan(media);
}
}
else if (e.reason === 'unavailable') {
// An SD card was just removed. First send an event.
dispatchEvent(media, 'cardremoved');
// Now figure out all the files we know about that were on that
// volume and remove their records from the database and send events
// to the client.
deleteAllFiles(storageName);
}
}
}
function fileChangeHandler(e) {
var filename = e.path;
if (ignoreName(media, filename)) {
return;
}
// insertRecord and deleteRecord will send events to the client once
// the db has been updated.
if (e.reason === 'modified') {
insertRecord(media, filename);
} else {
deleteRecord(media, filename);
}
}
// Enumerate all entries in the DB and call deleteRecord for any whose
// filename begins with the specified storageName
function deleteAllFiles(storageName) {
var storagePrefix = storageName ? '/' + storageName + '/' : '';
var store = media.db.transaction('files').objectStore('files');
var cursorRequest = store.openCursor();
cursorRequest.onsuccess = function() {
var cursor = cursorRequest.result;
if (cursor) {
if (cursor.value.name.startsWith(storagePrefix)) {
// This will generate an event to notify the client that the
// file is now gone.
deleteRecord(media, cursor.value.name);
}
cursor.continue();
}
};
}
}
}
MediaDB.prototype = {
close: function close() {
// Close the database
this.db.close();
// There is no way to close device storage, but we at least want
// to stop receiving events from it.
for (var i = 0; i < this.details.storages.length; i++) {
var s = this.details.storages[i];
s.removeEventListener('change', this.details.dsEventListener);
}
// Change state and send out an event
changeState(this, MediaDB.CLOSED);
},
addEventListener: function addEventListener(type, listener) {
if (!this.details.eventListeners.hasOwnProperty(type)) {
this.details.eventListeners[type] = [];
}
var listeners = this.details.eventListeners[type];
if (listeners.indexOf(listener) !== -1) {
return;
}
listeners.push(listener);
},
removeEventListener: function removeEventListener(type, listener) {
if (!this.details.eventListeners.hasOwnProperty(type)) {
return;
}
var listeners = this.details.eventListeners[type];
var position = listeners.indexOf(listener);
if (position === -1) {
return;
}
listeners.splice(position, 1);
},
// Look up the database record for the specfied filename and pass it
// to the specified callback.
getFileInfo: function getFile(filename, callback, errback) {
if (this.state === MediaDB.OPENING) {
throw Error('MediaDB is not ready. State: ' + this.state);
}
var media = this;
// First, look up the fileinfo record in the db
var read = media.db.transaction('files', 'readonly')
.objectStore('files')
.get(filename);
read.onerror = function() {
var msg = 'MediaDB.getFileInfo: unknown filename: ' + filename;
if (errback) {
errback(msg);
} else {
console.error(msg);
}
};
read.onsuccess = function() {
if (callback) {
callback(read.result);
}
};
},
// Look up the specified filename in DeviceStorage and pass the
// resulting File object to the specified callback.
getFile: function getFile(filename, callback, errback) {
if (this.state !== MediaDB.READY) {
throw Error('MediaDB is not ready. State: ' + this.state);
}
var storage = navigator.getDeviceStorage(this.mediaType);
var getRequest = storage.get(filename);
getRequest.onsuccess = function() {
callback(getRequest.result);
};
getRequest.onerror = function() {
var errmsg = getRequest.error && getRequest.error.name;
if (errback) {
errback(errmsg);
} else {
console.error('MediaDB.getFile:', errmsg);
}
};
},
// Delete the named file from device storage.
// This will cause a device storage change event, which will cause
// mediadb to remove the file from the database and send out a
// mediadb change event, which will notify the application UI.
deleteFile: function deleteFile(filename) {
if (this.state !== MediaDB.READY) {
throw Error('MediaDB is not ready. State: ' + this.state);
}
var storage = navigator.getDeviceStorage(this.mediaType);
storage.delete(filename).onerror = function(e) {
console.error('MediaDB.deleteFile(): Failed to delete', filename,
'from DeviceStorage:', e.target.error);
};
},