cbed73b8b15cd4f1bf3294a54c470d54674aef67
[redakcja.git] / redakcja / static / js / wiki / wikiapi.js
1 (function($) {
2         $.wikiapi = {};
3         var noop = function() {
4         };
5         var noops = {
6                 success: noop,
7                 failure: noop
8         };
9         /*
10          * Return absolute reverse path of given named view. (at least he have it
11          * hard-coded in one place)
12          *
13          * TODO: think of a way, not to hard-code it here ;)
14          *
15          */
16         function reverse() {
17                 var vname = arguments[0];
18                 var base_path = "/documents";
19
20                 if (vname == "ajax_document_text") {
21                         var path = "/text/" + arguments[1] + '/';
22
23                 if (arguments[2] !== undefined)
24                                 path += arguments[2] + '/';
25
26                         return base_path + path;
27                 }
28
29         if (vname == "ajax_document_revert") {
30             return base_path + "/revert/" + arguments[1] + '/';
31         }
32
33
34                 if (vname == "ajax_document_history") {
35
36                         return base_path + "/history/" + arguments[1] + '/';
37                 }
38
39                 if (vname == "ajax_document_gallery") {
40
41                         return base_path + "/gallery/" + arguments[1] + '/';
42                 }
43
44                 if (vname == "ajax_document_diff")
45                         return base_path + "/diff/" + arguments[1] + '/';
46
47         if (vname == "ajax_document_rev")
48             return base_path + "/rev/" + arguments[1] + '/';
49
50                 if (vname == "ajax_document_addtag")
51                         return base_path + "/tag/" + arguments[1] + '/';
52
53                 if (vname == "ajax_document_pubmark")
54                         return base_path + "/pubmark/" + arguments[1] + '/';
55
56                 if (vname == "ajax_publish")
57                         return base_path + "/publish/" + arguments[1] + '/';
58
59                 console.log("Couldn't reverse match:", vname);
60                 return "/404.html";
61         };
62
63         /*
64          * Document Abstraction
65          */
66         function WikiDocument(element_id) {
67                 var meta = $('#' + element_id);
68                 this.id = meta.attr('data-book') + '/' + meta.attr('data-chunk');
69
70                 this.revision = $("*[data-key='revision']", meta).text();
71                 this.readonly = !!$("*[data-key='readonly']", meta).text();
72
73                 this.galleryLink = $("*[data-key='gallery']", meta).text();
74
75         var diff = $("*[data-key='diff']", meta).text();
76         diff = diff.split(',');
77         if (diff.length == 2 && diff[0] < diff[1])
78             this.diff = diff;
79         else if (diff.length == 1) {
80             diff = parseInt(diff);
81             if (diff != NaN)
82                 this.diff = [diff - 1, diff];
83         }
84
85                 this.galleryImages = [];
86                 this.text = null;
87                 this.has_local_changes = false;
88                 this._lock = -1;
89                 this._context_lock = -1;
90                 this._lock_count = 0;
91         };
92
93         WikiDocument.prototype.triggerDocumentChanged = function() {
94                 $(document).trigger('wlapi_document_changed', this);
95         };
96         /*
97          * Fetch text of this document.
98          */
99         WikiDocument.prototype.fetch = function(params) {
100                 params = $.extend({}, noops, params);
101                 var self = this;
102                 $.ajax({
103                         method: "GET",
104                         url: reverse("ajax_document_text", self.id),
105                         data: {"revision": self.revision},
106                         dataType: 'json',
107                         success: function(data) {
108                                 var changed = false;
109
110                                 if (self.text === null || self.revision !== data.revision) {
111                                         self.text = data.text;
112                                         self.revision = data.revision;
113                                         self.gallery = data.gallery;
114                                         changed = true;
115                                         self.triggerDocumentChanged();
116                                 };
117
118                                 self.has_local_changes = false;
119                                 params['success'](self, changed);
120                         },
121                         error: function() {
122                                 params['failure'](self, "Nie udało się wczytać treści dokumentu.");
123                         }
124                 });
125         };
126         /*
127          * Fetch history of this document.
128          *
129          * from - First revision to fetch (default = 0) upto - Last revision to
130          * fetch (default = tip)
131          *
132          */
133         WikiDocument.prototype.fetchHistory = function(params) {
134                 /* this doesn't modify anything, so no locks */
135                 params = $.extend({}, noops, params);
136                 var self = this;
137                 $.ajax({
138                         method: "GET",
139                         url: reverse("ajax_document_history", self.id),
140                         dataType: 'json',
141                         data: {
142                                 "from": params['from'],
143                                 "upto": params['upto']
144                         },
145                         success: function(data) {
146                                 params['success'](self, data);
147                         },
148                         error: function() {
149                                 params['failure'](self, "Nie udało się wczytać historii dokumentu.");
150                         }
151                 });
152         };
153         WikiDocument.prototype.fetchDiff = function(params) {
154                 /* this doesn't modify anything, so no locks */
155                 var self = this;
156                 params = $.extend({
157                         'from': self.revision,
158                         'to': self.revision
159                 }, noops, params);
160                 $.ajax({
161                         method: "GET",
162                         url: reverse("ajax_document_diff", self.id),
163                         dataType: 'html',
164                         data: {
165                                 "from": params['from'],
166                                 "to": params['to']
167                         },
168                         success: function(data) {
169                                 params['success'](self, data);
170                         },
171                         error: function() {
172                                 params['failure'](self, "Nie udało się wczytać porównania wersji.");
173                         }
174                 });
175         };
176
177     WikiDocument.prototype.checkRevision = function(params) {
178         /* this doesn't modify anything, so no locks */
179         var self = this;
180         $.ajax({
181             method: "GET",
182             url: reverse("ajax_document_rev", self.id),
183             dataType: 'text',
184             success: function(data) {
185                 if (data == '') {
186                     if (params.error)
187                         params.error();
188                 }
189                 else if (data != self.revision)
190                     params.outdated();
191             }
192         });
193     };
194
195         /*
196          * Fetch gallery
197          */
198         WikiDocument.prototype.refreshGallery = function(params) {
199                 params = $.extend({}, noops, params);
200                 var self = this;
201                 $.ajax({
202                         method: "GET",
203                         url: reverse("ajax_document_gallery", self.galleryLink),
204                         dataType: 'json',
205                         // data: {},
206                         success: function(data) {
207                                 self.galleryImages = data;
208                                 params['success'](self, data);
209                         },
210                         error: function() {
211                                 self.galleryImages = [];
212                                 params['failure'](self, "<p>Nie udało się wczytać galerii pod nazwą: '" + self.galleryLink + "'.</p>");
213                         }
214                 });
215         };
216
217         /*
218          * Set document's text
219          */
220         WikiDocument.prototype.setText = function(text) {
221                 this.text = text;
222                 this.has_local_changes = true;
223         };
224
225         /*
226          * Set document's gallery link
227          */
228         WikiDocument.prototype.setGalleryLink = function(gallery) {
229                 this.galleryLink = gallery;
230                 this.has_local_changes = true;
231         };
232
233         /*
234          * Save text back to the server
235          */
236         WikiDocument.prototype.save = function(params) {
237                 params = $.extend({}, noops, params);
238                 var self = this;
239
240                 if (!self.has_local_changes) {
241                         console.log("Abort: no changes.");
242                         return params['success'](self, false, "Nie ma zmian do zapisania.");
243                 };
244
245                 // Serialize form to dictionary
246                 var data = {};
247                 $.each(params['form'].serializeArray(), function() {
248                         data[this.name] = this.value;
249                 });
250
251                 data['textsave-text'] = self.text;
252
253                 $.ajax({
254                         url: reverse("ajax_document_text", self.id),
255                         type: "POST",
256                         dataType: "json",
257                         data: data,
258                         success: function(data) {
259                                 var changed = false;
260
261                 $('#header').removeClass('saving');
262
263                                 if (data.text) {
264                                         self.text = data.text;
265                                         self.revision = data.revision;
266                                         self.gallery = data.gallery;
267                                         changed = true;
268                                         self.triggerDocumentChanged();
269                                 };
270
271                                 params['success'](self, changed, ((changed && "Udało się zapisać :)") || "Twoja wersja i serwera jest identyczna"));
272                         },
273                         error: function(xhr) {
274                 if ($('#header').hasClass('saving')) {
275                     $('#header').removeClass('saving');
276                     $.blockUI({
277                         message: "<p>Nie udało się zapisać zmian. <br/><button onclick='$.unblockUI()'>OK</button></p>"
278                     })
279                 }
280                 else {
281                     try {
282                         params['failure'](self, $.parseJSON(xhr.responseText));
283                     }
284                     catch (e) {
285                         params['failure'](self, {
286                             "__message": "<p>Nie udało się zapisać - błąd serwera.</p>"
287                         });
288                     };
289                 }
290
291                         }
292                 });
293
294         $('#save-hide').click(function(){
295             $('#header').addClass('saving');
296             $.unblockUI();
297             $.wiki.blocking.unblock();
298         });
299         }; /* end of save() */
300
301     WikiDocument.prototype.revertToVersion = function(params) {
302         var self = this;
303         params = $.extend({}, noops, params);
304
305         if (params.revision >= this.revision) {
306             params.failure(self, 'Proszę wybrać rewizję starszą niż aktualna.');
307             return;
308         }
309
310         // Serialize form to dictionary
311         var data = {};
312         $.each(params['form'].serializeArray(), function() {
313             data[this.name] = this.value;
314         });
315
316         $.ajax({
317             url: reverse("ajax_document_revert", self.id),
318             type: "POST",
319             dataType: "json",
320             data: data,
321             success: function(data) {
322                 if (data.text) {
323                     self.text = data.text;
324                     self.revision = data.revision;
325                     self.gallery = data.gallery;
326                     self.triggerDocumentChanged();
327
328                     params.success(self, "Udało się przywrócić wersję :)");
329                 }
330                 else {
331                     params.failure(self, "Przywracana wersja identyczna z aktualną. Anulowano przywracanie.");
332                 }
333             },
334             error: function(xhr) {
335                 params.failure(self, "Nie udało się przywrócić wersji - błąd serwera.");
336             }
337         });
338     };
339
340         WikiDocument.prototype.publish = function(params) {
341                 params = $.extend({}, noops, params);
342                 var self = this;
343                 $.ajax({
344                         url: reverse("ajax_publish", self.id),
345                         type: "POST",
346                         dataType: "json",
347                         success: function(data) {
348                                 params.success(self, data);
349                         },
350                         error: function(xhr) {
351                                 if (xhr.status == 403 || xhr.status == 401) {
352                                         params.failure(self, "Nie masz uprawnień lub nie jesteś zalogowany.");
353                                 }
354                                 else {
355                                         try {
356                                                 params.failure(self, xhr.responseText);
357                                         }
358                                         catch (e) {
359                                                 params.failure(self, "Nie udało się - błąd serwera.");
360                                         };
361                                 };
362
363                         }
364                 });
365         };
366         WikiDocument.prototype.setTag = function(params) {
367                 params = $.extend({}, noops, params);
368                 var self = this;
369                 var data = {
370                         "addtag-id": self.id,
371                 };
372
373                 /* unpack form */
374                 $.each(params.form.serializeArray(), function() {
375                         data[this.name] = this.value;
376                 });
377
378                 $.ajax({
379                         url: reverse("ajax_document_addtag", self.id),
380                         type: "POST",
381                         dataType: "json",
382                         data: data,
383                         success: function(data) {
384                                 params.success(self, data.message);
385                         },
386                         error: function(xhr) {
387                                 if (xhr.status == 403 || xhr.status == 401) {
388                                         params.failure(self, {
389                                                 "__all__": ["Nie masz uprawnień lub nie jesteś zalogowany."]
390                                         });
391                                 }
392                                 else {
393                                         try {
394                                                 params.failure(self, $.parseJSON(xhr.responseText));
395                                         }
396                                         catch (e) {
397                                                 params.failure(self, {
398                                                         "__all__": ["Nie udało się - błąd serwera."]
399                                                 });
400                                         };
401                                 };
402                         }
403                 });
404         };
405
406         WikiDocument.prototype.pubmark = function(params) {
407                 params = $.extend({}, noops, params);
408                 var self = this;
409                 var data = {
410                         "pubmark-id": self.id,
411                 };
412
413                 /* unpack form */
414                 $.each(params.form.serializeArray(), function() {
415                         data[this.name] = this.value;
416                 });
417
418                 $.ajax({
419                         url: reverse("ajax_document_pubmark", self.id),
420                         type: "POST",
421                         dataType: "json",
422                         data: data,
423                         success: function(data) {
424                                 params.success(self, data.message);
425                         },
426                         error: function(xhr) {
427                                 if (xhr.status == 403 || xhr.status == 401) {
428                                         params.failure(self, {
429                                                 "__all__": ["Nie masz uprawnień lub nie jesteś zalogowany."]
430                                         });
431                                 }
432                                 else {
433                                         try {
434                                                 params.failure(self, $.parseJSON(xhr.responseText));
435                                         }
436                                         catch (e) {
437                                                 params.failure(self, {
438                                                         "__all__": ["Nie udało się - błąd serwera."]
439                                                 });
440                                         };
441                                 };
442                         }
443                 });
444         };
445
446         $.wikiapi.WikiDocument = WikiDocument;
447 })(jQuery);