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