/
weeve.js
542 lines (465 loc) · 16.8 KB
/
weeve.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
$(function() {
// alert on flaky network connections
if (!(window.Keen && window.Firebase)) {
alert("One of more files needed by weeve could not \
be downloaded. Please reload the page and try again.")
}
var Weeve = {}
// Use the app's namespace as an event aggregator
_.extend(Weeve, Backbone.Events)
// Configuration variables - set according to your environment
var weeveUrl = "", //where you are deploying, or localhost
firebaseUrl = "", // A Firebase URL
singlyApiHost = "https://api.singly.com", // Default, change if hosting your own
singlyClientId = "", // Client ID of a Singly app
keenProjectId = "", // Project ID of a Keen project
keenApiKey = "", // API Key of a Keen project
twitterStreamProxy = "" // URL of a twitter proxy
// Other variables used throughout the script
var currentUser, currentUserAuth,
firebase = new Firebase(firebaseUrl)
tweets = new Backbone.Collection(),
users = new Backbone.Collection()
// *** Pre-routing setup
// proxy online and offline events to keep
// event handling consistent
$(window).on("online", function() {
$("body").removeClass("offline")
Weeve.trigger("online")
})
$(window).on("offline", function() {
$("body").addClass("offline")
Weeve.trigger("offline")
})
// configure keen client
configureKeen()
// *** All helper functions in alphabetical order
// Attach child_added and child_removed events for users and tweets
function bindFirebaseListeners() {
var usersRef = firebase.child("users")
usersRef.on("child_added", function(user) {
users.add(user.val())
})
usersRef.on("child_removed", function(user) {
users.remove(users.get(user.val().id))
})
var tweetsRef = firebase.child("tweets")
tweetsRef.limit(50).on("child_added", function(tweet) {
tweets.add(tweet.val())
})
tweetsRef.on("child_removed", function(tweet) {
tweets.remove(tweets.get(tweet.val().id))
})
}
function configureKeen() {
if (window.Keen) {
Keen.configure(keenProjectId, keenApiKey)
Keen.setGlobalProperties(function(collection) {
// assign a non-identifying user id for progress (funnel) event correlation
if (collection === "progress") {
var anonUserId = localStorage.anonUserId
if (!anonUserId) {
anonUserId = localStorage.anonUserId =
Math.random().toString(36).substring(8)
}
return {
anonUserId: anonUserId
}
} else {
return {}
}
})
}
}
function listenForTweets() {
function startStream() {
// Send the data so the proxy can initiate the conversation
socket.emit("userstream", {
token: currentUserAuth.token.oauth_token,
secret: currentUserAuth.token.oauth_token_secret })
}
var socket = io.connect(twitterStreamProxy)
socket.once("connect", function() {
socket.on('tweet', function(tweet) {
if (tweet.id) { //Sometimes non-tweet messages are sent
if (!tweet.user.protected) { // No tweets from protected accounts
// Add extra data about whose stream this came from
tweet.weeve = {
source: {
screen_name: currentUser.screen_name,
image_url: currentUser.profile_image_url } }
// Save the tweet to firebase with the tweet id_str as its key
// This way, if 2 streams receive the same tweet, we don't duplicate it
// The first user to write it to Firebase wins, because
// we've set the Firebase rules to reject updates to tweets
firebase.child("tweets").child(tweet.id_str).
// We use the tweet's ascending, numeric id as our priority
// to keep things in order
setWithPriority(tweet, tweet.id)
// Log the tweeter and the streamer to keen
keen("tweets", {
source_screen_name: currentUser.screen_name,
tweet_screen_name: tweet.user.screen_name,
tweet_id: tweet.id
})
}
}
})
// tell the proxy we're ready to accept tweets!
startStream()
})
// on any reconnect we need to tell the proxy to start again
socket.on("reconnect", startStream)
// If the user logs out, kill the socket connection
Weeve.once("auth:logout", function() {
socket.disconnect()
})
}
// Creates a firebase user and binds a socket to a proxy for their stream
function connectUser() {
function _connectUser() {
// Get a reference to the current user via their screen name
var userRef = firebase.child("users").child(currentUser.screen_name)
// User account is deleted if the connection breaks
userRef.removeOnDisconnect()
// Add metadata so every client knows when this user joined
currentUser.weeve = { connected_at: new Date().toISOString() }
// Oldest users are ordered first
userRef.setWithPriority(currentUser, new Date().getTime())
// add a keen progress event
keen("progress", { step: "user_added_to_firebase" })
// add another for computing total # of unique users
// using a different collection so screen name
// remains unlinked to anonymous correlation id
// used in progress collection
keen("users", { step: "signed_in", screen_name: currentUser.screen_name })
// If the user logs out, remove the user
Weeve.once("auth:logout", function() {
userRef.remove()
})
// sometimes w/ reconnection a removeOnDisconnect event can
// happen for our user even after they've been reinstated
// here we listen for it, and if it happens we put the user back
// this can also happen if the user has another browser window open
// and disconnects from there, removing the user
userRef.on("value", function(dataSnapshot) {
if (dataSnapshot.val() == null) {
setTimeout(function() {
_connectUser()
}, 1000)
}
})
}
// Anytime a connection is restored, re-create the user
Weeve.on("online", _connectUser)
// Connect now
_connectUser()
}
// Draw keen charts related to users & steps
function drawUserMetrics() {
// How many unique users?
$("#total-weevers").empty()
new Keen.Metric("users", {
analysisType: "count_unique",
targetProperty: "screen_name"
}).draw($("#total-weevers")[0], {
label: "All-time weevers",
width: "100%"
})
}
// Draw keen charts related to tweets
function drawTweetMetrics() {
var chartWidth = 300, chartHeight = 250,
hours = 36e5
function timeframeSince(howLongAgo) {
return {
start: new Date(
new Date().getTime() - howLongAgo).toISOString(),
end: new Date().toISOString()
}
}
// Who's 'contributed' the most tweets?
$("#top-weevers").empty()
new Keen.Metric("tweets", {
analysisType: "count",
timeframe: timeframeSince(24 * hours),
groupBy: "source_screen_name"
}).draw($("#top-weevers")[0], {
width: chartWidth,
height: chartHeight,
showLegend: true,
title: "Top weevers today"
})
// Who's the most popular tweeter in the weeve?
$("#top-tweeters").empty()
new Keen.Metric("tweets", {
analysisType: "count",
timeframe: timeframeSince(24 * hours),
groupBy: "tweet_screen_name"
}).draw($("#top-tweeters")[0], {
width: chartWidth,
height: chartHeight,
showLegend: true,
title: "Top tweeters today"
})
// How many tweets in the last hour?
$("#tweet-series").empty()
new Keen.Series("tweets", {
analysisType: "count",
timeframe: "last_6_hours",
interval: "hourly"
}).draw($("#tweet-series")[0], {
width: chartWidth,
height: chartHeight,
showLegend: false,
title: "Tweets per hour"
})
// How many total tweets have been weeved?
$("#total-tweets").empty()
new Keen.Metric("tweets", {
analysisType: "count",
}).draw($("#total-tweets")[0], {
label: "All-time tweets",
width: "100%"
})
}
// Send data to keen, logging any errors
function keen(collection, data) {
if (window.Keen) {
Keen.addEvent(collection, data, function() {
}, function() {
console.log("couldn't publish to keen")
})
}
}
// placeholder html
function loadingHtml(text) {
return $("<h5>", { "class": "loading" }).html(
sprintf("Loading %s...", text))
}
// Log the firebase user out and clear localStorage,
// removing any Oauth information
function logout() {
firebase.unauth()
localStorage.clear()
// tell any component the user is no longer active on the page
Weeve.trigger("auth:logout")
// tell components to ask for new authentication again
Weeve.trigger("auth:get")
}
// *** All Backbone objects in alphabetical order
// Manages login / logout
var AuthView = Backbone.View.extend({
initialize: function(options) {
Weeve.on("auth:ready", _.bind(this.authReady, this))
Weeve.on("auth:get", _.bind(this.authGet, this))
},
events: {
"click .login": "onLoginClick",
"click .logout": "onLogoutClick"
},
loggedInTemplate: _.template($("#t-auth-logged-in").html()),
loggedOutTemplate: _.template($("#t-auth-logged-out").html()),
authGet: function() {
this.$el.html(this.loggedOutTemplate())
},
authReady: function() {
this.$el.html(this.loggedInTemplate(currentUser))
},
onLoginClick: function(event) {
event.preventDefault()
var singlyAuthUrl = sprintf(
"%s/oauth/authenticate?client_id=%s&redirect_uri=%s&service=%s&response_type=token",
singlyApiHost, singlyClientId, weeveUrl, "twitter")
document.location.href = singlyAuthUrl
},
onLogoutClick: function(event) {
event.preventDefault()
logout()
// only track voluntary logouts, not clean-ups
keen("progress", {step: "logout"})
}
})
// Manages individual tweets
var TweetView = Backbone.View.extend({
className: "tweet-view",
template: _.template($("#t-tweet").html()),
render: function() {
this.$el.html(this.template({tweet: this.model.toJSON(),
currentUser: currentUser || {}}))
this.$(".timeago").timeago()
return this
}
})
// Manages adding and removing to the list of tweets
var TweetListView = Backbone.View.extend({
className: "tweet-list-view",
initialize: function() {
var views = {}
this.collection.once("add", function() {
this.$(".loading").remove()
}, this)
this.collection.on("add", function(model) {
views[model.id] = (view = new TweetView({model: model}).render())
this.$el.prepend(view.$el)
}, this)
this.collection.on("remove", function(model) {
views[model.id].$el.remove()
delete views[model.id]
}, this)
},
render: function() {
this.$el.html(loadingHtml("tweets"))
return this
}
})
// Manages individual users
var UserView = Backbone.View.extend({
className: "user-view",
template: _.template($("#t-user").html()),
events: {
"click .toggle": "toggleScreenName"
},
render: function() {
this.$el.html(this.template(this.model.toJSON()))
this.$(".timeago").timeago()
this.$(".icon-info-sign").tooltip({title: _.bind(function() {
return sprintf("connected %s", this.$(".timeago").html())
}, this)})
return this
},
toggleScreenName: function(event) {
event.preventDefault()
var screenName = this.model.get("screen_name")
var hide = $(sprintf("#hide-style-%s", screenName))
if (hide.length > 0) {
hide.remove()
} else {
$(sprintf("<style type='text/css' id='hide-style-%s'>", screenName)).
html(sprintf("*[data-source-screen-name='%s'] { display: none }", screenName)).
appendTo($("head"))
}
$(event.currentTarget).toggleClass("deselected")
}
})
// Manages adding and removing to the list of users
var UserListView = Backbone.View.extend({
className: "user-list-view",
initialize: function() {
var views = {}
this.collection.once("add", function() {
this.$(".loading").remove()
}, this)
this.collection.on("add", function(model) {
views[model.id] = (view = new UserView({model: model}).render())
// start new people at the bottom
this.$el.append(view.$el)
}, this)
this.collection.on("remove", function(model) {
views[model.id].$el.remove()
delete views[model.id]
}, this)
},
render: function() {
this.$el.html(loadingHtml("weevers"))
return this
}
})
// ** Launch sequence
// Use a Backbone router as the entry point
new (Backbone.Router.extend({
routes: {
"": "index",
"firebase=:firebase&access_token=:access_token&account=:account": "firebase"
},
index: function() {
// Create an auth view, which will listen for auth events
new AuthView().render().$el.appendTo($("#auth-view"))
// Create a view to list users on the page
new UserListView({collection: users}).render().$el.appendTo($("#users-view"))
// Create a view to list tweets on the page
new TweetListView({collection: tweets}).render().$el.appendTo($("#tweets-view"))
// Bind the collections of these views to firebase so they get updates
bindFirebaseListeners()
// address flaky net connections
if (window.Keen) {
// Draw keen charts
Keen.onChartsReady(drawUserMetrics)
Keen.onChartsReady(drawTweetMetrics)
// Update keen charts every minute
setInterval(drawUserMetrics, 6e4)
setInterval(drawTweetMetrics, 6e4)
}
keen("progress", { step: "visit" })
// If a user has logged in, use the auth token to authenticate with firebase
if (localStorage.firebaseAuthToken) {
firebase.auth(localStorage.firebaseAuthToken, function(error) {
keen("progress", { step: "firebase_auth" })
if (!error) {
// Retrieve twitter & auth data via singly
$.getJSON(sprintf("%s/profiles/twitter", singlyApiHost),
{ auth: true,
access_token: localStorage.singlyAccessToken }, function(response) {
// Assign the twitter data, and auth data required by the twitter stream proxy
currentUser = response.data
currentUserAuth = response.auth
// Allow other components to update now that user has signed in
// and current user data is available
Weeve.trigger("auth:ready")
// Check to see if the weeve is full
var usersRef = firebase.child("users")
usersRef.once('value', function(users) {
if (users.numChildren() < 20) {
// Create the Firebase user
connectUser()
// Start listening for tweets
listenForTweets()
} else {
keen("progress", { step: "full" })
alert("Weeve is full right now. Refresh your page if you see a spot open up.")
}
})
})
} else {
// Something is awry with the keys, logout and start over
logout()
}
})
} else {
// Trigger auth:get. compnents respond by setting up the sign up view, etc
Weeve.trigger("auth:get")
}
},
// Singly passes us back authentication data via this route
firebase: function(firebase, accessToken, account) {
// Write tokens into local storage so state can persist
// across page refreshes
localStorage.firebaseAuthToken = firebase
localStorage.singlyAccessToken = accessToken
localStorage.singlyAccountId = account
// Track success for funnel & debugging purposes
keen("progress", { step: "oauth_worked" })
Backbone.history.navigate("", { trigger: true })
}
}))
// Start execution!
Backbone.history.start()
// affix the row of weevers when the user scroll's down
// for the ultimate 'dashboard' type view
$(window).scroll(function() {
if (window.matchMedia) {
var mql = window.matchMedia("(min-width: 767px)");
if (mql.matches) {
var yPosition = $(window).scrollTop()
// the extra twenty makes it easier to dock when scrolling up
if (yPosition > $(".header-row").outerHeight() - 20) {
$(".main-row").css("margin-top", $(".user-row").outerHeight())
$(".user-row").addClass("fixed")
} else {
$(".main-row").css("margin-top", 0)
$(".user-row").removeClass("fixed")
}
}
}
})
})