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