add networkDeployment to xoslib
[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     SLICEDEPLOYMENT_API = "/plstackapi/slice_deployments/";
7     SLICEPRIVILEGE_API = "/plstackapi/slice_privileges/";
8     SLICEROLE_API = "/plstackapi/slice_roles/";
9     NODE_API = "/plstackapi/nodes/";
10     SITE_API = "/plstackapi/sites/";
11     USER_API = "/plstackapi/users/";
12     USERDEPLOYMENT_API = "/plstackapi/user_deployments/";
13     DEPLOYMENT_API = "/plstackapi/deployments/";
14     IMAGE_API = "/plstackapi/images/";
15     NETWORKTEMPLATE_API = "/plstackapi/networktemplates/";
16     NETWORKDEPLOYMENT_API = "/plstackapi/networkdeployments/";
17     NETWORK_API = "/plstackapi/networks/";
18     NETWORKSLIVER_API = "/plstackapi/networkslivers/";
19     SERVICE_API = "/plstackapi/services/";
20
21     SLICEPLUS_API = "/xoslib/slicesplus/";
22
23     XOSModel = Backbone.Model.extend({
24         /* from backbone-tastypie.js */
25         //idAttribute: 'resource_uri',
26
27         /* from backbone-tastypie.js */
28         url: function() {
29                     var url = this.attributes.resource_uri;
30
31                     if (!url) {
32                         url = this.urlRoot + this.id;
33                     }
34
35                     if (!url) {
36                         // XXX I'm not sure this does anything useful
37                         url = ( _.isFunction( this.collection.url ) ? this.collection.url() : this.collection.url );
38                         url = url || this.urlRoot;
39                     }
40
41                     // remove any existing query parameters
42                     url && ( url.indexOf("?") > -1 ) && ( url = url.split("?")[0] );
43
44                     url && ( url += ( url.length > 0 && url.charAt( url.length - 1 ) === '/' ) ? '' : '/' );
45
46                     url && ( url += "?no_hyperlinks=1" );
47
48                     return url;
49             },
50
51             listMethods: function() {
52                 var res = [];\r
53                 for(var m in this) {\r
54                     if(typeof this[m] == "function") {\r
55                         res.push(m)\r
56                     }\r
57                 }\r
58                 return res;\r
59             }
60     });
61
62     XOSCollection = Backbone.Collection.extend({
63         objects: function() {
64                     return this.models.map(function(element) { return element.attributes; });
65                  },
66
67         initialize: function(){
68           this.sortVar = 'name';\r
69           this.sortOrder = 'asc';\r
70         },\r
71 \r
72         relatedCollections: [],\r
73         foreignCollections: [],\r
74 \r
75         simpleComparator: function( model ){\r
76           parts=this.sortVar.split(".");\r
77           result = model.get(parts[0]);\r
78           for (index=1; index<parts.length; ++index) {\r
79               result=result[parts[index]];\r
80           }\r
81           return result;\r
82         },\r
83 \r
84         comparator: function (left, right) {\r
85             var l = this.simpleComparator(left);\r
86             var r = this.simpleComparator(right);\r
87 \r
88             if (l === void 0) return -1;\r
89             if (r === void 0) return 1;\r
90 \r
91             if (this.sortOrder=="desc") {\r
92                 return l < r ? 1 : l > r ? -1 : 0;\r
93             } else {\r
94                 return l < r ? -1 : l > r ? 1 : 0;\r
95             }\r
96         },\r
97 \r
98         startPolling: function() {\r
99             if (!this._polling) {\r
100                 var collection=this;
101                 setInterval(function() { collection.fetch(); }, 10000);
102                 this._polling=true;
103                 this.fetch();
104             }
105         },
106
107         maybeFetch: function(options){
108                 // Helper function to fetch only if this collection has not been fetched before.
109             if(this._fetched){
110                     // If this has already been fetched, call the success, if it exists
111                 options.success && options.success();
112                 console.log("alreadyFetched");
113                 return;
114             }
115
116                 // when the original success function completes mark this collection as fetched
117             var self = this,
118             successWrapper = function(success){
119                 return function(){
120                     self._fetched = true;
121                     success && success.apply(this, arguments);
122                 };
123             };
124             options.success = successWrapper(options.success);
125             console.log("call fetch");
126             this.fetch(options);
127         },
128
129         getOrFetch: function(id, options){
130                 // Helper function to use this collection as a cache for models on the server
131             var model = this.get(id);
132
133             if(model){
134                 options.success && options.success(model);
135                 return;
136             }
137
138             model = new this.model({
139                 resource_uri: id
140             });
141
142             model.fetch(options);
143         },
144
145         filterBy: function(fieldName, value) {
146              filtered = this.filter(function(obj) {
147                  return obj.get(fieldName) == value;
148                  });
149              return new this.constructor(filtered);
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                                                        relatedCollections: {"networkSlivers": "sliver"},
188                                                        foreignCollections: ["slices", "deployments", "images", "nodes", "users"],
189                                                        model: this.sliver});
190         this.slivers = new this.sliverCollection();
191
192         this.slice = XOSModel.extend({ urlRoot: SLICE_API });
193         this.sliceCollection = XOSCollection.extend({ urlRoot: SLICE_API,
194                                                        relatedCollections: {"slivers": "slice", "sliceDeployments": "slice", "slicePrivileges": "slice"},
195                                                        foreignCollections: ["services", "sites"],
196                                                        model: this.slice});
197         this.slices = new this.sliceCollection();
198
199         this.sliceDeployment = XOSModel.extend({ urlRoot: SLICEDEPLOYMENT_API });
200         this.sliceDeploymentCollection = XOSCollection.extend({ urlRoot: SLICEDEPLOYMENT_API,
201                                                        foreignCollections: ["slices", "deployments"],
202                                                        model: this.slice});
203         this.sliceDeployments = new this.sliceDeploymentCollection();
204
205         this.slicePrivilege = XOSModel.extend({ urlRoot: SLICEPRIVILEGE_API });
206         this.slicePrivilegeCollection = XOSCollection.extend({ urlRoot: SLICEPRIVILEGE_API,
207                                                        foreignCollections: ["slices", "users", "sliceRoles"],
208                                                        model: this.slice});
209         this.slicePrivileges = new this.slicePrivilegeCollection();
210
211         this.sliceRole = XOSModel.extend({ urlRoot: SLICEROLE_API });
212         this.sliceRoleCollection = XOSCollection.extend({ urlRoot: SLICEROLE_API,
213                                                        model: this.slice});
214         this.sliceRoles = new this.sliceRoleCollection();
215
216         this.node = XOSModel.extend({ urlRoot: NODE_API });
217         this.nodeCollection = XOSCollection.extend({ urlRoot: NODE_API,
218                                                        foreignCollections: ["sites", "deployments"],
219                                                        model: this.node});
220         this.nodes = new this.nodeCollection();
221
222         this.site = XOSModel.extend({ urlRoot: SITE_API });
223         this.siteCollection = XOSCollection.extend({ urlRoot: SITE_API,
224                                                        model: this.site});
225         this.sites = new this.siteCollection();
226
227         this.user = XOSModel.extend({ urlRoot: USER_API });
228         this.userCollection = XOSCollection.extend({ urlRoot: USER_API,
229                                                        relatedCollections: {"slicePrivileges": "user", "slices": "owner", "userDeployments": "user"},
230                                                        foreignCollections: ["sites"],
231                                                        model: this.user});
232         this.users = new this.userCollection();
233
234         this.userDeployment = XOSModel.extend({ urlRoot: USER_API });
235         this.userDeploymentCollection = XOSCollection.extend({ urlRoot: USERDEPLOYMENT_API,
236                                                        foreignCollections: ["users","deployments"],
237                                                        model: this.user});
238         this.userDeployments = new this.userDeploymentCollection();
239
240         this.deployment = XOSModel.extend({ urlRoot: DEPLOYMENT_API });
241         this.deploymentCollection = XOSCollection.extend({ urlRoot: DEPLOYMENT_API,
242                                                            model: this.deployment});
243         this.deployments = new this.deploymentCollection();
244
245         this.image = XOSModel.extend({ urlRoot: IMAGE_API });
246         this.imageCollection = XOSCollection.extend({ urlRoot: IMAGE_API,
247                                                            model: this.image});
248         this.images = new this.imageCollection();
249
250         this.networkTemplate = XOSModel.extend({ urlRoot: NETWORKTEMPLATE_API });
251         this.networkTemplateCollection = XOSCollection.extend({ urlRoot: NETWORKTEMPLATE_API,
252                                                            model: this.networkTemplate});
253         this.networkTemplates = new this.networkTemplateCollection();
254
255         this.network = XOSModel.extend({ urlRoot: NETWORK_API });
256         this.networkCollection = XOSCollection.extend({ urlRoot: NETWORK_API,
257                                                            relatedCollections: {"networkDeployments": "network", "networkSlivers": "network"},
258                                                            foreignCollections: ["slices", "networkTemplates"],
259                                                            model: this.network});
260         this.networks = new this.networkCollection();
261
262         this.networkSliver = XOSModel.extend({ urlRoot: NETWORKSLIVER_API });
263         this.networkSliverCollection = XOSCollection.extend({ urlRoot: NETWORKSLIVER_API,
264                                                            model: this.networkSliver});
265         this.networkSlivers = new this.networkSliverCollection();
266
267         this.networkDeployment = XOSModel.extend({ urlRoot: NETWORKDEPLOYMENT_API });
268         this.networkDeploymentCollection = XOSCollection.extend({ urlRoot: NETWORKDEPLOYMENT_API,
269                                                            model: this.networkDeployment});
270         this.networkDeployments = new this.networkDeploymentCollection();
271
272         this.service = XOSModel.extend({ urlRoot: SERVICE_API });
273         this.serviceCollection = XOSCollection.extend({ urlRoot: SERVICE_API,
274                                                        model: this.service});
275         this.services = new this.serviceCollection();
276
277         // enhanced REST
278         this.slicePlus = XOSModel.extend({ urlRoot: SLICEPLUS_API, relatedCollections: {'slivers': "slice"} });
279         this.slicePlusCollection = XOSCollection.extend({ urlRoot: SLICEPLUS_API,
280                                                           model: this.slicePlus});
281         this.slicesPlus = new this.slicePlusCollection();
282
283         this.listObjects = function() { return ["slivers", "slices", "nodes", "sites", "users", "deployments"]; };
284     };
285
286     xos = new xoslib();
287
288     function getCookie(name) {
289         var cookieValue = null;\r
290         if (document.cookie && document.cookie != '') {\r
291             var cookies = document.cookie.split(';');\r
292             for (var i = 0; i < cookies.length; i++) {\r
293                 var cookie = jQuery.trim(cookies[i]);\r
294                 // Does this cookie string begin with the name we want?\r
295                 if (cookie.substring(0, name.length + 1) == (name + '=')) {\r
296                     cookieValue = decodeURIComponent(cookie.substring(name.length + 1));\r
297                     break;\r
298                 }\r
299             }\r
300         }\r
301         return cookieValue;\r
302     }
303
304     (function() {
305       var _sync = Backbone.sync;\r
306       Backbone.sync = function(method, model, options){\r
307         options.beforeSend = function(xhr){\r
308           var token = getCookie("csrftoken");\r
309           xhr.setRequestHeader('X-CSRFToken', token);\r
310         };\r
311         return _sync(method, model, options);\r
312       };\r
313     })();
314 }