getting it from a cookie is better than sticking it in a meta tag
[plstackapi.git] / planetstack / core / xoslib / static / js / xoslib / xos-backbone.js
1 if (! window.XOSLIB_LOADED ) {
2     window.XOSLIB_LOADED=true;
3
4     SLIVER_API = "/plstackapi/slivers/";
5     SLICE_API = "/plstackapi/slices/";
6     NODE_API = "/plstackapi/nodes/";
7     SITE_API = "/plstackapi/sites/";
8     USER_API = "/plstackapi/users/";
9     DEPLOYMENT_API = "/plstackapi/deployments/";
10     IMAGE_API = "/plstackapi/images/";
11     NETWORKTEMPLATE_API = "/plstackapi/networktemplates/";
12     NETWORK_API = "/plstackapi/networks/";
13     SERVICE_API = "/plstackapi/services/";
14
15     SLICEPLUS_API = "/xoslib/slicesplus/";
16
17     function getCookie(name) {
18         var cookieValue = null;\r
19         if (document.cookie && document.cookie != '') {\r
20             var cookies = document.cookie.split(';');\r
21             for (var i = 0; i < cookies.length; i++) {\r
22                 var cookie = jQuery.trim(cookies[i]);\r
23                 // Does this cookie string begin with the name we want?\r
24                 if (cookie.substring(0, name.length + 1) == (name + '=')) {\r
25                     cookieValue = decodeURIComponent(cookie.substring(name.length + 1));\r
26                     break;\r
27                 }\r
28             }\r
29         }\r
30         return cookieValue;\r
31     }
32
33     XOSModel = Backbone.Model.extend({
34         /* from backbone-tastypie.js */
35         //idAttribute: 'resource_uri',
36
37         /* from backbone-tastypie.js */
38         url: function() {
39                     var url = this.attributes.resource_uri;
40
41                     if (!url) {
42                         url = this.urlRoot + this.id;
43                     }
44
45                     if (!url) {
46                         // XXX I'm not sure this does anything useful
47                         url = ( _.isFunction( this.collection.url ) ? this.collection.url() : this.collection.url );
48                         url = url || this.urlRoot;
49                     }
50
51                     // remove any existing query parameters
52                     url && ( url.indexOf("?") > -1 ) && ( url = url.split("?")[0] );
53
54                     url && ( url += ( url.length > 0 && url.charAt( url.length - 1 ) === '/' ) ? '' : '/' );
55
56                     url && ( url += "?no_hyperlinks=1" );
57
58                     return url;
59             },
60
61             listMethods: function() {
62                 var res = [];\r
63                 for(var m in this) {\r
64                     if(typeof this[m] == "function") {\r
65                         res.push(m)\r
66                     }\r
67                 }\r
68                 return res;\r
69             }
70     });
71
72     XOSCollection = Backbone.Collection.extend({
73         objects: function() {
74                     return this.models.map(function(element) { return element.attributes; });
75                  },
76
77         initialize: function(){
78           this.sortVar = 'name';\r
79           this.sortOrder = 'asc';\r
80         },\r
81 \r
82         simpleComparator: function( model ){\r
83           parts=this.sortVar.split(".");\r
84           result = model.get(parts[0]);\r
85           for (index=1; index<parts.length; ++index) {\r
86               result=result[parts[index]];\r
87           }\r
88           return result;\r
89         },\r
90 \r
91         comparator: function (left, right) {\r
92             var l = this.simpleComparator(left);\r
93             var r = this.simpleComparator(right);\r
94 \r
95             if (l === void 0) return -1;\r
96             if (r === void 0) return 1;\r
97 \r
98             if (this.sortOrder=="desc") {\r
99                 return l < r ? 1 : l > r ? -1 : 0;\r
100             } else {\r
101                 return l < r ? -1 : l > r ? 1 : 0;\r
102             }\r
103         },\r
104 \r
105         startPolling: function() {\r
106             if (!this._polling) {\r
107                 var collection=this;
108                 setInterval(function() { collection.fetch(); }, 10000);
109                 this._polling=true;
110                 this.fetch();
111             }
112         },
113
114         maybeFetch: function(options){
115                 // Helper function to fetch only if this collection has not been fetched before.
116             if(this._fetched){
117                     // If this has already been fetched, call the success, if it exists
118                 options.success && options.success();
119                 console.log("alreadyFetched");
120                 return;
121             }
122
123                 // when the original success function completes mark this collection as fetched
124             var self = this,
125             successWrapper = function(success){
126                 return function(){
127                     self._fetched = true;
128                     success && success.apply(this, arguments);
129                 };
130             };
131             options.success = successWrapper(options.success);
132             console.log("call fetch");
133             this.fetch(options);
134         },
135
136         getOrFetch: function(id, options){
137                 // Helper function to use this collection as a cache for models on the server
138             var model = this.get(id);
139
140             if(model){
141                 options.success && options.success(model);
142                 return;
143             }
144
145             model = new this.model({
146                 resource_uri: id
147             });
148
149             model.fetch(options);
150         },
151
152         /* from backbone-tastypie.js */
153         url: function( models ) {
154                     var url = this.urlRoot || ( models && models.length && models[0].urlRoot );
155                     url && ( url += ( url.length > 0 && url.charAt( url.length - 1 ) === '/' ) ? '' : '/' );
156
157                     // Build a url to retrieve a set of models. This assume the last part of each model's idAttribute
158                     // (set to 'resource_uri') contains the model's id.
159                     if ( models && models.length ) {
160                             var ids = _.map( models, function( model ) {
161                                             var parts = _.compact( model.id.split('/') );
162                                             return parts[ parts.length - 1 ];
163                                     });
164                             url += 'set/' + ids.join(';') + '/';
165                     }
166
167                     url && ( url += "?no_hyperlinks=1" );
168
169                     return url;
170             },
171
172             listMethods: function() {
173                 var res = [];\r
174                 for(var m in this) {\r
175                     if(typeof this[m] == "function") {\r
176                         res.push(m)\r
177                     }\r
178                 }\r
179                 return res;\r
180             }
181     });
182
183     function xoslib() {
184         // basic REST
185         this.sliver = XOSModel.extend({ urlRoot: SLIVER_API });
186         this.sliverCollection = XOSCollection.extend({ urlRoot: SLIVER_API,
187                                                        model: this.sliver});
188         this.slivers = new this.sliverCollection();
189
190         this.slice = XOSModel.extend({ urlRoot: SLICE_API });
191         this.sliceCollection = XOSCollection.extend({ urlRoot: SLICE_API,
192                                                        model: this.slice});
193         this.slices = new this.sliceCollection();
194
195         this.node = XOSModel.extend({ urlRoot: NODE_API });
196         this.nodeCollection = XOSCollection.extend({ urlRoot: NODE_API,
197                                                        model: this.node});
198         this.nodes = new this.nodeCollection();
199
200         this.site = XOSModel.extend({ urlRoot: SITE_API });
201         this.siteCollection = XOSCollection.extend({ urlRoot: SITE_API,
202                                                        model: this.site});
203         this.sites = new this.siteCollection();
204
205         this.user = XOSModel.extend({ urlRoot: USER_API });
206         this.userCollection = XOSCollection.extend({ urlRoot: USER_API,
207                                                        model: this.user});
208         this.users = new this.userCollection();
209
210         this.deployment = XOSModel.extend({ urlRoot: DEPLOYMENT_API });
211         this.deploymentCollection = XOSCollection.extend({ urlRoot: DEPLOYMENT_API,
212                                                            model: this.deployment});
213         this.deployments = new this.deploymentCollection();
214
215         this.image = XOSModel.extend({ urlRoot: IMAGE_API });
216         this.imageCollection = XOSCollection.extend({ urlRoot: IMAGE_API,
217                                                            model: this.image});
218         this.images = new this.imageCollection();
219
220         this.networkTemplate = XOSModel.extend({ urlRoot: NETWORKTEMPLATE_API });
221         this.networkTemplateCollection = XOSCollection.extend({ urlRoot: NETWORKTEMPLATE_API,
222                                                            model: this.networkTemplate});
223         this.networkTemplates = new this.networkTemplateCollection();
224
225         this.network = XOSModel.extend({ urlRoot: NETWORK_API });
226         this.networkCollection = XOSCollection.extend({ urlRoot: NETWORK_API,
227                                                            model: this.network});
228         this.networks = new this.networkCollection();
229
230         this.service = XOSModel.extend({ urlRoot: SERVICE_API });
231         this.serviceCollection = XOSCollection.extend({ urlRoot: SERVICE_API,
232                                                        model: this.service});
233         this.services = new this.serviceCollection();
234
235         // enhanced REST
236         this.slicePlus = XOSModel.extend({ urlRoot: SLICEPLUS_API });
237         this.slicePlusCollection = XOSCollection.extend({ urlRoot: SLICEPLUS_API,
238                                                           model: this.slicePlus});
239         this.slicesPlus = new this.slicePlusCollection();
240
241         this.listObjects = function() { return ["slivers", "slices", "nodes", "sites", "users", "deployments"]; };
242     };
243
244     xos = new xoslib();
245
246     (function() {
247       var _sync = Backbone.sync;\r
248       Backbone.sync = function(method, model, options){\r
249         options.beforeSend = function(xhr){\r
250           //var token = $('meta[name="csrf-token"]').attr('content');\r
251           var token = getCookie("csrftoken");\r
252           xhr.setRequestHeader('X-CSRFToken', token);\r
253           console.log(token);\r
254         };\r
255         return _sync(method, model, options);\r
256       };\r
257     })();
258 }