source: extensions/piwigo_mobile/ios/www/js/app.js @ 12473

Last change on this file since 12473 was 12473, checked in by patdenice, 13 years ago

Update languages

File size: 19.2 KB
Line 
1var pictureSource;
2var destinationType;
3var localization;
4var backPage;
5var conf = new Object;
6var selectedCat = null;
7var lastImageURL;
8var pwg_token;
9var queue = new Array;
10var uploadedPhotos;
11var uploadInProgress = false;
12var cancelRequest = false;
13var OSCode = 'IPH';
14
15$(document).ready( function () {
16
17  $(document).bind("deviceready", function() {
18 
19    pictureSource=navigator.camera.PictureSourceType;
20    destinationType=navigator.camera.DestinationType;
21
22    var reg = /(iphone|ipad|ipod)/i;
23    if (!reg.test(device.platform)) OSCode = 'AND';
24
25    if (!checkDeviceConnection ()) {
26      message("Error", "Please check your internet connection", '#config');
27    }
28
29    $(document).bind("resume", pwgLogin);
30  });
31
32  // Init
33  loadSettings();
34  loadLanguage(navigator.language);
35
36  // Page events
37  $("select#existing_album").change(function () {
38    $("select#parent_album").val($(this).val()).selectmenu('refresh');
39  });
40
41  $("#resize").change( function () {
42      $("#resize_options").toggle();
43  });
44
45  // New user
46  if (window.localStorage.getItem("pwg.imageNumber") == null) {
47    $.mobile.changePage('#config');
48    return;
49  }
50
51  // Update config
52  if (conf.resize == null) {
53    window.localStorage.setItem("pwg.resize", "true");
54    window.localStorage.setItem("pwg.max_width", "800");
55    window.localStorage.setItem("pwg.max_height", "600");
56    loadSettings();
57  }
58
59  // Fill settings page
60  $("#url").val(conf.url);
61  $("#username").val(conf.username);
62  $("#password").val(conf.password);
63
64  $("#advanced_config").page();
65  $("#quality").val(conf.quality).slider('refresh');
66  $("#default_author").val(conf.author);
67
68  if (!conf.resize) {
69    $("#resize").removeAttr('checked').checkboxradio('refresh');
70    $("#resize_options").hide();
71  }
72  $("#max_width").val(conf.max_width).slider('refresh');
73  $("#max_height").val(conf.max_height).slider('refresh');
74
75  // Log user
76  pwgLogin();
77  $("#photos, #config, #album, #advanced_config, #about").page();
78});
79
80
81function checkDeviceConnection () {
82
83  connection = navigator.network.connection.type;
84  if (connection == Connection.NONE || connection == Connection.UNKNOWN) {
85    return false;
86  }
87  return true;
88
89}
90
91function l10n(string) {
92  if (typeof(localization[string])=='undefined') {
93    return string;
94  } else {
95    return localization[string];
96  }
97}
98
99
100function loadLanguage(lang) {
101  $.ajax({
102    url: 'languages/'+lang+'.json',
103    dataType: 'json',
104    async: false,
105    success: function(json) {
106      localization = json;
107      getPrivacyLevels();
108      $('l10n').each(function() {
109        str = $(this).html();
110        if (typeof(localization[str])!='undefined')
111          $(this).html(localization[str]);
112      });
113    },
114    error: function() {
115      loadLanguage('en-us');
116    }
117  });
118}
119
120
121function getPhoto() {
122
123  var params = new Object();
124
125  params.quality = conf.quality;
126  params.destinationType = destinationType.FILE_URI;
127  params.sourceType = pictureSource.PHOTOLIBRARY;
128
129  if (conf.resize) {
130    params.targetWidth = conf.max_width;
131    params.targetHeight = conf.max_height;
132  }
133
134  navigator.camera.getResizedPicture(appendPhoto, null, params);
135}
136
137
138function saveSettings() {
139
140  if (window.localStorage.getItem("pwg.imageNumber") == null) {
141    window.localStorage.setItem("pwg.imageNumber", "1");
142  }
143
144  var old_conf = new Object;
145  for (i in conf) {
146    old_conf[i] = conf[i];
147  }
148
149  window.localStorage.setItem("pwg.url", $("#url").val().replace(/\/+$/g,''));
150  window.localStorage.setItem("pwg.username", $("#username").val());
151  window.localStorage.setItem("pwg.password", $("#password").val());
152  window.localStorage.setItem("pwg.author", $("#default_author").val());
153  window.localStorage.setItem("pwg.quality", $("#quality").val());
154  window.localStorage.setItem("pwg.resize", $("#resize").is(':checked').toString());
155  window.localStorage.setItem("pwg.max_width", $("#max_width").val());
156  window.localStorage.setItem("pwg.max_height", $("#max_height").val());
157
158  loadSettings();
159
160  // Reset photos selection only if photo parameters have changed
161  if (conf.quality != old_conf.quality || conf.resize != old_conf.resize || conf.max_width != old_conf.max_width || conf.max_height != old_conf.max_height) {
162    removeAllPhotos();
163  }
164
165  // Log only if connection parameters have changed
166  if (conf.url != old_conf.url || conf.username != old_conf.username || conf.password != old_conf.password || selectedCat == null) {
167    selectedCat = null;
168    pwgLogin();
169  } else {
170    $.mobile.changePage('#album');
171  }
172}
173
174
175function loadSettings() {
176
177  conf.imageNumber = parseInt(window.localStorage.getItem("pwg.imageNumber"));
178  conf.url = window.localStorage.getItem("pwg.url");
179  conf.username = window.localStorage.getItem("pwg.username");
180  conf.password = window.localStorage.getItem("pwg.password");
181  conf.author = window.localStorage.getItem("pwg.author");
182  conf.quality = parseInt(window.localStorage.getItem("pwg.quality"));
183  conf.resize = (window.localStorage.getItem("pwg.resize") === 'true');
184  conf.max_width = parseInt(window.localStorage.getItem("pwg.max_width"));
185  conf.max_height = parseInt(window.localStorage.getItem("pwg.max_height"));
186
187}
188
189
190function pwgLogin(callback) {
191
192  $.mobile.loadingMessage = l10n("Loging");
193  $.mobile.showPageLoadingMsg();
194
195  $.ajax({
196    type: "POST",
197    url: conf.url + "/ws.php?format=json",
198    data: {
199      method : "pwg.session.login",
200      username : conf.username,
201      password : conf.password
202    },
203    dataType: "json",
204    success: function(data) {
205      $.mobile.hidePageLoadingMsg();
206      if (data.stat == "ok") {
207        getPwgToken();
208        if (selectedCat == null) {
209          selectedCat = '0';
210          getCategories();
211          $.mobile.changePage('#album');
212        }
213      } else {
214        $.mobile.changePage('#config', { transition: "none" });
215        message("Error", data.message, '#config');
216      }
217    },
218    error: function(data) {
219      $.mobile.hidePageLoadingMsg();
220      $.mobile.changePage('#config', { transition: "none" });
221      if (!checkDeviceConnection ()) {
222          message("Error", "Please check your internet connection", '#config');
223      } else {
224          message("Error", "Unable to connect", '#config');
225      }
226    }
227  });
228}
229
230
231// Retrieve pwg_token (in case of cancel upload)
232function getPwgToken() {
233
234  $.ajax({
235    type: "GET",
236    url: conf.url + "/ws.php?format=json&method=pwg.session.getStatus",
237    dataType: "json",
238    success: function(data) {
239      if (data.stat == "ok") {
240        pwg_token = data.result.pwg_token;
241      }
242    }
243  });
244}
245
246
247// Recursive function to get categories list
248function getCategoriesOptions(cats, options, parents) {
249
250  if (options == null) {
251    options = '<option value="0">------</option>';
252    parents = '';
253  }
254  for (var i in cats) {
255    options += '<option value="' + cats[i].id + '"';
256    if (selectedCat == cats[i].id) {
257      options += ' selected="selected"';
258    }
259    options += '>' + parents + cats[i].name + '</option>';
260    if (cats[i].nb_categories > 0) {
261      options = getCategoriesOptions(cats[i].sub_categories, options, parents + cats[i].name + ' / ');
262    }
263  }
264  return options;
265}
266
267
268function getCategories() {
269
270  $.mobile.loadingMessage = l10n("Loading albums");
271  $.mobile.showPageLoadingMsg();
272
273  $.ajax({
274    type: "POST",
275    url: conf.url + "/ws.php?format=json",
276    data: {
277      method : "pwg.categories.getList",
278      recursive: "true",
279      tree_output: "true"
280    },
281    dataType: "json",
282    success: function(data) {
283      $.mobile.hidePageLoadingMsg();
284      if (data['stat'] == "ok") {
285        options = getCategoriesOptions(data['result']);
286        $("select#parent_album, select#existing_album").html(options).selectmenu('refresh');
287      }
288    },
289    error: function() {
290      $.mobile.hidePageLoadingMsg();
291    }
292  });
293}
294
295
296function getPrivacyLevels() {
297
298  var admins = l10n("Admins");
299  var family = admins + ', ' + l10n("Family");
300  var friends = family + ', ' + l10n("Friends");
301  var contacts = friends + ', ' + l10n("Contacts");
302  var everybody = l10n("Everybody");
303
304  var options = '<option label="'+admins+'" value="8">'+admins+'</option>';
305  options += '<option label="'+family+'" value="4">'+family+'</option>';
306  options += '<option label="'+friends+'" value="2">'+friends+'</option>';
307  options += '<option label="'+contacts+'" value="1">'+contacts+'</option>';
308  options += '<option label="'+everybody+'" value="0" selected="selected">'+everybody+'</option>';
309
310  $("select#privacy_level").html(options).selectmenu('refresh');
311}
312
313
314function createNewAlbum() {
315
316  var parent = $("#parent_album").val();
317  var name = $("#album_name").val();
318
319  if (name == "") {
320    message("Error", "Album name can not be empty", '#album');
321    return false;
322  }
323
324  $.mobile.loadingMessage = l10n("Album creation");
325  $.mobile.showPageLoadingMsg();
326
327  $.ajax({
328    type: "POST",
329    url: conf.url + "/ws.php?format=json",
330    data: {
331      method : "pwg.categories.add",
332      name: name,
333      parent: parent
334    },
335    dataType: "json",
336    async: false,
337    success: function(data) {
338      $.mobile.hidePageLoadingMsg();
339      if (data.stat == "ok") {
340        selectedCat = data['result']['id'];
341        getCategories();
342        $("#album_name").val('');
343      } else {
344        message("Error", "An error has occured", '#album', data.err, data.message);
345      }
346    },
347    error: function(data) {
348      $.mobile.hidePageLoadingMsg();
349      message("Error", "An error has occured", '#album', data.status, data.statusText);
350    }
351  });
352}
353
354
355function appendPhoto(uri) {
356
357  var num = conf.imageNumber.toString();
358  var filesize;
359
360  for (i=num.length;i<4;i++) {
361    num = '0'+num;
362  }
363
364  var checkFileExists = function (fileEntry) {
365
366    fileEntry.file(function(file) {
367      filesize = file.size;
368      var needCheck = new Array;
369      for (i in queue) {
370        if (queue[i][1] == file.size) {
371          needCheck.push(i);
372        }
373      }
374      if (needCheck.length == 0) {
375        renameFile(fileEntry);
376      }
377      for (i in needCheck) {
378        var imageToCheckURI = $("#img_"+queue[i][0]+" img").attr("src");
379        var reader1 = new FileReader();
380        reader1.onloadend = function(evt1) {
381          var result1 = evt1.target.result;
382          var checkFile2 = function (fe) {
383            var reader2 = new FileReader();
384            reader2.onloadend = function(evt2) {
385              result2 = evt2.target.result;
386              if (result1 == result2) {
387                fileEntry.remove(null, null);
388                message("Warning", "This photo is already selected", "#photos");
389              } else {
390                renameFile(fileEntry);
391              }
392            };
393            reader2.readAsDataURL(fileEntry.fullPath);
394          }
395          window.resolveLocalFileSystemURI(imageToCheckURI, checkFile2);
396        };
397        reader1.readAsDataURL(fileEntry.fullPath);
398      }
399    });
400  };
401
402  var renameFile = function (fileEntry) {
403
404    if (OSCode != 'AND' || conf.resize) {
405      var fileParent = new DirectoryEntry();
406      fileParent.fullPath = fileEntry.fullPath.substring(0, fileEntry.fullPath.lastIndexOf('/'));
407      fileEntry.moveTo(fileParent, OSCode+num+'.jpg', appendFile, null);
408    } else {
409      appendFile(fileEntry);
410    }
411  };
412
413  var appendFile = function (newEntry) {
414    uri = newEntry.toURI();
415
416    $('#no_photos_yet').hide();
417    $('.upload_button, #remove_photos_button').show();
418   
419    $('#prepare_photo').html('<li id="img_'+conf.imageNumber+'"><a href="#" onClick="dialogBoxPhoto('+conf.imageNumber+')"><img class="upload" src="'+uri+'"><p style="margin-top:5px;">'+l10n("Title")+': <span class="photo_title">'+OSCode+num+'</span></p><p>'+l10n("Author")+': <span class="photo_author"></span></p><p>'+l10n("Description")+': <span class="photo_desc"></span></p><input type="hidden" name="filename['+conf.imageNumber+']" class="photo_filename" value="'+OSCode+num+'"></a><a href="#" onClick="removePhotoFromQueue('+conf.imageNumber+');removePhoto('+conf.imageNumber+');">delete</a></li>');
420     
421    $('#prepare_photo img').load(function() {
422      $(this).sqrop(80);
423      $('#photos_list').append($('#prepare_photo').html());
424      $('#photos_list').hide();
425      $('#photos_list').listview('refresh');
426      $('#photos_list').show();
427      $('#photos_list li img:last').sqrop(80);
428
429      var content_height = $("#photos_content").outerHeight();
430      var list_height = $("#photos_list").outerHeight();
431      if (list_height > content_height) {
432        $("#photos_content").scrollview("scrollTo", 0, content_height - list_height);
433      }
434    });
435   
436    if (conf.author != '') {
437      $('#img_'+conf.imageNumber+' .photo_author').html(conf.author);
438    }
439   
440    queue.push([conf.imageNumber, filesize]);
441    $(".nb_photos").html(queue.length);
442    conf.imageNumber++;
443    window.localStorage.setItem("pwg.imageNumber", conf.imageNumber);
444  };
445
446  window.resolveLocalFileSystemURI(uri, checkFileExists);
447}
448
449
450function removePhotoFromQueue(num) {
451
452  var new_queue = new Array;
453  for(var i in queue){
454                if (queue[i][0]!=num)
455                        new_queue.push(queue[i]);
456        }
457  queue = new_queue;
458  if (queue.length == 0) {
459    $('.upload_button, #remove_photos_button').hide();
460    $('#no_photos_yet').show();
461  }
462}
463
464
465function removePhoto(num) {
466
467  // Delete photo from cache
468  var deleteFileEntry = function (fileEntry) {
469    var n = num.toString();
470    for (i=n.length;i<4;i++) {
471      n = '0'+n;
472    }
473
474    if (fileEntry.name == OSCode+n+'.jpg') {
475      fileEntry.remove(null, null);
476    }
477  };
478  window.resolveLocalFileSystemURI($("#img_"+num+" img").attr("src"), deleteFileEntry);
479
480  // Remove photo from page
481  $('#img_'+num).remove();
482  $(".nb_photos").html(queue.length);
483  $("#photos_list").listview('refresh');
484}
485
486
487function removeAllPhotos() {
488
489  if (queue.length == 0) return;
490
491  for (i in queue) {
492    removePhoto(queue[i][0]);
493  }
494  queue = new Array();
495  $('.upload_button, #remove_photos_button').hide();
496  $('#no_photos_yet').show();
497  $("#photos_content").scrollview("scrollTo", 0, 0);
498}
499
500
501function dialogBoxPhoto(i) {
502
503    $('#photo_id').val(i);
504    $('#photobox_header h1').html($('#img_'+i+' input').val());
505    $('#photo_title').val($('#img_'+i+' .photo_title').html());
506    $('#photo_author').val($('#img_'+i+' .photo_author').html());
507    $('#photo_desc').val($('#img_'+i+' .photo_desc').html());
508
509    $.mobile.changePage('#photobox', { transition: "pop"});
510}
511
512
513function savePhotoData() {
514
515  i = $('#photo_id').val();
516  $('#img_'+i+' .photo_title').html($('#photo_title').val());
517  $('#img_'+i+' .photo_author').html($('#photo_author').val());
518  $('#img_'+i+' .photo_desc').html($('#photo_desc').val());
519}
520
521
522function prepareUpload() {
523
524  uploadInProgress = true;
525  uploadedPhotos = new Array;
526
527  $("#uploaded_photo img").attr('src', '');
528  $("#upload_complete").hide();
529  $("#uploading p").show();
530
531  selectedCat = $("#existing_album").val();
532  if (selectedCat == '0') {
533    message("Error", "You must select an album", "#album");
534    return false;
535  }
536
537  $("#upload_total").html($(".nb_photos").html());
538  $.mobile.changePage('#uploading', { transition: "slide"});
539  cancelRequest = false;
540  uploadPhotos();
541}
542
543
544function uploadPhotos() {
545
546  imageURI = $("#img_"+queue[0][0]+" img").attr("src");
547  imageFilename = $("#img_"+queue[0][0]+" .photo_filename").val();
548  imageName = $("#img_"+queue[0][0]+" .photo_title").html();
549  imageAuthor = $("#img_"+queue[0][0]+" .photo_author").html();
550  imageDesc =  $("#img_"+queue[0][0]+" .photo_desc").html();
551  imageLevel = $("#privacy_level").val();
552
553  $("#uploaded_photo img").attr('src', imageURI);
554  $("#upload_current").html(parseInt($("#upload_total").html())-queue.length+1);
555 
556  var options = new FileUploadOptions();
557  var extension = imageURI.substr(imageURI.lastIndexOf('.')+1).toLowerCase();
558 
559  options.fileName = imageFilename+'.'+extension;
560  options.fileKey = "image";
561  options.chunkedMode = false;
562
563  if (extension == 'jpg') extension = 'jpeg';
564  options.mimeType = "image/"+extension; 
565 
566  var params = new Object();
567  params.method = "pwg.images.addSimple";
568  params.category = selectedCat;
569  params.level = imageLevel;
570  if (imageName != imageFilename && imageName != '') params.name = imageName;
571  if (imageAuthor != '') params.author = imageAuthor;
572  if (imageDesc != '') params.comment  = imageDesc;
573   
574  options.params = params;
575  var fileTransfer = new FileTransfer();
576  fileTransfer.upload(imageURI, conf.url + "/ws.php?format=json", uploadComplete, uploadFail, options);
577
578}
579
580
581function cancelUpload() {
582
583  cancelRequest = 'pending';
584  navigator.notification.confirm(
585    l10n('Are you sure?'),
586    function (data) {
587      if (data == 1) {
588        cancelRequest = 'confirmed';
589
590        // Delete uploaded photos from server and re-add to queue
591        var toDelete = new Array;
592        uploadedPhotos.reverse();
593        for (i in uploadedPhotos) {
594          queue.unshift([uploadedPhotos[i][0], uploadedPhotos[i][1]]);
595          toDelete.push(uploadedPhotos[i][2]);
596        }
597        deleteUploadedPhotos(toDelete);
598        $.mobile.changePage("#photos", { transition: "slide", reverse: true });
599      } else {
600        cancelRequest = false;
601        if (!uploadInProgress) {
602          if (queue.length > 0) {
603            uploadInProgress = true;
604            uploadPhotos();
605          } else {
606            displayUploadResult();
607          }
608        }
609      }
610    },
611    l10n('Cancel'),
612    l10n('Yes')+','+l10n('No')
613  );
614}
615
616
617function uploadComplete(data) {
618
619  var obj = jQuery.parseJSON(data.response);
620  if (obj.stat == 'ok') {
621
622    if (cancelRequest == 'confirmed') {
623      deleteUploadedPhotos([obj.result.image_id]);
624      return;
625    }
626
627    uploadedPhotos.push([queue[0][0], queue[0][1], obj.result.image_id]);
628    removePhotoFromQueue(queue[0][0]);
629    lastImageURL = obj.result.url;
630
631    if (cancelRequest == 'pending') {
632      uploadInProgress = false;
633      return;
634    }
635
636    if (queue.length > 0) {
637      uploadPhotos();
638      return;
639    }
640
641    displayUploadResult();
642
643  } else {
644    $("#uploading p").hide();
645    for (i in uploadedPhotos) {
646      removePhoto(uploadedPhotos[i][0]);
647    }
648    message("Error", "An error has occured", '#photos', obj.err, obj.message);
649  }
650  uploadInProgress = false;
651}
652
653
654function displayUploadResult() {
655
656  var up = new Array;
657  for (i in uploadedPhotos) {
658    up.push(uploadedPhotos[i][2]);
659    removePhoto(uploadedPhotos[i][0]);
660  }
661
662  $("#uploading p").hide();
663  $("#upload_complete").show();
664
665  var indexURL = conf.url + '/index';
666  if (lastImageURL.indexOf('.php') > 0) {
667    indexURL += '.php';
668  }
669  if (lastImageURL.indexOf('?') > 0) {
670    indexURL += '?';
671  }
672  indexURL += '/category/' + selectedCat.toString();
673  indexURL += indexURL.indexOf('?') > 0 ? '&' : '?';
674  indexURL += 'image_order=4';
675
676  $("#uploaded_photos_url").attr('href', indexURL);
677}
678
679
680function deleteUploadedPhotos(set) {
681
682  $.ajax({
683    type: "POST",
684    url: conf.url + "/ws.php?format=json",
685    data: {
686      method : "pwg.images.delete",
687      image_id: set.join(','),
688      pwg_token: pwg_token
689    },
690    dataType: "json"
691  });
692}
693
694
695function uploadFail(error) {
696
697  uploadInProgress = false;
698  var info = {
699    1: "File not found",
700    2: "Invalid URL",
701    3: "Connection error"
702  }
703  message("Error", "An error has occured", '#photos', "Error "+error.code, info[error.code]);
704}
705
706
707function message(title, message, parent, code, info) {
708
709  message = l10n(message);
710  if (info != null) {
711    message += "\n"+code+": "+info; 
712  } else if (code != null) {
713    message += " ("+code+")";
714  }
715  backPage = parent;
716  navigator.notification.alert(
717    message,
718    function() { 
719      $.mobile.changePage(backPage, { transition: "slide", reverse: true });
720    },
721    l10n(title)
722  );
723}
Note: See TracBrowser for help on using the repository browser.