facebook /backbone.api.facebook.js

Language Javascript Lines 506
MD5 Hash 78514b6cee4e69da83b9bf5cd356395b
Repository https://gitlab.com/intruxxer/facebook.git View Raw File
| Open JSFiddle
  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
/* Backbone API: Facebook
 * Source: https://github.com/backbone-api/facebook
 *
 * Created by Makis Tracend (@tracend)
 * Distributed through [Makesites.org](http://makesites.org)
 * Released under the [MIT license](http://makesites.org/licenses/MIT)
 */

// Assuming that Facebook JS lib is loaded...
if( window.FB ) (function(_, Backbone) {

	// Constants
	var api = "https://graph.facebook.com";

	// Base model - mainly used for setup options
	var Facebook = new Backbone.Model({
		api: api,
		appId: false,
		uri: false
	});

	// Namespace definition
	Facebook.Models = {};
	Facebook.Collections = {};
	Facebook.Views = {};


	// Helpers
	// Sync method
	var Sync = function(method, model, options) {

		var url = (this.url instanceof Function) ? this.url() : this.url;
		var params = {};

		// add access token if available
		var token = this.getToken();
		if( token ){
			if( url instanceof Object) { url["access_token"] = token; }
			else { url += ( url.search(/\?/) > -1 ) ? "&access_token="+ token : "?access_token="+ token; }
		}

		//FB.api(url, method, params, function( response ) {
		FB.api(url, method, function( response ) {
			// save response.paging for later?
			// send just the response.data:
			var data = response.data || response;

			options.success( data );
		});

	};

	var getToken = function(){
		// first priority have the local options
		if( this.options && this.options.access_token) return this.options.access_token;
		// after that the internal token
		if( !_.isUndefined( token.get("accessToken") ) ) return token.get("accessToken");
		// no token
		return false;
	}


	// Models

	// - Main Constructor
	var Model = Backbone.Model.extend({
		// available options
		options : {
			access_token : false
		},

		initialize: function(model, options){
			// fallbacks
			options = options || {};
			this.options = _.extend(this.options, options);
			//return Backbone.Model.prototype.initialize.apply(this, arguments);
			// auto-fetch if requested...
			if( options.fetch ){
				this.fetch();
			}
		},

		fetch : function(method, model, options) {
			var self = this;

			if( this.getToken() ){
				// we'll be using the supplied access token
				Backbone.Model.prototype.fetch.call( self );
			} else {
				FB.getLoginStatus(function(response){
					if( response.status == "connected" ){
						// save token
						token.set( response.authResponse );
						// continue with request
						Backbone.Model.prototype.fetch.call( self );
					}
					// else try to FB.Login?
				});
			}
		},
		sync: Sync,
		getToken: getToken
	});

	//
	Facebook.Models.User = Model.extend({
		defaults : {
			//installed : true
		}
	});

	Facebook.Models.Feed = Model.extend({
		defaults : {}
	});

	Facebook.Models.Post = Model.extend({
		defaults : {
			method: "feed",
			link: "",
			picture: "",
			name: "",
			caption: "",
			description: ""
		}
	});

	Facebook.Models.Page = Model.extend({
		defaults : {
			method: "oauth",
			client_id: false,
			redirect_uri: ""
		},
		isFan: function( uid ){
			uid = uid || "me()";
			return (new isFan({ id : this.id, uid : uid }) ).fetch();
		}

	});

	Facebook.Models.Tab = Model.extend({
		url: function(){ return Facebook.get("api") + "/"+ this.page +"/tabs/app_"+ this.id },
		defaults : {},
		initialize: function( data, options ){
			this.page = data.page;
			this.id = Facebook.get("appId");
		}
	});


	//
	Facebook.Models.Link = Model.extend({
		defaults : {
			url: window.location.href,
			normalized_url: "",
			share_count: 0,
			like_count: 0,
			comment_count: 0,
			total_count: 0,
			commentsbox_count: 0,
			comments_fbid: 0,
			click_count: 0
		},

		url: function(){
			return {
				method: 'fql.query',
				query: "SELECT url,normalized_url,share_count,like_count,comment_count,total_count,commentsbox_count,comments_fbid,click_count FROM link_stat WHERE url ='"+ this.get("url") +"'"
			}
		},

		parse: function( response ){
			// error control?
			if( response instanceof Array ){
				// use only the first item
				return response.shift();
			} else {
				return response;
			}
		}
	});

	Facebook.Models.Login = Model.extend({
		defaults : {
			method: "oauth",
			client_id: false, //fb_appId
			//display: "popup",
			//response_type: "token"
			//redirect_uri: "" //https://apps.facebook.com/'+ fb_uri +'/'
		}
	});

	Facebook.Models.AddToPage = Model.extend({
		defaults : {
			method: 'pagetab',
			//redirect_uri: '', //https://apps.facebook.com/{{fb_uri}}/
		}
	});

	// Me is an extension of the user
	Facebook.Models.Me = Facebook.Models.User.extend({
		url : function(){ return Facebook.get("api") + "/me"; },
		defaults : {
			id : "me"
		},
		// defaultOptions: {
		options : {
			auth: false,
			// see https://developers.facebook.com/docs/authentication/permissions/
			scope: [], // fb permissions
			autosync: true, // auto fetch profile after login
			protocol: location.protocol
		},
		oauth: null,
		initialize: function(){
			var self = this;
			FB.Event.subscribe('auth.authResponseChange', function(e){ self.onLoginStatusChange(e) });
			return Backbone.API.Facebook.Models.User.prototype.initialize.apply(this, arguments);
		},

		login: function(callback){
			callback =  callback || function() {};
			FB.login(callback, { scope: this.options.scope.join(',') });
		},

		logout: function(){
			FB.logout();
		},

		onLoginStatusChange: function(response) {
			// only execute once?
			if(this.options.auth === response.status) return false;

			var event;

			if(response.status === 'not_authorized') {
				event = 'facebook:unauthorized';
				// login logic
			} else if (response.status === 'connected') {
				event = 'facebook:connected';
				// save request for later...
				this.request = FB.getAuthResponse();
				// copy access token
				this.oauth = {
					access_token : this.request.accessToken,
					expiry : (new Date).getTime() + this.request.expiresIn
				};
				if(this.options.autosync === true) this.fetch();
			} else {
				event = 'facebook:disconnected';
			}

			this.trigger(event, this, response);
			this.options.auth = response.status;
		}

	});

	Facebook.Models.WebPage = Model.extend({

		defaults : {
			"shares": 0,
			"comments": 0,
			"type": "website",
			"is_scraped": false
		},

		options: {

		},

		url: function(){ return Facebook.get("api") +"/?ids="+ this.options.page },

		parse: function( data ){
			// data arrives in a sub-object with the URL as the key
			var model = {};
			// - pick the first element regardless of key
			for(var key in data ){
				model = data[key];
				break; // "break" because this is a loop
			}
			data = model;
			return data;
		}

	});

	// Collections

	// - Main Constructor
	var Collection = Backbone.Collection.extend({
		// available options
		options : {
			access_token : false
		},

		initialize: function(model, options){
			// fallbacks
			options = options || {};
			this.options = _.extend(this.options, options);
			//return Backbone.Collection.prototype.initialize.apply(this, arguments);
			// auto-fetch if requested...
			if( options.fetch ){
					this.fetch();
			}
		},

		fetch : function(method, model, options) {
			var self = this;

			if( this.getToken() ){
				// we'll be using the supplied access token
				Backbone.Collection.prototype.fetch.call( self );
			} else {
				FB.getLoginStatus(function(response){
					if( response.status == "connected" ){
						// save token
						token.set( response.authResponse );
						// continue with request
						Backbone.Collection.prototype.fetch.call( self );
					}
					// else try to FB.Login?
				});
			}
		},
		sync : Sync,
		parse : function( response ){
			//console.log("facebook data:", response );
			//is uid always the id? apparently...
			var data = _.map(response, function( result ){
				if( result.uid ){
					result.id = result.uid;
					delete result.uid;
				}
				return result;
			});
			return data;
		},
		getToken: getToken
	});


	//
	Facebook.Collections.Friends = Collection.extend({
		model : Backbone.API.Facebook.Models.User,
		url: function(){
			return {
				method: 'fql.query',
				query: 'Select name, uid from user where is_app_user = 1 and uid in (select uid2 from friend where uid1 = me()) order by concat(first_name,last_name) asc'
			}
		}
	});

	Facebook.Collections.Feed = Collection.extend({
		// examples options:
		options: {
			//access_token : config.facebook.access_token
		},
		model : Backbone.API.Facebook.Models.Feed,
		url: function(){
			// creating an object of parameters
			var params = {
				method: 'fql.query',
				query: "select message,description,attachment,created_time from stream where source_id ='"+ this.id +"' limit "+ this.num,
			}
			// add access token if available
			if( this.options.access_token ){
				// we'll be using the supplied access token
				params["access_token"] = this.options.access_token;
			}
			return params;
			// old...
			// check if there is either an id or user set - fallback to 'me'
			//var page = this.user || this.id || "me";
			//return "/"+ page +"/feed?limit="+ this.num;
		},
		initialize: function( model, options){
			// parameters
			this.id = options.id || false;
			this.user = options.user || null;
			this.num = options.num || 10;
			// auto-fetch if requested...
			if( options.fetch ){
				this.fetch();
			}
		}
	});


	// Views

	// - Main Constructor
	var View = Backbone.View.extend({
		template : FB.ui,
		initialize: function( options ){
			// fallback
			options = options || {};

			if( options.callback ) this.callback = options.callback;
			// load the parent?
			//
			// fincally, render the view
			return this.render();
		},
		render : function(){

			this.template( this.model.toJSON(), this.callback );
			// preserve chainability?
			return this;

		},
		callback : function(){

		}
	});

	//
	Facebook.Views.Post = View.extend({
		callback : function(response) {
			//document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
		}
	});

	Facebook.Views.Login = View.extend({
		initialize: function( options ){
			//
			this.model = new Backbone.API.Facebook.Models.Login({
				client_id: Backbone.API.Facebook.get("appId"), //fb_appId
				//redirect_uri: "https://apps.facebook.com/"+ Backbone.API.Facebook.get("uri") +'/'
			});
			// load the parent?
			//
			return View.prototype.initialize.call( this, options );
		},
		callback : function (response) {
			if( typeof( response ) != "undefined") {
				if(response.session) {
					//var user = JSON.parse(response.session);
					// save the userid in the form
					//$("#entry-form").find("input[name='fbid']").val(user.uid);
					top.location.href = this.model.get("redirect_uri");
				} else {
					// No session
					//top.location.href = 'http://facebook.com/';
					console.log("no session");
					window.location.reload();
				}
			} else {
				// denied access
				console.log("denied access");
				//top.location.href = tab.host;
			}
		}
	});

	Facebook.Views.AddToPage = View.extend({
		initialize: function( options ){
			//
			this.model = new Backbone.API.Facebook.Models.AddToPage();
			// load the parent?
			//
			return View.prototype.initialize.call( this, options );
		}
	});



	// Internal
	// - internal access token
	// Note: Always ask for the user_likes permission before calling any of the above to make sure you get a correct result
	var Token = Backbone.Model.extend({
	});
	// - isFan method
	// Note: Always ask for the user_likes permission before calling any of the above to make sure you get a correct result
	var isFan = Model.extend({
		url :  function(){
			// alternate 'plain' url
			// "/"+ this.options.uid +"/likes/"+ this.options.id
			return {
				method: 'fql.query',
				query: 'select uid from page_fan where uid='+ this.options.uid +' and page_id='+ this.options.id
			}
		},
		parse: function( response ){
			// check if there is a data response
			return { fan : !(_.isEmpty(response.data) ) };
		}

	});

	// init token
	var token = new Token();

	// Store in selected namespace(s)
	if( _.isUndefined(Backbone.API) ) Backbone.API = {};
	Backbone.API.Facebook = Facebook;
	// - alias APP.API
	if( typeof APP != "undefined" && (_.isUndefined( APP.API) || _.isUndefined( APP.API.Facebook) ) ){
		APP.API = APP.API || {};
		APP.API.Facebook = Facebook;
	}
	// - Shortcut
	if(typeof window.Facebook == "undefined"){
		window.Facebook = Facebook;
	}

})(this._, this.Backbone);
Back to Top