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