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