]> BookStack Code Mirror - bookstack/blob - resources/assets/js/controllers.js
Fixed attachment base-url usage and non-existant images
[bookstack] / resources / assets / js / controllers.js
1 "use strict";
2
3 import moment from 'moment';
4 import 'moment/locale/en-gb';
5 moment.locale('en-gb');
6
7 export default function (ngApp, events) {
8
9     ngApp.controller('ImageManagerController', ['$scope', '$attrs', '$http', '$timeout', 'imageManagerService',
10         function ($scope, $attrs, $http, $timeout, imageManagerService) {
11
12             $scope.images = [];
13             $scope.imageType = $attrs.imageType;
14             $scope.selectedImage = false;
15             $scope.dependantPages = false;
16             $scope.showing = false;
17             $scope.hasMore = false;
18             $scope.imageUpdateSuccess = false;
19             $scope.imageDeleteSuccess = false;
20             $scope.uploadedTo = $attrs.uploadedTo;
21             $scope.view = 'all';
22
23             $scope.searching = false;
24             $scope.searchTerm = '';
25
26             var page = 0;
27             var previousClickTime = 0;
28             var previousClickImage = 0;
29             var dataLoaded = false;
30             var callback = false;
31
32             var preSearchImages = [];
33             var preSearchHasMore = false;
34
35             /**
36              * Used by dropzone to get the endpoint to upload to.
37              * @returns {string}
38              */
39             $scope.getUploadUrl = function () {
40                 return window.baseUrl('/images/' + $scope.imageType + '/upload');
41             };
42
43             /**
44              * Cancel the current search operation.
45              */
46             function cancelSearch() {
47                 $scope.searching = false;
48                 $scope.searchTerm = '';
49                 $scope.images = preSearchImages;
50                 $scope.hasMore = preSearchHasMore;
51             }
52             $scope.cancelSearch = cancelSearch;
53
54
55             /**
56              * Runs on image upload, Adds an image to local list of images
57              * and shows a success message to the user.
58              * @param file
59              * @param data
60              */
61             $scope.uploadSuccess = function (file, data) {
62                 $scope.$apply(() => {
63                     $scope.images.unshift(data);
64                 });
65                 events.emit('success', 'Image uploaded');
66             };
67
68             /**
69              * Runs the callback and hides the image manager.
70              * @param returnData
71              */
72             function callbackAndHide(returnData) {
73                 if (callback) callback(returnData);
74                 $scope.hide();
75             }
76
77             /**
78              * Image select action. Checks if a double-click was fired.
79              * @param image
80              */
81             $scope.imageSelect = function (image) {
82                 var dblClickTime = 300;
83                 var currentTime = Date.now();
84                 var timeDiff = currentTime - previousClickTime;
85
86                 if (timeDiff < dblClickTime && image.id === previousClickImage) {
87                     // If double click
88                     callbackAndHide(image);
89                 } else {
90                     // If single
91                     $scope.selectedImage = image;
92                     $scope.dependantPages = false;
93                 }
94                 previousClickTime = currentTime;
95                 previousClickImage = image.id;
96             };
97
98             /**
99              * Action that runs when the 'Select image' button is clicked.
100              * Runs the callback and hides the image manager.
101              */
102             $scope.selectButtonClick = function () {
103                 callbackAndHide($scope.selectedImage);
104             };
105
106             /**
107              * Show the image manager.
108              * Takes a callback to execute later on.
109              * @param doneCallback
110              */
111             function show(doneCallback) {
112                 callback = doneCallback;
113                 $scope.showing = true;
114                 $('#image-manager').find('.overlay').css('display', 'flex').hide().fadeIn(240);
115                 // Get initial images if they have not yet been loaded in.
116                 if (!dataLoaded) {
117                     fetchData();
118                     dataLoaded = true;
119                 }
120             }
121
122             // Connects up the image manger so it can be used externally
123             // such as from TinyMCE.
124             imageManagerService.show = show;
125             imageManagerService.showExternal = function (doneCallback) {
126                 $scope.$apply(() => {
127                     show(doneCallback);
128                 });
129             };
130             window.ImageManager = imageManagerService;
131
132             /**
133              * Hide the image manager
134              */
135             $scope.hide = function () {
136                 $scope.showing = false;
137                 $('#image-manager').find('.overlay').fadeOut(240);
138             };
139
140             var baseUrl = window.baseUrl('/images/' + $scope.imageType + '/all/');
141
142             /**
143              * Fetch the list image data from the server.
144              */
145             function fetchData() {
146                 var url = baseUrl + page + '?';
147                 var components = {};
148                 if ($scope.uploadedTo) components['page_id'] = $scope.uploadedTo;
149                 if ($scope.searching) components['term'] = $scope.searchTerm;
150
151
152                 var urlQueryString = Object.keys(components).map((key) => {
153                     return key + '=' + encodeURIComponent(components[key]);
154                 }).join('&');
155                 url += urlQueryString;
156
157                 $http.get(url).then((response) => {
158                     $scope.images = $scope.images.concat(response.data.images);
159                     $scope.hasMore = response.data.hasMore;
160                     page++;
161                 });
162             }
163             $scope.fetchData = fetchData;
164
165             /**
166              * Start a search operation
167              */
168             $scope.searchImages = function() {
169
170                 if ($scope.searchTerm === '') {
171                     cancelSearch();
172                     return;
173                 }
174
175                 if (!$scope.searching) {
176                     preSearchImages = $scope.images;
177                     preSearchHasMore = $scope.hasMore;
178                 }
179
180                 $scope.searching = true;
181                 $scope.images = [];
182                 $scope.hasMore = false;
183                 page = 0;
184                 baseUrl = window.baseUrl('/images/' + $scope.imageType + '/search/');
185                 fetchData();
186             };
187
188             /**
189              * Set the current image listing view.
190              * @param viewName
191              */
192             $scope.setView = function(viewName) {
193                 cancelSearch();
194                 $scope.images = [];
195                 $scope.hasMore = false;
196                 page = 0;
197                 $scope.view = viewName;
198                 baseUrl = window.baseUrl('/images/' + $scope.imageType  + '/' + viewName + '/');
199                 fetchData();
200             };
201
202             /**
203              * Save the details of an image.
204              * @param event
205              */
206             $scope.saveImageDetails = function (event) {
207                 event.preventDefault();
208                 var url = window.baseUrl('/images/update/' + $scope.selectedImage.id);
209                 $http.put(url, this.selectedImage).then(response => {
210                     events.emit('success', 'Image details updated');
211                 }, (response) => {
212                     if (response.status === 422) {
213                         var errors = response.data;
214                         var message = '';
215                         Object.keys(errors).forEach((key) => {
216                             message += errors[key].join('\n');
217                         });
218                         events.emit('error', message);
219                     } else if (response.status === 403) {
220                         events.emit('error', response.data.error);
221                     }
222                 });
223             };
224
225             /**
226              * Delete an image from system and notify of success.
227              * Checks if it should force delete when an image
228              * has dependant pages.
229              * @param event
230              */
231             $scope.deleteImage = function (event) {
232                 event.preventDefault();
233                 var force = $scope.dependantPages !== false;
234                 var url = window.baseUrl('/images/' + $scope.selectedImage.id);
235                 if (force) url += '?force=true';
236                 $http.delete(url).then((response) => {
237                     $scope.images.splice($scope.images.indexOf($scope.selectedImage), 1);
238                     $scope.selectedImage = false;
239                     events.emit('success', 'Image successfully deleted');
240                 }, (response) => {
241                     // Pages failure
242                     if (response.status === 400) {
243                         $scope.dependantPages = response.data;
244                     } else if (response.status === 403) {
245                         events.emit('error', response.data.error);
246                     }
247                 });
248             };
249
250             /**
251              * Simple date creator used to properly format dates.
252              * @param stringDate
253              * @returns {Date}
254              */
255             $scope.getDate = function (stringDate) {
256                 return new Date(stringDate);
257             };
258
259         }]);
260
261
262     ngApp.controller('BookShowController', ['$scope', '$http', '$attrs', '$sce', function ($scope, $http, $attrs, $sce) {
263         $scope.searching = false;
264         $scope.searchTerm = '';
265         $scope.searchResults = '';
266
267         $scope.searchBook = function (e) {
268             e.preventDefault();
269             var term = $scope.searchTerm;
270             if (term.length == 0) return;
271             $scope.searching = true;
272             $scope.searchResults = '';
273             var searchUrl = window.baseUrl('/search/book/' + $attrs.bookId);
274             searchUrl += '?term=' + encodeURIComponent(term);
275             $http.get(searchUrl).then((response) => {
276                 $scope.searchResults = $sce.trustAsHtml(response.data);
277             });
278         };
279
280         $scope.checkSearchForm = function () {
281             if ($scope.searchTerm.length < 1) {
282                 $scope.searching = false;
283             }
284         };
285
286         $scope.clearSearch = function () {
287             $scope.searching = false;
288             $scope.searchTerm = '';
289         };
290
291     }]);
292
293
294     ngApp.controller('PageEditController', ['$scope', '$http', '$attrs', '$interval', '$timeout', '$sce',
295         function ($scope, $http, $attrs, $interval, $timeout, $sce) {
296
297         $scope.editorOptions = require('./pages/page-form');
298         $scope.editContent = '';
299         $scope.draftText = '';
300         var pageId = Number($attrs.pageId);
301         var isEdit = pageId !== 0;
302         var autosaveFrequency = 30; // AutoSave interval in seconds.
303         var isMarkdown = $attrs.editorType === 'markdown';
304         $scope.draftsEnabled = $attrs.draftsEnabled === 'true';
305         $scope.isUpdateDraft = Number($attrs.pageUpdateDraft) === 1;
306         $scope.isNewPageDraft = Number($attrs.pageNewDraft) === 1;
307
308         // Set initial header draft text
309         if ($scope.isUpdateDraft || $scope.isNewPageDraft) {
310             $scope.draftText = 'Editing Draft'
311         } else {
312             $scope.draftText = 'Editing Page'
313         }
314
315         var autoSave = false;
316
317         var currentContent = {
318             title: false,
319             html: false
320         };
321
322         if (isEdit && $scope.draftsEnabled) {
323             setTimeout(() => {
324                 startAutoSave();
325             }, 1000);
326         }
327
328         // Actions specifically for the markdown editor
329         if (isMarkdown) {
330             $scope.displayContent = '';
331             // Editor change event
332             $scope.editorChange = function (content) {
333                 $scope.displayContent = $sce.trustAsHtml(content);
334             }
335         }
336
337         if (!isMarkdown) {
338             $scope.editorChange = function() {};
339         }
340
341         let lastSave = 0;
342
343         /**
344          * Start the AutoSave loop, Checks for content change
345          * before performing the costly AJAX request.
346          */
347         function startAutoSave() {
348             currentContent.title = $('#name').val();
349             currentContent.html = $scope.editContent;
350
351             autoSave = $interval(() => {
352                 // Return if manually saved recently to prevent bombarding the server
353                 if (Date.now() - lastSave < (1000*autosaveFrequency)/2) return;
354                 var newTitle = $('#name').val();
355                 var newHtml = $scope.editContent;
356
357                 if (newTitle !== currentContent.title || newHtml !== currentContent.html) {
358                     currentContent.html = newHtml;
359                     currentContent.title = newTitle;
360                     saveDraft();
361                 }
362
363             }, 1000 * autosaveFrequency);
364         }
365
366         let draftErroring = false;
367         /**
368          * Save a draft update into the system via an AJAX request.
369          */
370         function saveDraft() {
371             if (!$scope.draftsEnabled) return;
372             var data = {
373                 name: $('#name').val(),
374                 html: isMarkdown ? $sce.getTrustedHtml($scope.displayContent) : $scope.editContent
375             };
376
377             if (isMarkdown) data.markdown = $scope.editContent;
378
379             let url = window.baseUrl('/ajax/page/' + pageId + '/save-draft');
380             $http.put(url, data).then(responseData => {
381                 draftErroring = false;
382                 var updateTime = moment.utc(moment.unix(responseData.data.timestamp)).toDate();
383                 $scope.draftText = responseData.data.message + moment(updateTime).format('HH:mm');
384                 if (!$scope.isNewPageDraft) $scope.isUpdateDraft = true;
385                 showDraftSaveNotification();
386                 lastSave = Date.now();
387             }, errorRes => {
388                 if (draftErroring) return;
389                 events.emit('error', 'Failed to save draft. Ensure you have internet connection before saving this page.')
390                 draftErroring = true;
391             });
392         }
393
394         function showDraftSaveNotification() {
395             $scope.draftUpdated = true;
396             $timeout(() => {
397                 $scope.draftUpdated = false;
398             }, 2000)
399         }
400
401         $scope.forceDraftSave = function() {
402             saveDraft();
403         };
404
405         // Listen to shortcuts coming via events
406         $scope.$on('editor-keydown', (event, data) => {
407             // Save shortcut (ctrl+s)
408             if (data.keyCode == 83 && (navigator.platform.match("Mac") ? data.metaKey : data.ctrlKey)) {
409                 data.preventDefault();
410                 saveDraft();
411             }
412         });
413
414         /**
415          * Discard the current draft and grab the current page
416          * content from the system via an AJAX request.
417          */
418         $scope.discardDraft = function () {
419             let url = window.baseUrl('/ajax/page/' + pageId);
420             $http.get(url).then((responseData) => {
421                 if (autoSave) $interval.cancel(autoSave);
422                 $scope.draftText = 'Editing Page';
423                 $scope.isUpdateDraft = false;
424                 $scope.$broadcast('html-update', responseData.data.html);
425                 $scope.$broadcast('markdown-update', responseData.data.markdown || responseData.data.html);
426                 $('#name').val(responseData.data.name);
427                 $timeout(() => {
428                     startAutoSave();
429                 }, 1000);
430                 events.emit('success', 'Draft discarded, The editor has been updated with the current page content');
431             });
432         };
433
434     }]);
435
436     ngApp.controller('PageTagController', ['$scope', '$http', '$attrs',
437         function ($scope, $http, $attrs) {
438
439             const pageId = Number($attrs.pageId);
440             $scope.tags = [];
441
442             $scope.sortOptions = {
443                 handle: '.handle',
444                 items: '> tr',
445                 containment: "parent",
446                 axis: "y"
447             };
448
449             /**
450              * Push an empty tag to the end of the scope tags.
451              */
452             function addEmptyTag() {
453                 $scope.tags.push({
454                     name: '',
455                     value: ''
456                 });
457             }
458             $scope.addEmptyTag = addEmptyTag;
459
460             /**
461              * Get all tags for the current book and add into scope.
462              */
463             function getTags() {
464                 let url = window.baseUrl(`/ajax/tags/get/page/${pageId}`);
465                 $http.get(url).then((responseData) => {
466                     $scope.tags = responseData.data;
467                     addEmptyTag();
468                 });
469             }
470             getTags();
471
472             /**
473              * Set the order property on all tags.
474              */
475             function setTagOrder() {
476                 for (let i = 0; i < $scope.tags.length; i++) {
477                     $scope.tags[i].order = i;
478                 }
479             }
480
481             /**
482              * When an tag changes check if another empty editable
483              * field needs to be added onto the end.
484              * @param tag
485              */
486             $scope.tagChange = function(tag) {
487                 let cPos = $scope.tags.indexOf(tag);
488                 if (cPos !== $scope.tags.length-1) return;
489
490                 if (tag.name !== '' || tag.value !== '') {
491                     addEmptyTag();
492                 }
493             };
494
495             /**
496              * When an tag field loses focus check the tag to see if its
497              * empty and therefore could be removed from the list.
498              * @param tag
499              */
500             $scope.tagBlur = function(tag) {
501                 let isLast = $scope.tags.length - 1 === $scope.tags.indexOf(tag);
502                 if (tag.name === '' && tag.value === '' && !isLast) {
503                     let cPos = $scope.tags.indexOf(tag);
504                     $scope.tags.splice(cPos, 1);
505                 }
506             };
507
508             /**
509              * Save the tags to the current page.
510              */
511             $scope.saveTags = function() {
512                 setTagOrder();
513                 let postData = {tags: $scope.tags};
514                 let url = window.baseUrl('/ajax/tags/update/page/' + pageId);
515                 $http.post(url, postData).then((responseData) => {
516                     $scope.tags = responseData.data.tags;
517                     addEmptyTag();
518                     events.emit('success', responseData.data.message);
519                 })
520             };
521
522             /**
523              * Remove a tag from the current list.
524              * @param tag
525              */
526             $scope.removeTag = function(tag) {
527                 let cIndex = $scope.tags.indexOf(tag);
528                 $scope.tags.splice(cIndex, 1);
529             };
530
531         }]);
532
533
534     ngApp.controller('PageAttachmentController', ['$scope', '$http', '$attrs',
535         function ($scope, $http, $attrs) {
536
537             const pageId = $scope.uploadedTo = $attrs.pageId;
538             let currentOrder = '';
539             $scope.files = [];
540             $scope.editFile = false;
541             $scope.file = getCleanFile();
542             $scope.errors = {
543                 link: {},
544                 edit: {}
545             };
546
547             function getCleanFile() {
548                 return {
549                     page_id: pageId
550                 };
551             }
552
553             // Angular-UI-Sort options
554             $scope.sortOptions = {
555                 handle: '.handle',
556                 items: '> tr',
557                 containment: "parent",
558                 axis: "y",
559                 stop: sortUpdate,
560             };
561
562             /**
563              * Event listener for sort changes.
564              * Updates the file ordering on the server.
565              * @param event
566              * @param ui
567              */
568             function sortUpdate(event, ui) {
569                 let newOrder = $scope.files.map(file => {return file.id}).join(':');
570                 if (newOrder === currentOrder) return;
571
572                 currentOrder = newOrder;
573                 $http.put(window.baseUrl(`/files/sort/page/${pageId}`), {files: $scope.files}).then(resp => {
574                     events.emit('success', resp.data.message);
575                 }, checkError('sort'));
576             }
577
578             /**
579              * Used by dropzone to get the endpoint to upload to.
580              * @returns {string}
581              */
582             $scope.getUploadUrl = function (file) {
583                 let suffix = (typeof file !== 'undefined') ? `/${file.id}` : '';
584                 return window.baseUrl(`/files/upload${suffix}`);
585             };
586
587             /**
588              * Get files for the current page from the server.
589              */
590             function getFiles() {
591                 let url = window.baseUrl(`/files/get/page/${pageId}`)
592                 $http.get(url).then(resp => {
593                     $scope.files = resp.data;
594                     currentOrder = resp.data.map(file => {return file.id}).join(':');
595                 }, checkError('get'));
596             }
597             getFiles();
598
599             /**
600              * Runs on file upload, Adds an file to local file list
601              * and shows a success message to the user.
602              * @param file
603              * @param data
604              */
605             $scope.uploadSuccess = function (file, data) {
606                 $scope.$apply(() => {
607                     $scope.files.push(data);
608                 });
609                 events.emit('success', 'File uploaded');
610             };
611
612             /**
613              * Upload and overwrite an existing file.
614              * @param file
615              * @param data
616              */
617             $scope.uploadSuccessUpdate = function (file, data) {
618                 $scope.$apply(() => {
619                     let search = filesIndexOf(data);
620                     if (search !== -1) $scope.files[search] = data;
621
622                     if ($scope.editFile) {
623                         $scope.editFile = angular.copy(data);
624                         data.link = '';
625                     }
626                 });
627                 events.emit('success', 'File updated');
628             };
629
630             /**
631              * Delete a file from the server and, on success, the local listing.
632              * @param file
633              */
634             $scope.deleteFile = function(file) {
635                 if (!file.deleting) {
636                     file.deleting = true;
637                     return;
638                 }
639                   $http.delete(window.baseUrl(`/files/${file.id}`)).then(resp => {
640                       events.emit('success', resp.data.message);
641                       $scope.files.splice($scope.files.indexOf(file), 1);
642                   }, checkError('delete'));
643             };
644
645             /**
646              * Attach a link to a page.
647              * @param file
648              */
649             $scope.attachLinkSubmit = function(file) {
650                 file.uploaded_to = pageId;
651                 $http.post(window.baseUrl('/files/link'), file).then(resp => {
652                     $scope.files.push(resp.data);
653                     events.emit('success', 'Link attached');
654                     $scope.file = getCleanFile();
655                 }, checkError('link'));
656             };
657
658             /**
659              * Start the edit mode for a file.
660              * @param file
661              */
662             $scope.startEdit = function(file) {
663                 $scope.editFile = angular.copy(file);
664                 $scope.editFile.link = (file.external) ? file.path : '';
665             };
666
667             /**
668              * Cancel edit mode
669              */
670             $scope.cancelEdit = function() {
671                 $scope.editFile = false;
672             };
673
674             /**
675              * Update the name and link of a file.
676              * @param file
677              */
678             $scope.updateFile = function(file) {
679                 $http.put(window.baseUrl(`/files/${file.id}`), file).then(resp => {
680                     let search = filesIndexOf(resp.data);
681                     if (search !== -1) $scope.files[search] = resp.data;
682
683                     if ($scope.editFile && !file.external) {
684                         $scope.editFile.link = '';
685                     }
686                     $scope.editFile = false;
687                     events.emit('success', 'Attachment details updated');
688                 }, checkError('edit'));
689             };
690
691             /**
692              * Get the url of a file.
693              */
694             $scope.getFileUrl = function(file) {
695                 return window.baseUrl('/files/' + file.id);
696             };
697
698             /**
699              * Search the local files via another file object.
700              * Used to search via object copies.
701              * @param file
702              * @returns int
703              */
704             function filesIndexOf(file) {
705                 for (let i = 0; i < $scope.files.length; i++) {
706                     if ($scope.files[i].id == file.id) return i;
707                 }
708                 return -1;
709             }
710
711             /**
712              * Check for an error response in a ajax request.
713              * @param errorGroupName
714              */
715             function checkError(errorGroupName) {
716                 $scope.errors[errorGroupName] = {};
717                 return function(response) {
718                     if (typeof response.data !== 'undefined' && typeof response.data.error !== 'undefined') {
719                         events.emit('error', response.data.error);
720                     }
721                     if (typeof response.data !== 'undefined' && typeof response.data.validation !== 'undefined') {
722                         $scope.errors[errorGroupName] = response.data.validation;
723                         console.log($scope.errors[errorGroupName])
724                     }
725                 }
726             }
727
728         }]);
729
730 };