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