~sil/+junk/u1fn9

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
import QtQuick 1.1
import com.nokia.meego 1.0 
import "sha1.js" as SHA1
import "oauth.js" as OAUTH

Page {
    id: listPage
    tools: commonTools

    property string u1path: ""
    property string totalDownloadSizeFriendly: ""
    property int folderCount: 0
    property int filesCount: 0
    property variant oauth_creds;
    property string u1_API_ROOT: "https://one.ubuntu.com/api/file_storage/v1";



    function browseFolder(newpath) {
        var component = Qt.createComponent("filesPage.qml")
        if (component.status == Component.Ready) {
            var obj = component.createObject(rootWindow, { u1path: newpath });
            pageStack.push(obj);
        } else {
            console.log("Error loading component:", component.errorString());
        }
    }
    
    function downloadAllFiles() {
        for (var i=0; i<pagesModel.count; i++) {
            if (pagesModel.get(i).kind == "file" && pagesModel.get(i).state == "ready") {
                downloader.downloadurl(pagesModel.get(i).destpath, pagesModel.get(i).downloadpath);
                pagesModel.setProperty(i, "state", "downloading");
            }
        }
    }

    BusyIndicator {
        id: spinner
        platformStyle: BusyIndicatorStyle { size: "large" }
        running: true
        visible: true
        anchors.verticalCenter: listPage.verticalCenter
        anchors.horizontalCenter: listPage.horizontalCenter
    }
    
    QueryDialog {
        id: fileDetailsDialog
        property string fileName: "filename"
        property string publicUrl: ""
        message: {
            var msg = fileDetailsDialog.fileName.substr(0,15) + "&shy;" + fileDetailsDialog.fileName.substr(15) + "<br>";
            return msg;
        }
        icon: "image://theme/icon-m-sharing-document"
        titleText: "File Details"
        acceptButtonText: "OK"
        rejectButtonText: ""
        onAccepted: {
            // do nothing; they hit OK
        }
    }
    
    SelectionDialog {
        id: fileLongPressDialog
        property string fileName: ""
        property string fileState: "ready"
        property string downloadPath: "ready"
        property string publicUrl: ""
    
        titleText: fileLongPressDialog.fileName

        model: ListModel {  
        }  
        onSelectedIndexChanged: {
            var menuChoice = fileLongPressDialog.model.get(fileLongPressDialog.selectedIndex).name;
            if (menuChoice == "Details") {
                console.log("show details of " + fileLongPressDialog.downloadPath);
                fileDetailsDialog.fileName = fileName;
                fileDetailsDialog.publicUrl = publicUrl;
                fileDetailsDialog.open();
            } else if (menuChoice == "Share public URL") {
                downloader.meegosharepublicurl(fileLongPressDialog.fileName, fileLongPressDialog.publicUrl);
            } else if (menuChoice == "Delete from N9") {
                downloader.deletefile(fileLongPressDialog.downloadPath);
                updateDownloadedFile(fileLongPressDialog.downloadPath, "ready");
            } else if (menuChoice == "Delete from Ubuntu One") {
                console.log("delete u1 " + fileLongPressDialog.downloadPath);
            } else if (menuChoice == "Publish") {
                console.log("publish " + fileLongPressDialog.downloadPath);
                var parts = fileLongPressDialog.downloadPath.split("/");
                var nparts = []
                for (var j=0; j<parts.length; j++) {
                    nparts.push(encodeURIComponent(parts[j]));
                }
                var url = listPage.u1_API_ROOT + "/~/" + nparts.join("/");
                var x = new XMLHttpRequest();
                var message = {
                    action: url,
                    method: "GET",
                    parameters: {oauth_signature_method: "PLAINTEXT"}
                };
                OAUTH.OAuth.completeRequest(message, listPage.oauth_creds);
                OAUTH.OAuth.SignatureMethod.sign(message, listPage.oauth_creds);
                x.open(message.method, url + '?' + OAUTH.OAuth.formEncode(message.parameters));
                x.onreadystatechange = function() {
                    if (x.readyState == 4) {
                        if (x.status == 200 || x.status == 0) {
                            console.log(x.responseText);
                        } else {
                            console.log("failed to get data " + x.status + "," + url);
                        }
                    }
                }
                x.send();
            } else if (menuChoice == "Open") {
                downloader.openfile(fileLongPressDialog.downloadPath);
            } else {
                console.log("Internal error: bad menu item")
            }
        }
        
        selectedIndex: -1
        
        function populate() {
            var m = fileLongPressDialog.model;
            m.clear();
            m.append({"name": "Cancel"});
            if (fileLongPressDialog.fileState == "downloaded") {
                m.append({"name": "Open"});
                m.append({"name": "Delete from N9"});
            }
            if (fileLongPressDialog.publicUrl) {
                m.append({"name": "Share public URL"});
            }
            /*
            m.append({"name": "Publish"});
            m.append({"name": "Delete from Ubuntu One"});
            */
            m.append({"name": "Details"});
        }
    }

    ListModel {
        id: pagesModel
        Component.onCompleted: {
            spinner.visible = true;
            var creds = downloader.getCredentials();
            var oauth = JSON.parse(creds);
            listPage.oauth_creds = oauth;

            var friendly = function(size) {
                if (size < 1024) return size + "bytes";
                if (size < 1024 * 1024) return (size / 1024).toFixed(1) + "KB";
                if (size < 1024 * 1024 * 1024) return (size / 1024 / 1024).toFixed(1) + "MB";
                return (size / 1024 / 1024 / 1024).toFixed(1) + "GB";
            }

            var x = new XMLHttpRequest();
            /* put in the 443 so that the QUrl downloader verifies OAuth correctly */
            var CONTENT_ROOT = "https://files.one.ubuntu.com:443";
            var url = listPage.u1_API_ROOT + u1path;
            var message = {
                action: url,
                method: "GET",
                parameters: {include_children: "true"}
            };
            OAUTH.OAuth.completeRequest(message, listPage.oauth_creds);
            OAUTH.OAuth.SignatureMethod.sign(message, listPage.oauth_creds);
            x.open(message.method, url + '?' + OAUTH.OAuth.formEncode(message.parameters));
            x.onreadystatechange = function() {
                if (x.readyState == 4) {
                    if (x.status == 200 || x.status == 0) {
                        try {
                            var data = JSON.parse(x.responseText);
                        } catch(e) {
                            throw new Error("Could not parse JSON: " + x.responseText);
                        }
                        var kidslist = [];
                        var totalDownloadSize = 0;
                        
                        // special handling for the very root node
                        if (u1path === "") {
                            kidslist.push({
                                title: "Ubuntu One",
                                destpath: "/~/Ubuntu%20One",
                                subtitle: "Always synced to machines",
                                kind: "directory",
                                state: "ready"
                            });
                            for (var i=0; i<data.user_node_paths.length; i++) {
                                var parts = data.user_node_paths[i].split("/");
                                var nparts = []
                                for (var j=0; j<parts.length; j++) {
                                    nparts.push(encodeURIComponent(parts[j]));
                                }
                                var title = data.user_node_paths[i].substr(3);
                                if (title == ".ubuntuone/Purchased from Ubuntu One") {
                                    title = "Purchased Music"
                                }
                                kidslist.push({
                                    title: title,
                                    destpath: nparts.join("/"),
                                    subtitle: "Synced folder",
                                    kind: "directory",
                                    state: "ready"
                                });
                            }
                        } else {
                            var kids = data.children;
                            for (var i=0; i<kids.length; i++) {
                                var pathElements = kids[i].path.split("/");
                                var destpath, subtitle;
                                if (kids[i].kind == "file") {
                                    var parts = kids[i].content_path.split("/");
                                    var nparts = []
                                    for (var j=0; j<parts.length; j++) {
                                        nparts.push(encodeURIComponent(parts[j]));
                                    }
                                    var furl = CONTENT_ROOT + nparts.join("/");
                                    var message = {
                                        action: furl,
                                        method: "GET",
                                        parameters: { oauth_signature_method: "PLAINTEXT" }
                                    };
                                    OAUTH.OAuth.completeRequest(message, oauth);
                                    OAUTH.OAuth.SignatureMethod.sign(message, oauth);
                                    destpath = furl + '?' + OAUTH.OAuth.formEncode(message.parameters);
                                    subtitle = friendly(kids[i].size);
                                    totalDownloadSize += kids[i].size;
                                    listPage.filesCount += 1;
                                    if (kids[i].public_url) subtitle += ", public";
                                } else {
                                    destpath = encodeURI(kids[i].resource_path);
                                    subtitle = "";
                                    listPage.folderCount += 1;
                                }
                                kidslist.push({
                                    title: pathElements[pathElements.length-1],
                                    destpath: destpath,
                                    subtitle: subtitle,
                                    kind: kids[i].kind,
                                    downloadpath: kids[i].resource_path.substr(3),
                                    state: "ready",
                                    public_url: kids[i].public_url
                                });
                            }
                        }
                        
                        listPage.totalDownloadSizeFriendly = friendly(totalDownloadSize);
                        
                        kidslist.sort(function(a,b) {
                            if (a.kind < b.kind) return -1;
                            if (a.kind > b.kind) return 1;
                            if (a.title < b.title) return -1;
                            if (a.title > b.title) return 1;
                            return 0;
                        });
                        if (kidslist.length == 0) {
                            kidslist.push({title: "No files", kind: "empty", subtitle: "", destpath: "", state: "ready"});
                        }
                        for (i=0; i<kidslist.length; i++) {
                            pagesModel.append(kidslist[i]);
                            if (kidslist[i].downloadpath) {
                                downloader.isalreadydownloaded(kidslist[i].downloadpath);
                            }
                        }
                        spinner.visible = false;
                    } else {
                        console.log("error rq2 " + x.status);
                    }
                }
            };
            x.send();

        }
    }

    Rectangle {
        id: headerback
        color: "#dd4814"
        width: parent.width
        height: headerbar.height * 2
        anchors.top: parent.top
        z: 2
    }

    Label {
        id: headerbar
        text: {
            var pathElements = listPage.u1path.split("/");
            var out = decodeURIComponent(pathElements[pathElements.length-1]);
            return out ? out : "Ubuntu One"
        }
        font.weight: Font.Bold
        font.pixelSize: 26
        elide: Text.ElideMiddle
        color: "white"
        verticalAlignment: Text.AlignVCenter
        horizontalAlignment: Text.AlignHCenter
        anchors.top: parent.top
        width: parent.width
        anchors.topMargin: 10
        z: 2
        anchors.horizontalCenter: parent.horizontalCenter
    }
    
    ListView {
        id: listView
        anchors.top: headerback.bottom
        anchors.left: listPage.left
        anchors.right: listPage.right
        anchors.bottom: listPage.bottom
        model: pagesModel    
        
        delegate:  Item {
            id: listItem
            height: 88
            width: parent.width

            BorderImage {
                id: background
                anchors.fill: parent
                // Fill page borders
                anchors.leftMargin: -listPage.anchors.leftMargin
                anchors.rightMargin: -listPage.anchors.rightMargin
                visible: mouseArea.pressed
                source: "image://theme/meegotouch-list-background-pressed-center"
            }

            Row {
                anchors.fill: parent

                BusyIndicator {
                    anchors.verticalCenter: parent.verticalCenter
                    id: busydownloading
                    platformStyle: BusyIndicatorStyle { size: "small" }
                    running: true
                    visible: model.state == "downloading"
                }


                Image {
                    id: statusindicator
                    anchors.verticalCenter: parent.verticalCenter
                    visible: model.state != "downloading"
                    source: {
                        var iconname = "gray";
                        if (kind == "directory") {
                            iconname = "directory";
                        } else if (kind == "file") {
                            if (model.state == "ready") {
                                iconname = "favorite-unmark"
                            } else if (model.state == "downloaded") {
                                iconname = "favorite-mark"
                            } else if (model.state == "downloading") {
                                iconname = "silver" // but ignored because the busyindicator will do it
                            } else {
                                console.log("found weird state: " + model.state);
                            }
                        }
                        return "image://theme/icon-m-common-" + iconname + (theme.inverted ? "-inverse" : "")
                    }
                }
                Column {
                    anchors.verticalCenter: parent.verticalCenter
                    Label {
                        id: mainText
                        text: model.title
                        font.weight: Font.Bold
                        font.pixelSize: 26
                        elide: Text.ElideMiddle
                        width: listView.width - busydownloading.width - statusindicator.width - browsearrow.width
                    }
                    Label {
                        id: subText
                        text: model.subtitle
                        font.weight: Font.Light
                        font.pixelSize: 22
                        color: "#dd4814"
                        visible: text != ""
                        horizontalAlignment: Text.AlignRight
                    }
                }
            }
            Image {
                id: browsearrow
                source: "image://theme/icon-m-common-drilldown-arrow" + (theme.inverted ? "-inverse" : "")
                anchors.right: parent.right;
                anchors.verticalCenter: parent.verticalCenter
                visible: kind == "directory"
            }
            MouseArea {
                id: mouseArea
                anchors.fill: background
                onClicked: {
                    if (kind == "directory") {                
                        listPage.browseFolder(destpath);
                    } else {
                        if (model.state == "ready") {
                            console.log("start downloading, with indicator width " + statusindicator.width);
                            busydownloading.width = statusindicator.width;
                            downloader.downloadurl(destpath, downloadpath);
                            pagesModel.setProperty(index, "state", "downloading");
                        } else {
                            console.log("already downloading");
                        }
                    }
                }
                onPressAndHold: {
                    if (kind == "directory") {                
                        console.log("long press on directory");
                    } else {
                        fileLongPressDialog.fileName = title;
                        fileLongPressDialog.fileState = model.state;
                        fileLongPressDialog.downloadPath = model.downloadpath;
                        fileLongPressDialog.publicUrl = model.public_url || "";
                        fileLongPressDialog.populate();
                        fileLongPressDialog.open();
                    }
                }
            }
        }
    }
    ScrollDecorator {
        flickableItem: listView
    }
}