(function (factory) { if (typeof define === 'function' && define.amd) { // AMD define('condo-abstract-md5', ['jquery', 'condo-broadcaster'], factory); } else { // Browser global factory(jQuery); } }(function ($, uploads, undefined) { 'use strict'; angular.module('CondoAbstractMd5', ['CondoBroadcaster']) .factory('Condo.Md5', ['$rootScope', '$q', 'Condo.Broadcast', function($rootScope, $q, broadcaster) { var hasher, queue = [], ready = false, processing = undefined, // // Resolves the hashing promise // recievedMessage = function(e) { if(e.data.success) { processing.result.resolve(e.data.result); } else { processing.result.reject(e.data.result); } processing = undefined; processNext(); if(!$rootScope.$$phase) { $rootScope.$apply(); // This triggers the promise response } }, // // starts processing the next item if the queue is not empty // processNext = function() { if(ready && processing === undefined && queue.length > 0) { processing = queue.pop(); hasher.postMessage(processing.blob); } }; if(!!window.Worker) { hasher = new Worker('<%= asset_path("condo/md5/hash.worker.js") %>'); hasher.onmessage = recievedMessage; hasher.onerror = function(e) { ready = false; broadcaster.broadcast('coComponentLoadFailed', ['MD5', 'file fingerprinting']); // Critical error }; ready = true; } else { $.getScript('<%= asset_path("condo/md5/hash.worker.emulator.js") %>', function() { hasher = new CondoHashWorkerEmulator(recievedMessage); ready = true; processNext(); // It is possible }).fail(function(jqxhr, settings, exception) { broadcaster.broadcast('coComponentLoadFailed', ['MD5', 'file fingerprinting']); }); } return { // // Will queue a start message and return the hash result // hash: function(blob) { var result = $q.defer(); queue.push({ blob: blob, result: result }); processNext(); return result.promise; } }; }]); }));