2015-08-31 17:42:21 +02:00
|
|
|
angular.module('ponyfm').factory('upload', [
|
2015-10-25 03:35:37 +01:00
|
|
|
'$rootScope'
|
|
|
|
($rootScope) ->
|
|
|
|
self =
|
|
|
|
queue: []
|
2015-08-31 17:42:21 +02:00
|
|
|
|
2015-10-25 03:35:37 +01:00
|
|
|
upload: (files) ->
|
|
|
|
_.each files, (file) ->
|
|
|
|
upload =
|
|
|
|
name: file.name
|
|
|
|
progress: 0
|
|
|
|
uploadedSize: 0
|
|
|
|
size: file.size
|
|
|
|
index: self.queue.length
|
|
|
|
isUploading: true
|
|
|
|
success: false
|
|
|
|
error: null
|
2015-08-31 17:42:21 +02:00
|
|
|
|
2015-10-25 03:35:37 +01:00
|
|
|
self.queue.push upload
|
|
|
|
$rootScope.$broadcast 'upload-added', upload
|
2015-08-31 17:42:21 +02:00
|
|
|
|
2015-10-25 03:35:37 +01:00
|
|
|
xhr = new XMLHttpRequest()
|
|
|
|
xhr.upload.onprogress = (e) ->
|
|
|
|
$rootScope.$apply ->
|
|
|
|
upload.uploadedSize = e.loaded
|
|
|
|
upload.progress = e.loaded / upload.size * 100
|
|
|
|
$rootScope.$broadcast 'upload-progress', upload
|
2015-08-31 17:42:21 +02:00
|
|
|
|
2015-10-25 03:35:37 +01:00
|
|
|
xhr.onload = -> $rootScope.$apply ->
|
|
|
|
upload.isUploading = false
|
|
|
|
if xhr.status != 200
|
|
|
|
error =
|
|
|
|
if xhr.getResponseHeader('content-type') == 'application/json'
|
|
|
|
$.parseJSON(xhr.responseText).errors.track.join ', '
|
|
|
|
else
|
|
|
|
'There was an unknown error!'
|
2015-08-31 17:42:21 +02:00
|
|
|
|
2015-10-25 03:35:37 +01:00
|
|
|
upload.error = error
|
|
|
|
$rootScope.$broadcast 'upload-error', [upload, error]
|
|
|
|
else
|
|
|
|
upload.success = true
|
|
|
|
upload.trackId = $.parseJSON(xhr.responseText).id
|
2015-08-31 17:42:21 +02:00
|
|
|
|
2015-10-25 03:35:37 +01:00
|
|
|
$rootScope.$broadcast 'upload-finished', upload
|
|
|
|
formData = new FormData();
|
|
|
|
formData.append('track', file);
|
2015-08-31 17:42:21 +02:00
|
|
|
|
2015-10-25 03:35:37 +01:00
|
|
|
xhr.open 'POST', '/api/web/tracks/upload', true
|
|
|
|
xhr.setRequestHeader 'X-CSRF-Token', pfm.token
|
|
|
|
xhr.send formData
|
2015-09-13 04:19:45 +02:00
|
|
|
])
|