-
Notifications
You must be signed in to change notification settings - Fork 10
/
sample.coffee
197 lines (161 loc) · 6.66 KB
/
sample.coffee
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
############################################################################
# Copyright (C) 2014-2016 by Vaughn Iverson
# meteor-file-sample-app is free software released under the MIT/X11 license.
# See included LICENSE file for details.
############################################################################
# Both client and server
# Default collection name is 'fs'
myData = FileCollection({
resumable: true, # Enable the resumable.js compatible chunked file upload interface
resumableIndexName: 'test', # Don't use the default MongoDB index name, which is 94 chars long
http: [ { method: 'get', path: '/md5/:md5', lookup: (params, query) -> return { md5: params.md5 }}]}
# Define a GET API that uses the md5 sum id files
)
############################################################
# Client-only code
############################################################
if Meteor.isClient
# This assigns a file drop zone to the "file table"
# once DOM is ready so jQuery can see it
Template.collTest.onRendered ->
myData.resumable.assignDrop $('.fileDrop')
return
Meteor.startup () ->
################################
# Setup resumable.js in the UI
# When a file is added
myData.resumable.on 'fileAdded', (file) ->
# Keep track of its progress reactivaly in a session variable
Session.set file.uniqueIdentifier, 0
# Create a new file in the file collection to upload to
myData.insert({
_id: file.uniqueIdentifier # This is the ID resumable will use
filename: file.fileName
contentType: file.file.type
},
(err, _id) ->
if err
console.warn "File creation failed!", err
return
# Once the file exists on the server, start uploading
myData.resumable.upload()
)
# Update the upload progress session variable
myData.resumable.on 'fileProgress', (file) ->
Session.set file.uniqueIdentifier, Math.floor(100*file.progress())
# Finish the upload progress in the session variable
myData.resumable.on 'fileSuccess', (file) ->
Session.set file.uniqueIdentifier, undefined
# More robust error handling needed!
myData.resumable.on 'fileError', (file) ->
console.warn "Error uploading", file.uniqueIdentifier
Session.set file.uniqueIdentifier, undefined
# Set up an autorun to keep the X-Auth-Token cookie up-to-date and
# to update the subscription when the userId changes.
Tracker.autorun () ->
userId = Meteor.userId()
Meteor.subscribe 'allData', userId
$.cookie 'X-Auth-Token', Accounts._storedLoginToken(),
path: '/'
#####################
# UI template helpers
shorten = (name, w = 16) ->
w += w % 4
w = (w-4)/2
if name.length > 2*w
name[0..w] + '…' + name[-w-1..-1]
else
name
truncateId = (id, length = 6) ->
if id
if typeof id is 'object'
id = "#{id.valueOf()}"
"#{id.substr(0,6)}…"
else
""
Template.registerHelper "truncateId", truncateId
Template.collTest.events
# Wire up the event to remove a file by clicking the `X`
'click .del-file': (e, t) ->
# If there's an active upload, cancel it
if Session.get "#{this._id}"
console.warn "Cancelling active upload to remove file! #{this._id}"
myData.resumable.removeFile(myData.resumable.getFromUniqueIdentifier "#{this._id}")
# Then just remove the file
myData.remove {_id: this._id}
Template.collTest.helpers
dataEntries: () ->
# Reactively populate the table
myData.find({})
shortFilename: (w = 16) ->
if this.filename?.length
shorten this.filename, w
else
"(no filename)"
owner: () ->
this.metadata?._auth?.owner
id: () ->
"#{this._id}"
link: () ->
myData.baseURL + "/md5/" + this.md5
uploadStatus: () ->
percent = Session.get "#{this._id}"
unless percent?
"Processing..."
else
"Uploading..."
formattedLength: () ->
numeral(this.length).format('0.0b')
uploadProgress: () ->
percent = Session.get "#{this._id}"
isImage: () ->
types =
'image/jpeg': true
'image/png': true
'image/gif': true
'image/tiff': true
types[this.contentType]? and this.md5 isnt 'd41d8cd98f00b204e9800998ecf8427e'
loginToken: () ->
Meteor.userId()
Accounts._storedLoginToken()
userId: () ->
Meteor.userId()
############################################################
# Server-only code
############################################################
if Meteor.isServer
Meteor.startup () ->
# Only publish files owned by this userId, and ignore temp file chunks used by resumable
Meteor.publish 'allData', (clientUserId) ->
# This prevents a race condition on the client between Meteor.userId() and subscriptions to this publish
# See: https://stackoverflow.com/questions/24445404/how-to-prevent-a-client-reactive-race-between-meteor-userid-and-a-subscription/24460877#24460877
if this.userId is clientUserId
return myData.find({ 'metadata._Resumable': { $exists: false }, 'metadata._auth.owner': this.userId })
else
return []
# Don't allow users to modify the user docs
Meteor.users.deny({update: () -> true })
# Allow rules for security. Without these, no writes would be allowed by default
myData.allow
insert: (userId, file) ->
# Assign the proper owner when a file is created
file.metadata = file.metadata ? {}
file.metadata._auth =
owner: userId
true
remove: (userId, file) ->
# Only owners can delete
if file.metadata?._auth?.owner and userId isnt file.metadata._auth.owner
return false
true
read: (userId, file) ->
# Only owners can GET file data
if file.metadata?._auth?.owner and userId isnt file.metadata._auth.owner
return false
true
write: (userId, file, fields) -> # This is for the HTTP REST interfaces PUT/POST
# All client file metadata updates are denied, implement Methods for that...
# Only owners can upload a file
if file.metadata?._auth?.owner and userId isnt file.metadata._auth.owner
return false
true