Completed
Push — master ( c719b2...13f554 )
by Thomas
48:38
created

Files_PaperHive.NewFileMenuPlugin.attach   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
c 0
b 0
f 0
nc 1
dl 0
loc 4
rs 10
nop 1
1
/**
2
 * @author Piotr Mrowczynski <[email protected]>
3
 *
4
 * @copyright Copyright (c) 2017, Piotr Mrowczynski.
5
 * @license AGPL-3.0
6
 *
7
 * This code is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU Affero General Public License, version 3,
9
 * as published by the Free Software Foundation.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU Affero General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Affero General Public License, version 3,
17
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
18
 *
19
 */
20
21
/**
22
 *
23
 * global: OCA, OC, _
24
 *
25
 * */
26
27
var Files_PaperHive;
28
Files_PaperHive = {
29
30
    /**
31
     * Holds the notification container
32
     */
33
    $notification: null,
34
35
    /**
36
     * Holds the notification html
37
     */
38
    container: null,
39
40
    /**
41
     * Holds the notification html options
42
     */
43
    containerOptions: null,
44
45
    /**
46
     * Gets if is paperhive file
47
     */
48
    isPaperHive: function (fileName) {
49
        var parts = fileName.split('.');
50
        var extension = "";
51
        if (parts.length > 1) {
52
            extension = parts.pop();
53
        }
54
55
        return (extension === 'paperhive');
56
57
    },
58
59
    /**
60
     * Registers the file actions
61
     */
62
    registerFileActions: function () {
63
        var mimetype = 'application/octet-stream';
64
65
        OCA.Files.fileActions.registerAction({
66
            name: 'ShowPaper',
67
            displayName: '',
68
            altText: t('core', 'Show Paper'),
69
            mime: mimetype,
70
            actionHandler: _.bind(this._onPaperHiveTrigger, this),
0 ignored issues
show
Bug introduced by
The variable _ seems to be never declared. If this is a global, consider adding a /** global: _ */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
71
            permissions: OC.PERMISSION_READ,
72
            iconClass: 'icon-filetype-paperhive',
73
            type: OCA.Files.FileActions.TYPE_INLINE,
74
            render: function (actionSpec, isDefault, context) {
75
                if (OCA.Files_PaperHive.isPaperHive(context.$file.attr('data-file'))) {
76
                    return OCA.Files.fileActions._defaultRenderAction.call(OCA.Files.fileActions, actionSpec, isDefault, context);
77
                }
78
                // don't render anything
79
                return null;
80
            }
81
        });
82
    },
83
84
    /**
85
     * Setup on page load
86
     */
87
    initialize: function () {
88
        $(document).bind('mouseup', this._onClickDocument);
89
        this.$notification = null;
90
        this.registerFileActions();
91
    },
92
93
    createContainer: function () {
94
        var self = this;
95
        $.ajax({
96
            type: 'GET',
97
            url: OC.generateUrl('/apps/files_paperhive/ajax/getpaperhivedetails')
98
        })
99
            .done(function (phdata) {
100
                var containerString = '<div class="icon-paperhive"></div>' +
101
                    '<div><p class="normal">Visit PaperHive at </p><p class="normal">' + phdata.paperhive_base_url + '</p><p class="normal"> and transform reading into a process of collaboration!</p></div>' +
102
                    //'<div><span></span></div>' +
103
                    '<div><p class="bold">Your Book ID </p><p class="normal">is the last fragment of PaperHive document URL.</p></div>' +
104
                    '<div><p class="normal">Example: </p><p class="normal">' + phdata.paperhive_base_url + phdata.paperhive_document_url + '</p><p class="bold">Ra5WnkxImoOE</p></div>';
105
106
                self.container = $('<div class="notification_paperhive"></div>').html(
107
                    containerString
108
                );
109
                self.containerOptions = {
110
                    isHTML: true,
111
                    timeout: 30
112
                };
113
                self.$notification = OC.Notification.showHtml(
114
                    self.container,
115
                    self.containerOptions
116
                );
117
            })
118
            .fail(function (jqXHR) {
119
                var message;
120
121
                try {
122
                    message = JSON.parse(jqXHR.responseText).message;
123
                } catch (e) {
0 ignored issues
show
Coding Style Comprehensibility Best Practice introduced by
Empty catch clauses should be used with caution; consider adding a comment why this is needed.
Loading history...
124
                }
125
126
                OC.dialogs.alert(message, t('files_paperhive', 'An error occurred!'));
127
            });
128
    },
129
130
    createNotification: function () {
131
        if (this.$notification === null) {
132
            this.createContainer();
133
        }
134
    },
135
136
    hideNotification: function () {
137
        if (!OC.Notification.isHidden() && this.$notification != null) {
138
            OC.Notification.hide(this.$notification);
139
            this.$notification = null;
140
        }
141
    },
142
143
    failureNotification: function (message) {
144
        OC.dialogs.alert(message, t('files_paperhive', 'An error occurred!'));
145
    },
146
147
    /**
148
     * Loads the data through AJAX
149
     */
150
    loadFile: function (dir, filename, fetchDiscussions, success, failure) {
151
        $.get(
152
            OC.generateUrl('/apps/files_paperhive/ajax/loadfile'),
153
            {
154
                filename: filename,
155
                dir: dir,
156
                fetchDiscussions: fetchDiscussions
157
            }
158
        ).done(function (fileContents) {
159
            // Call success callback
160
            success(fileContents);
161
        }).fail(function (jqXHR) {
162
            var message;
163
164
            try {
165
                message = JSON.parse(jqXHR.responseText).message;
166
            } catch (e) {
0 ignored issues
show
Coding Style Comprehensibility Best Practice introduced by
Empty catch clauses should be used with caution; consider adding a comment why this is needed.
Loading history...
167
            }
168
169
            failure(message);
170
        });
171
    },
172
173
    validatePaperHiveJSON: function (paperHiveObject) {
174
        //validate request
175
        var successResponseTags = ['id', 'authors', 'title'];
176
        var errorResponseTags = ['status', 'message'];
177
        for (var responseErrorTag in errorResponseTags) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
178
            if (paperHiveObject.hasOwnProperty(errorResponseTags[responseErrorTag])) {
179
                return false;
180
            }
181
        }
182
183
        for (var responseSuccessTag in successResponseTags) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
184
            if (!paperHiveObject.hasOwnProperty(successResponseTags[responseSuccessTag])) {
185
                return false;
186
            }
187
        }
188
189
        return true;
190
    },
191
192
    /**
193
     * Handles request for book contents to PaperHive API
194
     */
195
    getPaperHiveBook: function (dir, bookID, success, failure) {
196
        $.get(
197
            OC.generateUrl('/apps/files_paperhive/ajax/getpaperhivedocument'),
198
            {
199
                dir: dir,
200
                bookID: bookID
201
            }
202
        ).done(function (paperHiveData) {
203
            // Success - found valid Book at PaperHive
204
            success(paperHiveData);
205
        }).fail(function (jqXHR) {
206
            var message;
207
208
            try {
209
                message = JSON.parse(jqXHR.responseText).message;
210
            } catch (e) {
0 ignored issues
show
Coding Style Comprehensibility Best Practice introduced by
Empty catch clauses should be used with caution; consider adding a comment why this is needed.
Loading history...
211
            }
212
213
            failure("Error occured while connecting to PaperHive: " + message);
214
        });
215
216
    },
217
218
    setDiscussionCount: function ($tr) {
219
        OCA.Files_PaperHive.loadFile(
220
            $tr.attr('data-path'),
221
            $tr.attr('data-file'),
222
            "true",
223
            function (paperHiveData) {
224
                var discussionsCount = paperHiveData.paperhive_discussion_count;
225
                OCA.Files_PaperHive._updatePaperHiveFileData($tr, discussionsCount);
226
            },
227
            function (message) {
0 ignored issues
show
Unused Code introduced by
The parameter message is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
228
            }
229
        );
230
    },
231
232
    _updatePaperHiveFileData: function ($tr, discussionCount) {
233
        $tr.find('.filename .thumbnail').css('background-image', 'url(' + OC.imagePath('files_paperhive', 'paperhive-icon') + ')');
234
        var action = $tr.find('.fileactions .action[data-action="ShowPaper"]');
235
236
        action.addClass('shared-style');
237
        var icon = action.find('.icon');
238
239
        var message = '';
240
        if (discussionCount === -1) {
241
            message = t('files_paperhive', 'Discuss');
242
        } else {
243
            message = t('files_paperhive', 'Discuss') + ' (' + discussionCount + ')';
244
        }
245
        action.html('<span> ' + message + '</span>').prepend(icon);
246
    },
247
248
    /**
249
     * Handles the FileAction click event
250
     */
251
    _onPaperHiveTrigger: function (filename, context) {
252
        // Get the file data
253
        this.loadFile(
254
            context.dir,
255
            filename,
256
            "false",
257
            function (paperHiveData) {
258
                try {
259
                    var paperHiveObject = JSON.parse(paperHiveData.paperhive_document);
260
                } catch (e) {
261
                    OC.dialogs.alert("Your [.paperhive] file is not a valid PaperHive document, please redownload document");
262
                    return;
263
                }
264
265
                if (!OCA.Files_PaperHive.validatePaperHiveJSON(paperHiveObject)) {
266
                    OC.dialogs.alert("Your [.paperhive] file is not a valid PaperHive document, please redownload document");
267
                    return;
268
                }
269
270
                var paperhiveUrl = paperHiveData.paperhive_base_url + paperHiveData.paperhive_document_url + paperHiveObject.id;
271
272
                var w = window.open(paperhiveUrl, '_blank');
273
                if (!w) {
274
                    window.location.href = paperhiveUrl;
275
                }
276
            },
277
            function (message) {
278
                // Oh dear
279
                OC.dialogs.alert(message, t('files_paperhive', 'An error occurred!'));
280
            }
281
        );
282
    },
283
284
    /**
285
     * Handles event when clicking outside editor
286
     */
287
    _onClickDocument: function (event) {
288
        var menuItem = $(event.target).closest('.menuitem');
289
        var notificationItem = $(event.target).closest('.notification_paperhive');
290
291
        if (menuItem.length && menuItem.attr('data-action') === 'paperhive') {
292
            OCA.Files_PaperHive.createNotification();
293
        } else if (!notificationItem.length) {
294
            OCA.Files_PaperHive.hideNotification();
295
        }
296
    }
297
};
298
299
Files_PaperHive.NewFileMenuPlugin = {
300
301
    attach: function (menu) {
302
        var fileList = menu.fileList;
303
304
        // only attach to main file list, public view is not supported yet
305
        if (fileList.id !== 'files') {
306
            return;
307
        }
308
309
        // register the new menu entry
310
        menu.addMenuEntry({
311
            id: 'paperhive',
312
            displayName: t('files_paperhive', 'PaperHive Book'),
313
            templateName: t('files_paperhive', 'Your Book ID'),
314
            iconClass: 'icon-filetype-paperhive',
315
            fileType: 'file',
316
            actionHandler: function (bookID) {
317
                // Hide any remaining notification
318
                OCA.Files_PaperHive.hideNotification();
319
320
                // Get the file data from PaperHive API
321
                var dir = fileList.getCurrentDirectory();
322
                var $saveNot = OC.Notification.showHtml(t('files_paperhive', 'Saving...'));
323
                OCA.Files_PaperHive.getPaperHiveBook(
324
                    dir,
325
                    bookID,
326
                    function (paperHiveData) {
327
                        var filename = paperHiveData.filename+paperHiveData.extension;
328
329
                        fileList.filesClient.getFileInfo(
330
                            paperHiveData.path,
331
                            {
332
                                properties: fileList._getWebdavProperties()
333
                            })
334
                            .then(function(status, data) {
335
                                fileList.add(data, {scrollTo: true});
336
                                var $tr = fileList.findFileEl(filename);
337
                                OCA.Files_PaperHive._updatePaperHiveFileData($tr, paperHiveData.discussionCount);
338
                                OC.Notification.hide($saveNot);
339
                            })
340
                            .fail(function(status) {
0 ignored issues
show
Unused Code introduced by
The parameter status is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
341
                                OC.Notification.hide($saveNot);
342
                                OCA.Files_PaperHive.failureNotification(t('files_paperhive', 'Please reload the page, error occured'));
343
                            });
344
                    },
345
                    function (message) {
346
                        OC.Notification.hide($saveNot);
347
                        OCA.Files_PaperHive.failureNotification(message);
348
                    }
349
                );
350
            }
351
        });
352
    }
353
};
354
355
Files_PaperHive.FileMenuPlugin = {
356
357
    attach: function (fileList) {
358
        // use delegate to catch the case with multiple file lists
359
        fileList.$el.on('fileActionsReady', function (ev) {
360
            var $files = ev.$files;
361
            var $phfiles = [];
362
363
            _.each($files, function (file) {
0 ignored issues
show
Bug introduced by
The variable _ seems to be never declared. If this is a global, consider adding a /** global: _ */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
364
                var $tr = $(file);
365
366
                if (OCA.Files_PaperHive.isPaperHive($tr.attr('data-file'))) {
367
                    OCA.Files_PaperHive._updatePaperHiveFileData($tr, -1);
368
                    $phfiles.push(file);
369
                }
370
            });
371
372
            setTimeout(function () {
373
                _.each($phfiles, function (file) {
0 ignored issues
show
Bug introduced by
The variable _ seems to be never declared. If this is a global, consider adding a /** global: _ */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
374
                    var $tr = $(file);
375
                    OCA.Files_PaperHive.setDiscussionCount($tr);
376
                });
377
            }, 20);
378
379
        });
380
    }
381
};
382
383
OCA.Files_PaperHive = Files_PaperHive;
384
385
OC.Plugins.register('OCA.Files.NewFileMenu', Files_PaperHive.NewFileMenuPlugin);
386
OC.Plugins.register('OCA.Files.FileList', Files_PaperHive.FileMenuPlugin);
387
388
$(document).ready(function () {
389
    OCA.Files_PaperHive.initialize();
390
});
391