Statistics
| Branch: | Revision:

root / src / pithos / content / share / addshareinit.js @ 46:f16f6e0e5b69

History | View | Annotate | Download (12.9 kB)

1
// The Pithos File Manager Firefox Extension is funded by GRNET S.A.
2
// (http://www.grnet.gr)
3
//
4
// Copyright (c) 2009, Christos KK Loverdos, Vassilios Karakoidas.
5
// All rights reserved.
6
//
7
// Redistribution and use in source and binary forms, with or without
8
// modification, are permitted provided that the following conditions are
9
// met:
10
//
11
//   - Redistributions of source code must retain the above copyright
12
//     notice, this list of conditions and the following disclaimer.
13
//   - Redistributions in binary form must reproduce the above
14
//     copyright notice, this list of conditions and the following
15
//     disclaimer in the documentation and/or other materials provided
16
//     with the distribution.
17
//   - Neither the name of GRNET S.A. nor the names of its contributors
18
//     may be used to endorse or promote products derived from this
19
//     software without specific prior written permission.
20
//
21
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32

    
33
connection_obj = null;
34
mimes = null;
35
cache = null;
36
vfs = null;
37
uri = null;
38
metadata = null;
39
permcols = {3: 'modifyACL' , 1: 'read' , 2: 'write' };
40
/* permissions will reflect the current permissions as the user changes them through the ui
41
  throught the lifetime of the addshare window */
42
permissions = null;
43
treeobj = null;
44
// itemname has the folder or file name striped of the home page path 
45
itemname = null;
46

    
47
//debugging vars
48
debug = null;
49

    
50
// Called once when the dialog displays
51
function init() {
52
    // Use the arguments passed to us by the caller
53
    connection_obj = new ConnectionObject();
54
    mimes = new Mimes();
55
    cache = new FileCache();
56
    vfs = new VFS();
57
    $mb = jQuery.noConflict();
58

    
59
    var obj = window.arguments[0];
60

    
61
    uri = obj.inp;
62

    
63
    // Retrieve metadata for selected item (file or folder)
64
    metadata = vfs.getResourceMetadata(uri);
65
    // Store the permissions object separately
66
    permissions = metadata.permissions;
67

    
68
    // Store the name of the item (folder or file) in itemname
69
    itemname = itemName();
70
    
71
    // Build the UI of the tree
72
    treeobj = new treeHandler(uri);
73
        treeobj.setItemLabel();
74
    treeobj.addRow(uri);
75
}
76

    
77
/* Function to store the simplified share name in itemname variable.
78
   Reason is the name of the folder or file is stored in a different property in the json object
79
  (directoryName as opposed to name)
80
*/
81
function itemName() {
82
    var item;
83
    if(metadata.hasOwnProperty("directoryName")) {
84
        item = metadata.directoryName.replace(connection_obj.user_homepage().fileroot,'');
85
    } else {
86
        item = metadata.name.replace(connection_obj.user_homepage().fileroot,'');
87
    };
88
    return(item);
89
}
90

    
91
function promptbox(message) {
92
    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
93
    var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
94
    var result = prompts.confirm(window, "Confirm action", message);
95
    return(result);
96
}
97

    
98
function submitChanges() {
99
    
100
    var result = promptbox('Are you sure you want to modify shares on '+itemname+' ?');
101

    
102
    // Retrieve all modified values from the checkboxes and update the permissions object
103
    makeCurrent();
104
  
105
    // Build the permissions object
106
    var permgroup = new Object();
107
    permgroup.permissions = permissions;
108
    if (result == true) {
109
        var success = null;
110
        if(metadata.hasOwnProperty('readForAll')) {
111
            success = share_resource(uri, metadata);
112
        } else {
113
            success = share_resource(uri, permgroup);
114
        }
115
        if (success != true) {
116
            promptAlert('Unsuccesful updating shares with code '+success);
117
        }
118
        else {
119
            promptAlert('Succesful in updating shares');
120
        }
121
        window.close();
122
    }
123
}
124

    
125
function closeWindow() {
126

    
127
    var promptmessage = 'Are you sure you want to abandon changes to shares of the item '+itemname+' ?';
128
    var result = promptbox(promptmessage);
129

    
130
    if (result == true) {
131
        window.close();
132
    }
133
}
134

    
135
// Array Remove - By John Resig (MIT Licensed)
136
Array.prototype.remove = function(from, to) {
137
    var rest = this.slice((to || from) + 1 || this.length);
138
    this.length = from < 0 ? this.length + from : from;
139
    return this.push.apply(this, rest);
140
};
141

    
142
// Remove a whole row
143
function removeShare(event) {
144
    var tree = document.getElementById('shareTree');
145
    var chosenRow = tree.currentIndex;
146

    
147
    // chosenRow == -1 if user hasn't clicked any tree row
148
    if(chosenRow != -1) {
149
        permissions.remove(tree.currentIndex);
150
        treeobj.refreshTree();
151
    }
152
}
153

    
154
// Update the permissions object with the current values of checkboxes on the ui
155
function makeCurrent(event) {
156
    var ttree=document.getElementById('shareTree');
157

    
158
    var currows = ttree.view.rowCount;
159

    
160
    for(var i =0 ; i< currows ; i=i+1) {
161
        var rowElement = ttree.view.getItemAtIndex(i);
162

    
163
        permissions[i].read = $mb('treecell:eq(1)',rowElement).attr('value');
164
        permissions[i].write = $mb('treecell:eq(2)',rowElement).attr('value');
165
        permissions[i].modifyACL = $mb('treecell:eq(3)',rowElement).attr('value');
166
    }
167
}
168

    
169
// Obsolete function, will be removed in the future. The updates are done once, just before commiting
170
// the new permission object
171
function onTreeClicked(event) {
172
    makeCurrent(event); return;
173
}
174

    
175
/* Class for managing the tree */
176
function treeHandler(uri) {
177
/*  <treecols id="shareTree-treeCols">
178
    <!-- Make sure to set container="true" -->
179
    <treeitem container="true" open="true">
180
      <treerow>
181
        <treecell label="2"/>
182
        <treecell label="b"/>
183
      </treerow>
184
      <treechildren id="firstchild">
185
        <treeitem>
186
          <treerow>
187
            <treecell label="2a"/>
188
            <treecell label="ba"/>
189
          </treerow>
190
        </treeitem>
191
      </treechildren>
192
    </treeitem>
193
*/
194
    this.cleanRows = function(uri) {
195
        $mb('#topChild').empty();
196
    }
197
  
198
    this.refreshTree = function(uri) {
199
        this.cleanRows();
200
        this.addRow(uri);
201
    }
202
    
203
        /* The the label for the caption to the file or folder name */
204
        this.setItemLabel = function() {
205
                $mb('caption').attr({
206
                        label: itemname
207
                });
208
        }
209
        
210
    this.addRow = function(uri) {
211

    
212
        metadata.permissions.forEach( function( permobj) {
213
            var treeItem = document.createElement('treeitem');
214
            var treeRow = document.createElement('treerow');
215
            var treeCell1 = document.createElement('treecell');
216
            var treeCell2 = document.createElement('treecell');
217
            var treeCell3 = document.createElement('treecell');
218
            var treeCell4 = document.createElement('treecell');
219
            var checkbox1 = document.createElement('checkbox');
220
            var checkbox2 = document.createElement('checkbox');
221
            var checkbox3 = document.createElement('checkbox');
222
    
223
            $mb('#topChild').append(treeItem);
224
            $mb(treeItem).append(treeRow);
225
            $mb(treeRow).append(treeCell1);
226
            $mb(treeRow).append(treeCell2);
227
            $mb(treeRow).append(treeCell3);
228
            $mb(treeRow).append(treeCell4);
229
    
230
            var itemvalue;
231
            if(permobj.hasOwnProperty("user")) {
232
                itemvalue = permobj.user;
233
            } else {
234
                itemvalue = permobj.group;
235
            };
236
            
237
            $mb(treeCell1).attr({
238
                label: itemvalue
239
            });
240
            $mb(treeCell2).attr({
241
                value: permobj.read
242
            });
243
            $mb(treeCell3).attr({
244
                value: permobj.write
245
            });
246
            $mb(treeCell4).attr({
247
                value: permobj.modifyACL
248
            });
249
        
250
        });
251
        
252
        // Set the readForAll flag in the GUI depending on the initial value in metadata ...
253
        if(metadata.hasOwnProperty('directoryName')) {
254
            // Groups do not have readForAll properties ...
255
            $mb('checkbox').remove();
256
        } else {
257
            if(metadata.hasOwnProperty('readForAll')) {
258
                if(metadata.readForAll == true) {
259
                    $mb('checkbox').attr({
260
                    checked : "true"
261
                    });
262
                }
263
                else {
264
                    $mb('checkbox').attr({
265
                        checked : "false"
266
                    });
267
                }
268
            }
269
        }
270
    }
271
}
272

    
273
// Call the addGroup window
274
function addGroup() {
275
    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
276

    
277
    // Get available groups
278
    var grouprequest = connection_obj.rest_request_get(connection_obj.user_homepage().groups, '');
279

    
280
    var jsongroup;
281
    if( connection_obj.success(grouprequest.status) ) {
282
        // parse the response to a JSON object
283
        jsongroup = JSON.parse(grouprequest.responseText);
284
    }
285

    
286
    // retvals stores both input and output parameters from calling window.openDialog
287
    var retvals = {inp: jsongroup, out : null};
288
    window.openDialog("addgroup.xul", "Group", "chrome,dialog,modal,resizable", retvals).focus();
289

    
290
    // Check if we have valid return values
291
    if (retvals.out != null) {
292
        // Ok has been clicked
293
        var ret = pushNewUserGroup(retvals.out,'group');
294
        if(ret) {
295
            treeobj.refreshTree();
296
        } else {
297
            promptAlert('Group already exists');
298
        }
299
    }
300
}
301

    
302
/* bring the new user prompt and update the permissions object if succesful */
303
function addUser() {
304
    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
305

    
306
    //prompt for username
307
    var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
308
                            .getService(Components.interfaces.nsIPromptService);
309
    input = {value: ""};
310
    check = {value: false};
311

    
312
    var results = prompts.prompt(null, 'Add user to shares', 'Username:',input,null,check);
313
    if (results) {
314
        // Ok has been clicked
315
        
316
        // Show dialog with the usernames similar to what has been typed
317
        var userobj = findUser(input.value);
318
        if (userobj == false) {
319
            promptAlert('Name not found');
320
            return;
321
        } else {
322
            var ok = checkUserExistsInShare(userobj.username);
323
            if (ok == false) {
324
                promptAlert('User already exists in group');
325
                return;
326
            }
327
            else {
328
                var ret = pushNewUserGroup(userobj.username,'user');
329
                if(ret) {
330
                    treeobj.refreshTree();
331
                } else {
332
                    promptAlert('User already exists');
333
                }
334
            }
335
        }
336
    }
337
}
338

    
339
/* This function pushes the new user or group (with no permissions=default) to the permission object
340
after checking if he/it already exists
341
type should be 'group' or 'user'
342
*/
343
function pushNewUserGroup(value, type) {
344
    for each (var permrow in permissions) {
345
        if(permrow.hasOwnProperty(type)) {
346
            if (permrow[type] == value) {
347
                // already exists ...
348
                return false;
349
            }
350
        }
351
    };
352

    
353
    // Build the new permissions object (user or group)
354
    var newp = new Object;
355
    newp.modifyACL = 'false';
356
    newp.write = 'false';
357
    newp.read = 'false';
358
    newp[type] = value;
359

    
360
    permissions.push(newp);
361
    return true;
362
}
363

    
364
// function to set the readForAll to true
365
function makePublic(event) {
366
    $mb = jQuery.noConflict();
367
    var value = $mb(event.currentTarget).attr('checked');
368
    // remember the event shows us the state BEFORE being checked so true/false is reversed
369
    if(value == "true") {
370
        metadata.readForAll = false;
371
    } else {
372
        metadata.readForAll = true;
373
    }
374
}
375

    
376
// This will display a prompt with Ok or Cancel, the result needs to be checked
377
function promptBox(message) {
378
    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
379
    var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
380
    var result = prompts.confirm(window, "Confirm action", message);
381
    
382
    return result;
383
}
384

    
385
// This is just an alert box, using the prompt xpcom service
386
function promptAlert(message) {
387
    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
388
    var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
389
    prompts.alert(window, "Information", message);
390
}