13435ea008381e0c33f8e807324bf546803feb09
[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.
11          * (at least he have it 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 = "/" + arguments[1] + "/text";
22
23                 if (arguments[2] !== undefined)
24                                 path += "/" + arguments[2];
25
26                         return base_path + path;
27                 }
28
29                 if (vname == "ajax_document_history") {
30
31                         return base_path + "/" + arguments[1] + "/history";
32                 }
33
34                 if (vname == "ajax_document_gallery") {
35
36                         return base_path + "/gallery/" + arguments[1];
37                 }
38
39                 if (vname == "ajax_document_diff")
40                         return base_path + "/" + arguments[1] + "/diff";
41
42                 if (vname == "ajax_document_addtag")
43                         return base_path + "/" + arguments[1] + "/tags";
44
45                 if (vname == "ajax_publish")
46                         return base_path + "/" + arguments[1] + "/publish";
47                 
48                 if (vname == 'ping')
49                     return base_path + '/ping/'
50
51                 console.log("Couldn't reverse match:", vname);
52                 return "/404.html";
53         };
54
55         /*
56          * Document Abstraction
57          */
58         function WikiDocument(element_id) {
59                 var meta = $('#' + element_id);
60                 this.id = meta.attr('data-document-name');
61
62                 this.revision = $("*[data-key='revision']", meta).text();
63                 this.readonly = !!$("*[data-key='readonly']", meta).text();
64
65                 this.galleryLink = $("*[data-key='gallery']", meta).text();
66                 this.galleryImages = [];
67                 this.text = null;
68                 this.has_local_changes = false;
69                 this._lock = -1;
70                 this._context_lock = -1;
71                 this._lock_count = 0;
72         };
73
74         WikiDocument.prototype.triggerDocumentChanged = function() {
75                 $(document).trigger('wlapi_document_changed', this);
76         };
77         /*
78          * Fetch text of this document.
79          */
80         WikiDocument.prototype.fetch = function(params) {
81                 params = $.extend({}, noops, params);
82                 var self = this;
83                 $.ajax({
84                         method: "GET",
85                         url: reverse("ajax_document_text", self.id),
86                         data: {"revision": self.revision},
87                         dataType: 'json',
88                         success: function(data) {
89                                 var changed = false;
90
91                                 if (self.text === null || self.revision !== data.revision) {
92                                         self.text = data.text;
93                                         self.revision = data.revision;
94                                         self.gallery = data.gallery;
95                                         changed = true;
96                                         self.triggerDocumentChanged();
97                                 };
98
99                                 self.has_local_changes = false;
100                                 params['success'](self, changed);
101                         },
102                         error: function() {
103                                 params['failure'](self, "Nie udało się wczytać treści dokumentu.");
104                         }
105                 });
106         };
107         /*
108          * Fetch history of this document.
109          *
110          * from - First revision to fetch (default = 0)
111          * upto - Last revision to fetch (default = tip)
112          *
113          */
114         WikiDocument.prototype.fetchHistory = function(params) {
115                 /* this doesn't modify anything, so no locks */
116                 params = $.extend({}, noops, params);
117                 var self = this;
118                 $.ajax({
119                         method: "GET",
120                         url: reverse("ajax_document_history", self.id),
121                         dataType: 'json',
122                         data: {
123                                 "from": params['from'],
124                                 "upto": params['upto']
125                         },
126                         success: function(data) {
127                                 params['success'](self, data);
128                         },
129                         error: function() {
130                                 params['failure'](self, "Nie udało się wczytać historii dokumentu.");
131                         }
132                 });
133         };
134         WikiDocument.prototype.fetchDiff = function(params) {
135                 /* this doesn't modify anything, so no locks */
136                 var self = this;
137                 params = $.extend({
138                         'from': self.revision,
139                         'to': self.revision
140                 }, noops, params);
141                 $.ajax({
142                         method: "GET",
143                         url: reverse("ajax_document_diff", self.id),
144                         dataType: 'html',
145                         data: {
146                                 "from": params['from'],
147                                 "to": params['to']
148                         },
149                         success: function(data) {
150                                 params['success'](self, data);
151                         },
152                         error: function() {
153                                 params['failure'](self, "Nie udało się wczytać porównania wersji.");
154                         }
155                 });
156         };
157
158         /*
159          * Fetch gallery
160          */
161         WikiDocument.prototype.refreshGallery = function(params) {
162                 params = $.extend({}, noops, params);
163                 var self = this;
164                 $.ajax({
165                         method: "GET",
166                         url: reverse("ajax_document_gallery", self.galleryLink),
167                         dataType: 'json',
168                         // data: {},
169                         success: function(data) {
170                                 self.galleryImages = data;
171                                 params['success'](self, data);
172                         },
173                         error: function() {
174                                 self.galleryImages = [];
175                                 params['failure'](self, "<p>Nie udało się wczytać gallerii pod nazwą: '" + self.galleryLink + "'.</p>");
176                         }
177                 });
178         };
179
180         /*
181          * Set document's text
182          */
183         WikiDocument.prototype.setText = function(text) {
184                 this.text = text;
185                 this.has_local_changes = true;
186         };
187
188         /*
189          * Set document's gallery link
190          */
191         WikiDocument.prototype.setGalleryLink = function(gallery) {
192                 this.galleryLink = gallery;
193                 this.has_local_changes = true;
194         };
195
196         /*
197          * Save text back to the server
198          */
199         WikiDocument.prototype.save = function(params) {
200                 params = $.extend({}, noops, params);
201                 var self = this;
202
203                 if (!self.has_local_changes) {
204                         console.log("Abort: no changes.");
205                         return params['success'](self, false, "Nie ma zmian do zapisania.");
206                 };
207
208                 // Serialize form to dictionary
209                 var data = {};
210                 $.each(params['form'].serializeArray(), function() {
211                         data[this.name] = this.value;
212                 });
213
214                 var metaComment = '<!--';
215                 metaComment += '\n\tgallery:' + self.galleryLink;
216                 metaComment += '\n-->\n'
217
218                 data['textsave-text'] = metaComment + self.text;
219
220                 $.ajax({
221                         url: reverse("ajax_document_text", self.id),
222                         type: "POST",
223                         dataType: "json",
224                         data: data,
225                         timeout: 5000,
226                         success: function(data) {
227                                 var changed = false;
228
229                                 if (data.text) {
230                                         self.text = data.text;
231                                         self.revision = data.revision;
232                                         self.gallery = data.gallery;
233                                         changed = true;
234                                         self.triggerDocumentChanged();
235                                 };
236
237                                 params['success'](self, changed, ((changed && "Udało się zapisać :)") || "Twoja wersja i serwera jest identyczna"));
238                         },
239                         error: function(xhr, msg) {
240                                 if (msg == 'timeout') {
241                                         params['failure'](self, {
242                         "__message": "Przekroczony czas połączenia. Zmiany nie zostały zapisane."
243                     });
244                                 }
245                                 else {
246                     try {
247                         params['failure'](self, $.parseJSON(xhr.responseText));
248                     }
249                     catch (e) {
250                         params['failure'](self, {
251                             "__message": "Nie udało się zapisać - błąd serwera."
252                         });
253                     };
254                                 }
255                         }
256                 });
257         }; /* end of save() */
258
259         WikiDocument.prototype.publish = function(params) {
260                 params = $.extend({}, noops, params);
261                 var self = this;
262                 $.ajax({
263                         url: reverse("ajax_publish", self.id),
264                         type: "POST",
265                         dataType: "json",
266                         success: function(data) {
267                                 params.success(self, data);
268                         },
269                         error: function(xhr) {
270                                 if (xhr.status == 403 || xhr.status == 401) {
271                                         params.failure(self, "Nie masz uprawnień lub nie jesteś zalogowany.");
272                                 }
273                                 else {
274                                         try {
275                                                 params.failure(self, xhr.responseText);
276                                         }
277                                         catch (e) {
278                                                 params.failure(self, "Nie udało się - błąd serwera.");
279                                         };
280                                 };
281
282                         }
283                 });
284         };
285         WikiDocument.prototype.setTag = function(params) {
286                 params = $.extend({}, noops, params);
287                 var self = this;
288                 var data = {
289                         "addtag-id": self.id,
290                 };
291
292                 /* unpack form */
293                 $.each(params.form.serializeArray(), function() {
294                         data[this.name] = this.value;
295                 });
296
297                 $.ajax({
298                         url: reverse("ajax_document_addtag", self.id),
299                         type: "POST",
300                         dataType: "json",
301                         data: data,
302                         success: function(data) {
303                                 params.success(self, data.message);
304                         },
305                         error: function(xhr) {
306                                 if (xhr.status == 403 || xhr.status == 401) {
307                                         params.failure(self, {
308                                                 "__all__": ["Nie masz uprawnień lub nie jesteś zalogowany."]
309                                         });
310                                 }
311                                 else {
312                                         try {
313                                                 params.failure(self, $.parseJSON(xhr.responseText));
314                                         }
315                                         catch (e) {
316                                                 params.failure(self, {
317                                                         "__all__": ["Nie udało się - błąd serwera."]
318                                                 });
319                                         };
320                                 };
321                         }
322                 });
323         };
324
325         $.wikiapi.WikiDocument = WikiDocument;
326         
327         
328         var ping = function () {
329         $.ajax({
330             url : reverse('ping'),
331                         timeout: 2000,
332             complete : function () {
333                 setTimeout(function () {
334                     ping();
335                 }, 600000);
336             }
337         });
338     };
339         
340     ping();
341
342 })(jQuery);