d8ade93f8c8d1f8bbf75294a795693ba6f81d979
[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 + "/tags/" + arguments[1];
52
53                 if (vname == "ajax_publish")
54                         return base_path + "/publish/" + arguments[1];
55
56                 console.log("Couldn't reverse match:", vname);
57                 return "/404.html";
58         };
59
60         /*
61          * Document Abstraction
62          */
63         function WikiDocument(element_id) {
64                 var meta = $('#' + element_id);
65                 this.id = meta.attr('data-book') + '/' + meta.attr('data-chunk');
66
67                 this.revision = $("*[data-key='revision']", meta).text();
68                 this.readonly = !!$("*[data-key='readonly']", meta).text();
69
70                 this.galleryLink = $("*[data-key='gallery']", meta).text();
71                 this.galleryImages = [];
72                 this.text = null;
73                 this.has_local_changes = false;
74                 this._lock = -1;
75                 this._context_lock = -1;
76                 this._lock_count = 0;
77         };
78
79         WikiDocument.prototype.triggerDocumentChanged = function() {
80                 $(document).trigger('wlapi_document_changed', this);
81         };
82         /*
83          * Fetch text of this document.
84          */
85         WikiDocument.prototype.fetch = function(params) {
86                 params = $.extend({}, noops, params);
87                 var self = this;
88                 $.ajax({
89                         method: "GET",
90                         url: reverse("ajax_document_text", self.id),
91                         data: {"revision": self.revision},
92                         dataType: 'json',
93                         success: function(data) {
94                                 var changed = false;
95
96                                 if (self.text === null || self.revision !== data.revision) {
97                                         self.text = data.text;
98                                         self.revision = data.revision;
99                                         self.gallery = data.gallery;
100                                         changed = true;
101                                         self.triggerDocumentChanged();
102                                 };
103
104                                 self.has_local_changes = false;
105                                 params['success'](self, changed);
106                         },
107                         error: function() {
108                                 params['failure'](self, "Nie udało się wczytać treści dokumentu.");
109                         }
110                 });
111         };
112         /*
113          * Fetch history of this document.
114          *
115          * from - First revision to fetch (default = 0) upto - Last revision to
116          * fetch (default = tip)
117          *
118          */
119         WikiDocument.prototype.fetchHistory = function(params) {
120                 /* this doesn't modify anything, so no locks */
121                 params = $.extend({}, noops, params);
122                 var self = this;
123                 $.ajax({
124                         method: "GET",
125                         url: reverse("ajax_document_history", self.id),
126                         dataType: 'json',
127                         data: {
128                                 "from": params['from'],
129                                 "upto": params['upto']
130                         },
131                         success: function(data) {
132                                 params['success'](self, data);
133                         },
134                         error: function() {
135                                 params['failure'](self, "Nie udało się wczytać historii dokumentu.");
136                         }
137                 });
138         };
139         WikiDocument.prototype.fetchDiff = function(params) {
140                 /* this doesn't modify anything, so no locks */
141                 var self = this;
142                 params = $.extend({
143                         'from': self.revision,
144                         'to': self.revision
145                 }, noops, params);
146                 $.ajax({
147                         method: "GET",
148                         url: reverse("ajax_document_diff", self.id),
149                         dataType: 'html',
150                         data: {
151                                 "from": params['from'],
152                                 "to": params['to']
153                         },
154                         success: function(data) {
155                                 params['success'](self, data);
156                         },
157                         error: function() {
158                                 params['failure'](self, "Nie udało się wczytać porównania wersji.");
159                         }
160                 });
161         };
162
163     WikiDocument.prototype.checkRevision = function(params) {
164         /* this doesn't modify anything, so no locks */
165         var self = this;
166         $.ajax({
167             method: "GET",
168             url: reverse("ajax_document_rev", self.id),
169             dataType: 'text',
170             success: function(data) {
171                 if (data == '') {
172                     if (params.error)
173                         params.error();
174                 }
175                 else if (data != self.revision)
176                     params.outdated();
177             }
178         });
179     };
180
181         /*
182          * Fetch gallery
183          */
184         WikiDocument.prototype.refreshGallery = function(params) {
185                 params = $.extend({}, noops, params);
186                 var self = this;
187                 $.ajax({
188                         method: "GET",
189                         url: reverse("ajax_document_gallery", self.galleryLink),
190                         dataType: 'json',
191                         // data: {},
192                         success: function(data) {
193                                 self.galleryImages = data;
194                                 params['success'](self, data);
195                         },
196                         error: function() {
197                                 self.galleryImages = [];
198                                 params['failure'](self, "<p>Nie udało się wczytać galerii pod nazwą: '" + self.galleryLink + "'.</p>");
199                         }
200                 });
201         };
202
203         /*
204          * Set document's text
205          */
206         WikiDocument.prototype.setText = function(text) {
207                 this.text = text;
208                 this.has_local_changes = true;
209         };
210
211         /*
212          * Set document's gallery link
213          */
214         WikiDocument.prototype.setGalleryLink = function(gallery) {
215                 this.galleryLink = gallery;
216                 this.has_local_changes = true;
217         };
218
219         /*
220          * Save text back to the server
221          */
222         WikiDocument.prototype.save = function(params) {
223                 params = $.extend({}, noops, params);
224                 var self = this;
225
226                 if (!self.has_local_changes) {
227                         console.log("Abort: no changes.");
228                         return params['success'](self, false, "Nie ma zmian do zapisania.");
229                 };
230
231                 // Serialize form to dictionary
232                 var data = {};
233                 $.each(params['form'].serializeArray(), function() {
234                         data[this.name] = this.value;
235                 });
236
237                 data['textsave-text'] = self.text;
238
239                 $.ajax({
240                         url: reverse("ajax_document_text", self.id),
241                         type: "POST",
242                         dataType: "json",
243                         data: data,
244                         success: function(data) {
245                                 var changed = false;
246
247                 $('#header').removeClass('saving');
248
249                                 if (data.text) {
250                                         self.text = data.text;
251                                         self.revision = data.revision;
252                                         self.gallery = data.gallery;
253                                         changed = true;
254                                         self.triggerDocumentChanged();
255                                 };
256
257                                 params['success'](self, changed, ((changed && "Udało się zapisać :)") || "Twoja wersja i serwera jest identyczna"));
258                         },
259                         error: function(xhr) {
260                 if ($('#header').hasClass('saving')) {
261                     $('#header').removeClass('saving');
262                     $.blockUI({
263                         message: "<p>Nie udało się zapisać zmian. <br/><button onclick='$.unblockUI()'>OK</button></p>"
264                     })
265                 }
266                 else {
267                     try {
268                         params['failure'](self, $.parseJSON(xhr.responseText));
269                     }
270                     catch (e) {
271                         params['failure'](self, {
272                             "__message": "<p>Nie udało się zapisać - błąd serwera.</p>"
273                         });
274                     };
275                 }
276
277                         }
278                 });
279
280         $('#save-hide').click(function(){
281             $('#header').addClass('saving');
282             $.unblockUI();
283             $.wiki.blocking.unblock();
284         });
285         }; /* end of save() */
286
287     WikiDocument.prototype.revertToVersion = function(params) {
288         var self = this;
289         params = $.extend({}, noops, params);
290
291         if (params.revision >= this.revision) {
292             params.failure(self, 'Proszę wybrać rewizję starszą niż aktualna.');
293             return;
294         }
295
296         // Serialize form to dictionary
297         var data = {};
298         $.each(params['form'].serializeArray(), function() {
299             data[this.name] = this.value;
300         });
301
302         $.ajax({
303             url: reverse("ajax_document_revert", self.id),
304             type: "POST",
305             dataType: "json",
306             data: data,
307             success: function(data) {
308                 if (data.text) {
309                     self.text = data.text;
310                     self.revision = data.revision;
311                     self.gallery = data.gallery;
312                     self.triggerDocumentChanged();
313
314                     params.success(self, "Udało się przywrócić wersję :)");
315                 }
316                 else {
317                     params.failure(self, "Przywracana wersja identyczna z aktualną. Anulowano przywracanie.");
318                 }
319             },
320             error: function(xhr) {
321                 params.failure(self, "Nie udało się przywrócić wersji - błąd serwera.");
322             }
323         });
324     };
325
326         WikiDocument.prototype.publish = function(params) {
327                 params = $.extend({}, noops, params);
328                 var self = this;
329                 $.ajax({
330                         url: reverse("ajax_publish", self.id),
331                         type: "POST",
332                         dataType: "json",
333                         success: function(data) {
334                                 params.success(self, data);
335                         },
336                         error: function(xhr) {
337                                 if (xhr.status == 403 || xhr.status == 401) {
338                                         params.failure(self, "Nie masz uprawnień lub nie jesteś zalogowany.");
339                                 }
340                                 else {
341                                         try {
342                                                 params.failure(self, xhr.responseText);
343                                         }
344                                         catch (e) {
345                                                 params.failure(self, "Nie udało się - błąd serwera.");
346                                         };
347                                 };
348
349                         }
350                 });
351         };
352         WikiDocument.prototype.setTag = function(params) {
353                 params = $.extend({}, noops, params);
354                 var self = this;
355                 var data = {
356                         "addtag-id": self.id,
357                 };
358
359                 /* unpack form */
360                 $.each(params.form.serializeArray(), function() {
361                         data[this.name] = this.value;
362                 });
363
364                 $.ajax({
365                         url: reverse("ajax_document_addtag", self.id),
366                         type: "POST",
367                         dataType: "json",
368                         data: data,
369                         success: function(data) {
370                                 params.success(self, data.message);
371                         },
372                         error: function(xhr) {
373                                 if (xhr.status == 403 || xhr.status == 401) {
374                                         params.failure(self, {
375                                                 "__all__": ["Nie masz uprawnień lub nie jesteś zalogowany."]
376                                         });
377                                 }
378                                 else {
379                                         try {
380                                                 params.failure(self, $.parseJSON(xhr.responseText));
381                                         }
382                                         catch (e) {
383                                                 params.failure(self, {
384                                                         "__all__": ["Nie udało się - błąd serwera."]
385                                                 });
386                                         };
387                                 };
388                         }
389                 });
390         };
391
392         $.wikiapi.WikiDocument = WikiDocument;
393 })(jQuery);