fix sliceplus to work with big rename
[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     SLICEROLE_API = "/plstackapi/slice_roles/";
7     NODE_API = "/plstackapi/nodes/";
8     SITE_API = "/plstackapi/sites/";
9     USER_API = "/plstackapi/users/";
10     USERDEPLOYMENT_API = "/plstackapi/user_deployments/";
11     DEPLOYMENT_API = "/plstackapi/deployments/";
12     IMAGE_API = "/plstackapi/images/";
13     NETWORKTEMPLATE_API = "/plstackapi/networktemplates/";
14     NETWORK_API = "/plstackapi/networks/";
15     NETWORKSLIVER_API = "/plstackapi/networkslivers/";
16     SERVICE_API = "/plstackapi/services/";
17     SLICEPRIVILEGE_API = "/plstackapi/slice_privileges/";
18     NETWORKDEPLOYMENT_API = "/plstackapi/networkdeployments/";
19
20     /* changed as a side effect of the big rename
21     SLICEDEPLOYMENT_API = "/plstackapi/slice_deployments/";
22     USERDEPLOYMENT_API = "/plstackapi/user_deployments/";
23     */
24
25     SLICEDEPLOYMENT_API = "/plstackapi/slicedeployments/";
26     USERDEPLOYMENT_API = "/plstackapi/userdeployments/";
27
28     SLICEPLUS_API = "/xoslib/slicesplus/";
29
30     XOSModel = Backbone.Model.extend({
31         /* from backbone-tastypie.js */
32         //idAttribute: 'resource_uri',
33
34         /* from backbone-tastypie.js */
35         url: function() {
36                     var url = this.attributes.resource_uri;
37
38                     if (!url) {
39                         if (this.id) {
40                             url = this.urlRoot + this.id;
41                         } else {
42                             // this happens when creating a new model.
43                             url = this.urlRoot;
44                         }
45                     }
46
47                     if (!url) {
48                         // XXX I'm not sure this does anything useful
49                         url = ( _.isFunction( this.collection.url ) ? this.collection.url() : this.collection.url );
50                         url = url || this.urlRoot;
51                     }
52
53                     // remove any existing query parameters
54                     url && ( url.indexOf("?") > -1 ) && ( url = url.split("?")[0] );
55
56                     url && ( url += ( url.length > 0 && url.charAt( url.length - 1 ) === '/' ) ? '' : '/' );
57
58                     url && ( url += "?no_hyperlinks=1" );
59
60                     return url;
61             },
62
63             listMethods: function() {
64                 var res = [];\r
65                 for(var m in this) {\r
66                     if(typeof this[m] == "function") {\r
67                         res.push(m)\r
68                     }\r
69                 }\r
70                 return res;\r
71             }
72     });
73
74     XOSCollection = Backbone.Collection.extend({
75         objects: function() {
76                     return this.models.map(function(element) { return element.attributes; });
77                  },
78
79         initialize: function(){
80           this.isLoaded = false;
81           this.failedLoad = false;
82           this.startedLoad = false;
83           this.sortVar = 'name';\r
84           this.sortOrder = 'asc';\r
85           this.on( "sort", this.sorted );\r
86         },\r
87 \r
88         relatedCollections: [],\r
89         foreignCollections: [],\r
90 \r
91         sorted: function() {\r
92             //console.log("sorted " + this.modelName);\r
93         },\r
94 \r
95         simpleComparator: function( model ){\r
96           parts=this.sortVar.split(".");\r
97           result = model.get(parts[0]);\r
98           for (index=1; index<parts.length; ++index) {\r
99               result=result[parts[index]];\r
100           }\r
101           return result;\r
102         },\r
103 \r
104         comparator: function (left, right) {\r
105             var l = this.simpleComparator(left);\r
106             var r = this.simpleComparator(right);\r
107 \r
108             if (l === void 0) return -1;\r
109             if (r === void 0) return 1;\r
110 \r
111             if (this.sortOrder=="desc") {\r
112                 return l < r ? 1 : l > r ? -1 : 0;\r
113             } else {\r
114                 return l < r ? -1 : l > r ? 1 : 0;\r
115             }\r
116         },\r
117 \r
118         fetchSuccess: function(collection, response, options) {\r
119             //console.log("fetch succeeded " + collection.modelName);\r
120             this.failedLoad = false;\r
121             this.fetching = false;\r
122             if (!this.isLoaded) {\r
123                 this.isLoaded = true;\r
124                 Backbone.trigger("xoslib:collectionLoadChange", this);\r
125             }\r
126             this.trigger("fetchStateChange");\r
127             if (options["orig_success"]) {\r
128                 options["orig_success"](collection, response, options);\r
129             }\r
130         },\r
131 \r
132         fetchFailure: function(collection, response, options) {\r
133             //console.log("fetch failed " + collection.modelName);\r
134             this.fetching = false;\r
135             if ((!this.isLoaded) && (!this.failedLoad)) {\r
136                 this.failedLoad=true;\r
137                 Backbone.trigger("xoslib:collectionLoadChange", this);\r
138             }\r
139             this.trigger("fetchStateChange");\r
140             if (options["orig_failure"]) {\r
141                 options["orig_failure"](collection, response, options);\r
142             }\r
143         },\r
144 \r
145         fetch: function(options) {\r
146             var self=this;\r
147             this.fetching=true;\r
148             //console.log("fetch " + this.modelName);\r
149             if (!this.startedLoad) {\r
150                 this.startedLoad=true;\r
151                 Backbone.trigger("xoslib:collectionLoadChange", this);\r
152             }\r
153             this.trigger("fetchStateChange");\r
154             if (options == undefined) {\r
155                 options = {};\r
156             }\r
157             options["orig_success"] = options["success"];\r
158             options["orig_failure"] = options["failure"];\r
159             options["success"] = function(collection, response, options) { self.fetchSuccess.call(self, collection, response, options); };\r
160             options["failure"] = this.fetchFailure;\r
161             Backbone.Collection.prototype.fetch.call(this, options);\r
162         },\r
163 \r
164         startPolling: function() {\r
165             if (!this._polling) {\r
166                 var collection=this;
167                 setInterval(function() { collection.fetch(); }, 10000);
168                 this._polling=true;
169                 this.fetch();
170             }
171         },
172
173         refresh: function(refreshRelated) {
174             if (!this.fetching) {
175                 this.fetch();
176             }
177             if (refreshRelated) {
178                 for (related in this.relatedCollections) {
179                     related = xos[related];
180                     if (!related.fetching) {
181                         related.fetch();
182                     }
183                 }
184             }
185         },
186
187         maybeFetch: function(options){
188                 // Helper function to fetch only if this collection has not been fetched before.
189             if(this._fetched){
190                     // If this has already been fetched, call the success, if it exists
191                 options.success && options.success();
192                 console.log("alreadyFetched");
193                 return;
194             }
195
196                 // when the original success function completes mark this collection as fetched
197             var self = this,
198             successWrapper = function(success){
199                 return function(){
200                     self._fetched = true;
201                     success && success.apply(this, arguments);
202                 };
203             };
204             options.success = successWrapper(options.success);
205             console.log("call fetch");
206             this.fetch(options);
207         },
208
209         getOrFetch: function(id, options){
210                 // Helper function to use this collection as a cache for models on the server
211             var model = this.get(id);
212
213             if(model){
214                 options.success && options.success(model);
215                 return;
216             }
217
218             model = new this.model({
219                 resource_uri: id
220             });
221
222             model.fetch(options);
223         },
224
225         filterBy: function(fieldName, value) {
226              filtered = this.filter(function(obj) {
227                  return obj.get(fieldName) == value;
228                  });
229              return new this.constructor(filtered);
230         },
231
232         /* from backbone-tastypie.js */
233         url: function( models ) {
234                     var url = this.urlRoot || ( models && models.length && models[0].urlRoot );
235                     url && ( url += ( url.length > 0 && url.charAt( url.length - 1 ) === '/' ) ? '' : '/' );
236
237                     // Build a url to retrieve a set of models. This assume the last part of each model's idAttribute
238                     // (set to 'resource_uri') contains the model's id.
239                     if ( models && models.length ) {
240                             var ids = _.map( models, function( model ) {
241                                             var parts = _.compact( model.id.split('/') );
242                                             return parts[ parts.length - 1 ];
243                                     });
244                             url += 'set/' + ids.join(';') + '/';
245                     }
246
247                     url && ( url += "?no_hyperlinks=1" );
248
249                     return url;
250             },
251
252         listMethods: function() {
253                 var res = [];\r
254                 for(var m in this) {\r
255                     if(typeof this[m] == "function") {\r
256                         res.push(m)\r
257                     }\r
258                 }\r
259                 return res;\r
260             },
261     });
262
263     function define_model(lib, attrs) {
264         modelName = attrs.modelName;
265         modelClassName = modelName;
266         collectionClassName = modelName + "Collection";
267
268         if (!attrs.collectionName) {
269             attrs.collectionName = modelName + "s";
270         }
271         collectionName = attrs.collectionName;
272
273         modelAttrs = {}
274         collectionAttrs = {}
275
276         for (key in attrs) {
277             value = attrs[key];
278             if ($.inArray(key, ["urlRoot", "modelName"])>=0) {
279                 modelAttrs[key] = value;
280             }
281             if ($.inArray(key, ["urlRoot", "modelName", "relatedCollections", "foreignCollections"])>=0) {
282                 collectionAttrs[key] = value;
283             }
284         }
285
286         if (xosdefaults && xosdefaults[modelName]) {
287             modelAttrs["defaults"] = xosdefaults[modelName];
288         }
289
290         lib[modelName] = XOSModel.extend(modelAttrs);
291
292         collectionAttrs["model"] = lib[modelName];
293
294         lib[collectionClassName] = XOSCollection.extend(collectionAttrs);
295         lib[collectionName] = new lib[collectionClassName]();
296
297         lib.allCollectionNames.push(collectionName);
298         lib.allCollections.push(lib[collectionName]);
299     };
300
301     function xoslib() {
302         this.allCollectionNames = [];
303         this.allCollections = [];
304
305         define_model(this, {urlRoot: SLIVER_API,
306                             relatedCollections: {"networkSlivers": "sliver"},
307                             foreignCollections: ["slices", "deployments", "images", "nodes", "users"],
308                             modelName: "sliver"});
309
310         define_model(this, {urlRoot: SLICE_API,
311                            relatedCollections: {"slivers": "slice", "sliceDeployments": "slice", "slicePrivileges": "slice", "networks": "owner"},
312                            foreignCollections: ["services", "sites"],
313                            modelName: "slice"});
314
315         define_model(this, {urlRoot: SLICEDEPLOYMENT_API,
316                            foreignCollections: ["slices", "deployments"],
317                            modelName: "sliceDeployment"});
318
319         define_model(this, {urlRoot: SLICEPRIVILEGE_API,
320                             foreignCollections: ["slices", "users", "sliceRoles"],
321                             modelName: "slicePrivilege"});
322
323         define_model(this, {urlRoot: SLICEROLE_API,
324                             modelName: "sliceRole"});
325
326         define_model(this, {urlRoot: NODE_API,
327                             foreignCollections: ["sites", "deployments"],
328                             modelName: "node"});
329
330         define_model(this, {urlRoot: SITE_API,
331                             relatedCollections: {"users": "site", "slices": "site", "nodes": "site"},
332                             modelName: "site"});
333
334         define_model(this, {urlRoot: USER_API,
335                             relatedCollections: {"slicePrivileges": "user", "slices": "owner", "userDeployments": "user"},
336                             foreignCollections: ["sites"],
337                             modelName: "user"});
338
339         define_model(this, {urlRoot: USERDEPLOYMENT_API,
340                             foreignCollections: ["users","deployments"],
341                             modelName: "userDeployment"});
342
343         define_model(this, { urlRoot: DEPLOYMENT_API,
344                              relatedCollections: {"nodes": "deployment", "slivers": "deploymentNetwork", "networkDeployments": "deployment", "userDeployments": "deployment"},
345                              modelName: "deployment"});
346
347         define_model(this, {urlRoot: IMAGE_API,
348                             model: this.image,
349                             modelName: "image"});
350
351         define_model(this, {urlRoot: NETWORKTEMPLATE_API,
352                             modelName: "networkTemplate"});
353
354         define_model(this, {urlRoot: NETWORK_API,
355                             relatedCollections: {"networkDeployments": "network", "networkSlivers": "network"},
356                             foreignCollections: ["slices", "networkTemplates"],
357                             modelName: "network"});
358
359         define_model(this, {urlRoot: NETWORKSLIVER_API,
360                             modelName: "networkSliver"});
361
362         define_model(this, {urlRoot: NETWORKDEPLOYMENT_API,
363                             modelName: "networkDeployment"});
364
365         define_model(this, {urlRoot: SERVICE_API,
366                             modelName: "service"});
367
368         // enhanced REST
369         define_model(this, {urlRoot: SLICEPLUS_API,
370                             relatedCollections: {'slivers': "slice"},
371                             modelName: "slicePlus",
372                             collectionName: "slicesPlus"});
373
374         this.listObjects = function() { return this.allCollectionNames; };
375
376         this.getCollectionStatus = function() {
377             stats = {isLoaded: 0, failedLoad: 0, startedLoad: 0};
378             for (index in this.allCollections) {
379                 collection = this.allCollections[index];
380                 if (collection.isLoaded) {
381                     stats["isLoaded"] = stats["isLoaded"] + 1;
382                 }
383                 if (collection.failedLoad) {
384                     stats["failedLoad"] = stats["failedLoad"] + 1;
385                 }
386                 if (collection.startedLoad) {
387                     stats["startedLoad"] = stats["startedLoad"] + 1;
388                 }
389             }
390             stats["completedLoad"] = stats["failedLoad"] + stats["isLoaded"];
391             return stats;
392         };
393     };
394
395     xos = new xoslib();
396
397     function getCookie(name) {
398         var cookieValue = null;\r
399         if (document.cookie && document.cookie != '') {\r
400             var cookies = document.cookie.split(';');\r
401             for (var i = 0; i < cookies.length; i++) {\r
402                 var cookie = jQuery.trim(cookies[i]);\r
403                 // Does this cookie string begin with the name we want?\r
404                 if (cookie.substring(0, name.length + 1) == (name + '=')) {\r
405                     cookieValue = decodeURIComponent(cookie.substring(name.length + 1));\r
406                     break;\r
407                 }\r
408             }\r
409         }\r
410         return cookieValue;\r
411     }
412
413     (function() {
414       var _sync = Backbone.sync;\r
415       Backbone.sync = function(method, model, options){\r
416         options.beforeSend = function(xhr){\r
417           var token = getCookie("csrftoken");\r
418           xhr.setRequestHeader('X-CSRFToken', token);\r
419         };\r
420         return _sync(method, model, options);\r
421       };\r
422     })();
423 }