Skip to content

Instantly share code, notes, and snippets.

@juanghurtado
Created January 9, 2014 09:33
Show Gist options
  • Save juanghurtado/8331694 to your computer and use it in GitHub Desktop.
Save juanghurtado/8331694 to your computer and use it in GitHub Desktop.
Mock Firefox OS Device Storage API. Note that now we only mock enumerate() method here.
# -----------------------------------------------------------------------------
# UTILS
# -----------------------------------------------------------------------------
convertBase64ToBinary = (base64) ->
raw = window.atob base64
rawLength = raw.length
array = new Uint8Array(new ArrayBuffer(rawLength))
i = 0
while i < rawLength
array[i] = raw.charCodeAt(i)
i++
return array
# -----------------------------------------------------------------------------
# CLASSES
# -----------------------------------------------------------------------------
# Cursor class
# ------------------------
class Cursor
ix : -1
results : {}
constructor: (blobs) ->
@blobs = blobs
@__defineGetter__ 'result', =>
@results[@.ix]
continue : =>
ix = ++@.ix
blob = @blobs[Object.keys(@blobs)[ix]]
if not blob
@results[ix] = null
@done = true
setTimeout =>
@onsuccess()
return
decoded = new Blob([convertBase64ToBinary(blob)], type: 'image/png')
decoded.name = "file#{ix}.png"
decoded.lastModifiedDate = new Date()
@results[ix] = decoded
setTimeout =>
@onsuccess()
# Cursor class
# ------------------------
class DeviceStorage
constructor: (mediaType, blobs) ->
defaultBlobs =
'file0.png' : 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAABbSURBVCjPY/jPgB8yDCkFB/7v+r/5/+r/i/7P+N/3DYuC7V93/d//fydQ0Zz/9eexKFgtsejLiv8b/8/8X/WtUBGrGyZLdH6f8r/sW64cTkdWSRS+zpQbgiEJAI4UCqdRg1A6AAAAAElFTkSuQmCC'
'file1.png' : 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAABbSURBVCjPY/jPgB8yDCkFB/7v+r/5/+r/i/7P+N/3DYuC7V93/d//fydQ0Zz/9eexKFgtsejLiv8b/8/8X/WtUBGrGyZLdH6f8r/sW64cTkdWSRS+zpQbgiEJAI4UCqdRg1A6AAAAAElFTkSuQmCC'
@mediaType = mediaType
@blobs = blobs or defaultBlobs
enumerate : ->
cursor = new Cursor(@blobs)
cont = ->
cursor.continue()
setTimeout cont, 1000
return cursor
# -----------------------------------------------------------------------------
# SHIM INIT
# -----------------------------------------------------------------------------
getDeviceStorage = (mediaType) ->
new DeviceStorage(mediaType)
window.navigator.__defineGetter__ 'getDeviceStorage', ->
getDeviceStorage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment