source: trunk/expressoMail1_2/js/mail_sync.js @ 7426

Revision 7426, 17.2 KB checked in by thiago, 11 years ago (diff)

Ticket #3088 - Validação na aba de pesquisas de mensagens locais.

Line 
1/**
2 * @author diogenes
3 */
4
5        /**
6         *  @param folders:
7         *              1 - rowid of folder in sqlite
8         *              2 - folder name in sqlite
9         *              3 - ids to not download(for auto archiving) or ids to download(for archiving)
10         *              4 - true for auto archiving and false for normal archiving.
11         */
12        function mail_sync() {
13                if (typeof(google) == 'undefined')
14                        return false;
15//              this.dbGears = null;
16//              this.localServer = null;
17//              this.store = null;
18                this.folders = new Array();
19                this.messages = null;
20                this.attachs = null;
21                this.url_attachs = null;
22                this.working = false;
23                this.is_auto = null;
24                this.errors = new Array();
25//              this.main_title = null;
26               
27                this.main_title = null;
28                this.dbGears = google.gears.factory.create('beta.database');
29                this.localServer = google.gears.factory.create('beta.localserver');
30                this.store = this.localServer.createStore('test-store');
31                this.update_folder = false;
32        }
33       
34        mail_sync.prototype.open_conn = function(){
35                var db_in_other_use = true;
36                var start_trying = new Date().getTime();
37                while (db_in_other_use) {
38                        try {
39                                this.dbGears.open('database-test');
40                                db_in_other_use = false;
41                        }
42                        catch (ex) {
43                                if(new Date().getTime()-start_trying>10000) { //too much time trying, throw an exception
44                                        throw ex;
45                                }
46                        }
47                }
48        }
49       
50        mail_sync.prototype.start_sync = function() {
51                if(this.working) {
52                        //Já está sincronizando...
53                        return;
54                }
55               
56                this.open_conn();
57
58                var rs = this.dbGears.execute("select id_folder,folder_name from folders_sync where uid_usuario=?",[account_id]);
59                if(!rs.isValidRow()) {
60                        this.dbGears.close();
61                        return;
62                }
63                       
64
65                this.working=true;
66                this.messages = null;
67                this.attachs = null;
68                this.url_attachs = null;
69
70                document.getElementById('main_title').innerHTML = get_lang("Creating folders structure");
71                while(rs.isValidRow()) {
72                        var temp = new Array();
73                        temp[0] = rs.field(0);
74                        temp[1] = rs.field(1);
75                        temp[2] = null;
76                        temp[3] = false;
77                        var rs2 = this.dbGears.execute("select mail.original_id from mail inner join folder on mail.id_folder=folder.rowid where folder.folder = ? and mail.uid_usuario=?",[temp[1]==get_lang('Inbox')?'Inbox':temp[1],account_id]);
78                        while(rs2.isValidRow()) {
79                                if(temp[2]==null)
80                                        temp[2]=rs2.field(0)+",";
81                                else
82                                        temp[2]+=rs2.field(0)+",";
83                                rs2.next();
84                        }
85                        this.folders.push(temp);
86                       
87                       
88                        //Criando estrutura de pastas...
89                        var folders_to_check = temp[0].split("/");//Todas as pastas tem ao menos INBOX/
90                        if (folders_to_check.length == 1)
91                                var actual_check = "Inbox";
92                        else {
93                                folders_to_check = folders_to_check.slice(1);
94                                var actual_check = folders_to_check[0];
95                        }
96                        for (var i in folders_to_check) {
97                                var rs2 = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?", [actual_check, account_id]);
98                               
99                                if (!rs2.isValidRow()) {
100                                        if((!preferences.hide_folders) || (preferences.hide_folders=="0"))
101                                                this.update_folder = true; //Precisa atualizar as pastas na arvore de pastas
102                                        this.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)", [actual_check, account_id]);
103                                }
104                                if(parseInt(i)+1<folders_to_check.length)
105                                        actual_check += "/"+folders_to_check[parseInt(i)+1];
106                        }
107                       
108                        rs.next();
109                }
110                this.dbGears.close();
111                this.syncronize_folders();
112        }
113       
114        mail_sync.prototype.archive_msgs = function(folder,folder_dest,ids) {
115
116                //this.main_title = document.getElementById('main_title').innerHTML;
117                var temp = new Array();
118                temp[0] = folder;
119                temp[1] = folder_dest.substr(6);
120                temp[2] = ids;
121                temp[3] = true;
122                this.folders.push(temp);
123                Element('chk_box_select_all_messages').checked = false;
124               
125                array_ids = ids.split(",");
126                for (var i in array_ids) {
127                        if (Element("check_box_message_" + array_ids[i]))
128                                Element("check_box_message_" + array_ids[i]).checked = false;
129                        remove_className(Element(array_ids[i]), 'selected_msg');
130                }
131                if(!this.working) {
132                        this.working=true;
133                        this.syncronize_folders();
134                }
135                else {
136                        write_msg(get_lang("An archiving is in process, but dont worry, expresso will process this messages after the actual archiving"));
137                }
138        }
139       
140        mail_sync.prototype.syncronize_folders = function() {
141                if (this.folders.length == 0) {
142                        document.getElementById('main_title').innerHTML = get_lang("Deleting downloadeds msgs...");
143                        expresso_mail_sync.remove_archived_mails();
144                        if((!preferences.hide_folders) || (preferences.hide_folders=="0")) {
145                                if (expresso_mail_sync.update_folder) {
146                                        //ttreeBox.update_folder();
147                                        expresso_mail_sync.update_folder = false;
148                                }
149                                else
150                                        draw_tree_local_folders();
151                        }
152                        expresso_mail_sync.working=false;
153                        return;
154                }
155                var folder_to_sync = this.folders.pop();
156                folder_to_sync[1] = folder_to_sync[0].toUpperCase()=="INBOX" && !folder_to_sync[3]?"Inbox":folder_to_sync[1];
157               
158                if(folder_to_sync[3]) { //Em caso de arquivamento normal, pode ser que a pasta inbox ainda não tenha sido criada.
159                        expresso_mail_sync.open_conn()
160                        if(folder_to_sync[1]=="Inbox" && !expresso_mail_sync.has_inbox_folder()) {
161                                if((!preferences.hide_folders) || (preferences.hide_folders=="0"))
162                                        expresso_mail_sync.update_folder = true; //Precisa atualizar as pastas na arvore de pastas
163                                expresso_mail_sync.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)",["Inbox",account_id]);
164                        }
165                        expresso_mail_sync.dbGears.close();
166                       
167                       
168                }
169               
170                var start_sync_mails = function(data) {
171                        if (!data) { //Erro ao pegar lista de e-mails a serem baixados
172                                write_msg(get_lang("Problems while downloading mails, please try later"));
173                                expresso_mail_sync.working=false;
174                                window.setTimeout("eval('document.getElementById(\"main_title\").innerHTML =\"Expresso Mail\"')",3000);
175                                return;
176                        }
177                        expresso_mail_sync.messages=data;
178                        if(expresso_mail_sync.is_auto)
179                                document.getElementById('main_title').innerHTML = get_lang("Auto archiving")+" "+lang_folder(folder_to_sync[1])+": 0 / "+data.length;
180                        else
181                                document.getElementById('main_title').innerHTML = get_lang("Archiving messages on folder")+" "+lang_folder(folder_to_sync[1])+": 0 / "+data.length;
182
183                        expresso_mail_sync.syncronize_mails(folder_to_sync[1]);
184                }
185               
186
187                if (folder_to_sync[3]) {
188                        document.getElementById('main_title').innerHTML = get_lang("Starting to archive messages");
189                        cExecute("$this.imap_functions.get_info_msgs&folder=" + folder_to_sync[0] + "&msgs_number=" + folder_to_sync[2], start_sync_mails);
190                        this.is_auto = false;
191                }
192                else {
193                        document.getElementById('main_title').innerHTML = get_lang("Starting to sync folder")+" "+lang_folder(folder_to_sync[1]);
194                        var params = "folder="+folder_to_sync[0]+"&mails="+folder_to_sync[2];
195                        cExecute("$this.imap_functions.msgs_to_archive", start_sync_mails,params);
196                        this.is_auto = true;
197                }
198                       
199        }
200       
201        mail_sync.prototype.syncronize_mails = function(folder_dest) {
202                if (expresso_mail_sync.messages == null || expresso_mail_sync.messages.length == 0) {
203                        expresso_mail_sync.syncronize_folders();
204                        return;
205                }
206               
207                msg_to_sync = expresso_mail_sync.messages.pop();
208               
209                //refresh loading
210                var value_to_change = document.getElementById('main_title').innerHTML.match(/\d+ \//);
211                value_to_change += "";
212                var new_value = value_to_change.replace(" /","");
213                new_value = parseInt(new_value) + 1;
214                document.getElementById('main_title').innerHTML = document.getElementById('main_title').innerHTML.replace(value_to_change,new_value+" /");
215                msg_to_sync = connector.unserialize(msg_to_sync);
216               
217                var source_msg = new Array();
218                source_msg['url'] = msg_to_sync.url_export_file;
219
220                if (typeof(msg_to_sync['array_attach'])=='object'&&(msg_to_sync['array_attach'] instanceof Array))
221                        expresso_mail_sync.attachs = msg_to_sync['array_attach'].slice();
222                else
223                        expresso_mail_sync.attachs = new Array();
224                expresso_mail_sync.attachs.push(source_msg);
225                expresso_mail_sync.download_attachs(msg_to_sync,folder_dest);
226        }
227       
228        mail_sync.prototype.download_attachs = function(msg,folder_dest) {
229                if (expresso_mail_sync.attachs == null || expresso_mail_sync.attachs.length == 0) {
230                        expresso_mail_sync.insert_mail(msg, folder_dest);
231                       
232                        return;
233                }
234               
235                attach_to_capt = expresso_mail_sync.attachs.pop();
236               
237                var call_back = function(url,success,captureId) {
238                        if (!success) {
239                                /*
240                                 * 0 - original id
241                                 * 1 - message subject
242                                 * 2 - original folder
243                                 */
244                                var mail_error = new Array();
245                                mail_error[0] = msg.msg_number;
246                                mail_error[1] = msg.subject;
247                                mail_error[2] = msg.msg_folder;
248                                expresso_mail_sync.errors.push(mail_error);
249                                alert('erro ao baixar: '+url);
250                               
251                                /*if (typeof(msg['array_attach']) == 'object' && (msg['array_attach'] instanceof Array)) {
252                                        for (var i in msg['array_attach']) { //remove os anexos que já foram baixados para essa mensagem...
253                                                expresso_mail_sync.store.remove(msg['array_attach'][i]['url']);
254                                        }
255                                }*/
256                                expresso_mail_sync.syncronize_mails(folder_dest); //Pula para o próximo e-mail.
257                        }
258                        else {
259                                expresso_mail_sync.download_attachs(msg, folder_dest);//continua baixando o próximo anexo
260                        }
261                }
262                expresso_mail_sync.store.capture(attach_to_capt['url'],call_back);
263        }
264       
265        mail_sync.prototype.insert_mail = function(msg,folder) {
266                try {
267
268                        expresso_mail_sync.open_conn();
269               
270                        var msg_info = msg;
271                        var msg_header = msg['header'];
272                        var anexos = msg['array_attach'];
273                       
274                       
275                        var unseen = 0;
276                        var flagged = 0;
277                        var answered = 0;
278                        var login = msg_info.login;
279                        var original_id = msg_info.msg_number;
280                        var original_folder = msg_info.msg_folder=='INBOX/Lixeira/tmpMoveToLocal'?msg_info.msg_folder+(Date.parse(new Date)):msg_info.msg_folder;
281
282                        //Os campos abaixo precisam estar isolados para busca de mensagens em cima deles.
283                        var from = connector.serialize(msg_info.from);
284                        var subject = msg_info.subject;
285                        var body = msg_info.body;
286                        var to = connector.serialize(msg_info.toaddress2);
287                        var cc = connector.serialize(msg_info.cc);
288                        var size = msg_header.Size;
289       
290                        //Zero os campos que foram isolados para não ter informações duplicadas
291                        msg_info.from = null;
292                        msg_info.subject = null;
293                        msg_info.body = null;
294                        msg_info.to = null;
295                        msg_info.cc = null;
296                        msg_header.Size=null;
297
298                        /**
299                         * The importance attribute can be empty, and javascript consider as null causing nullpointer.
300                         */
301                        if((msg_header.Importance == null) ||  (msg_header.Importance == ""))
302                                msg_header.Importance = "Normal";
303                       
304                       
305                        var mail = connector.serialize(msg_info);
306                        var header = connector.serialize(msg_header);
307       
308                        var timestamp = msg_info.timestamp;
309                        var id_folder;
310                       
311                        var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?", [folder, account_id]);
312                        id_folder = rs.field(0);
313       
314                        if(msg_info.Unseen=="U")
315                                unseen = 1;
316                        this.dbGears.execute("insert into mail (mail,original_id,original_folder,header,timestamp,uid_usuario,unseen,id_folder,ffrom,subject,fto,cc,body,size,flagged,answered) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[mail,original_id,original_folder,header,timestamp,login,unseen,id_folder,from,subject,to,cc,body,size,flagged,answered]);
317
318
319                       
320                        //Preenche os anexos.
321                        var id_mail = this.dbGears.lastInsertRowId;
322
323                        for (var i = 0; i < anexos.length; i++) {
324                                this.dbGears.execute("insert into anexo (id_mail,nome_anexo,url,pid) values (?,?,?,?)", [id_mail, anexos[i]['name'],anexos[i]['url'],anexos[i]['pid']]);
325                        }
326                       
327                        var check_remove;
328                        if(this.is_auto)
329                                check_remove = preferences.keep_after_auto_archiving;
330                        else
331                                check_remove = preferences.keep_archived_messages;
332                       
333                       
334                       
335                        if(check_remove!=1)
336                                this.dbGears.execute("insert into msgs_to_remove (id_msg,folder,uid_usuario) values (?,?,?)",[original_id,original_folder,account_id]);
337                                               
338                } catch (error) {
339                        /*
340                         * 0 - original id
341                         * 1 - message subject
342                         * 2 - original folder
343                         */
344                        var mail_error = new Array();
345                        mail_error[0] = original_id;
346                        mail_error[1] = subject;
347                        mail_error[2] = original_folder;
348                        this.errors.push(mail_error);
349                       
350                        if (typeof(msg_info['array_attach'])=='object'&&(msg_info['array_attach'] instanceof Array)) {
351                                for(var i in msg_info['array_attach']) { //remove os anexos que já foram baixados para essa mensagem...
352                                        this.store.remove(msg_info['array_attach'][i]['url']);
353                                }
354                        }
355
356                }
357                this.dbGears.close();
358                this.syncronize_mails(folder);
359        }
360       
361        mail_sync.prototype.has_inbox_folder = function() {//This function considers that the connection with base is already opened.
362                var rs = this.dbGears.execute("select rowid from folder where folder='Inbox' and uid_usuario=?",[account_id]);
363                if(rs.isValidRow())
364                        return true;
365                else
366                        return false;
367        }
368       
369        mail_sync.prototype.remove_archived_mails = function() {
370               
371                expresso_mail_sync.open_conn();
372
373                var rs = this.dbGears.execute("select distinct(folder) from msgs_to_remove where uid_usuario=?",[account_id]);
374                if(rs.isValidRow()) {
375                        var folder_to_remove_msgs = rs.field(0);
376                        var rs2 = this.dbGears.execute("select id_msg from msgs_to_remove where folder=? and uid_usuario=?",[folder_to_remove_msgs,account_id]);
377                       
378                        var msgs = null;
379                        while(rs2.isValidRow()) {
380                                if(msgs==null)
381                                        msgs = rs2.field(0);
382                                else
383                                        msgs += ","+rs2.field(0);
384                                rs2.next();
385                        }
386                       
387                       
388                        var handler_delete_msgs = function(data){
389                                if (current_folder == data.folder) {
390                                        mail_msg = Element("tbody_box");
391                                        var msg_to_delete;
392                                        for (var i = 0; i < data.msgs_number.length; i++) {
393                                                msg_to_delete = Element(data.msgs_number[i]);
394                                                if (msg_to_delete) {
395                                                        mail_msg.removeChild(msg_to_delete);
396                                                }
397                                        }
398                                        Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) - data.msgs_number.length;
399                                }
400                               
401                                refresh();
402                                expresso_mail_sync.remove_archived_mails();
403                        }
404                       
405                        cExecute ("$this.imap_functions.delete_msgs&folder="+folder_to_remove_msgs+"&msgs_number="+msgs, handler_delete_msgs);
406                        this.dbGears.execute("delete from msgs_to_remove where folder=? and uid_usuario=?",[folder_to_remove_msgs,account_id]);
407                        this.dbGears.close();
408                       
409                }
410                else {
411                        this.dbGears.close();
412                        document.getElementById('main_title').innerHTML = get_lang("End of archive messages");
413                        if(this.errors.length>0) {
414                                //TODO: Tratar melhor quando existirem erros...
415                                write_msg(get_lang("at least, one of selected mails is already archived, expresso tried to archive the others, check them later"));
416                                this.errors=new Array();
417                        }
418                        window.setTimeout("eval('document.getElementById(\"main_title\").innerHTML =\"Expresso Mail\"')",3000);
419                }
420               
421        }
422       
423        mail_sync.prototype.configure_sync = function(folders,formul) {
424                this.dbGears = google.gears.factory.create('beta.database');
425                this.localServer = google.gears.factory.create('beta.localserver');
426                this.store = this.localServer.createStore('test-store');       
427                this.dbGears.open('database-test');
428                this.dbGears.execute("delete from folders_sync where uid_usuario=?",[account_id]);
429                for (var i=0;i<folders.length;i++) {
430                        var pos = folders[i].value.indexOf("/");
431                        if(pos=="-1")
432                                var folder_name = folders[i].text;
433                        else
434                                var folder_name = folders[i].value.substr(pos+1);
435
436                        folders[i].value = folders[i].value.replace(/#/g,' '); //Whitespaces has the # symbol in combo.
437                        folder_name = folder_name.replace(/#/g,' '); //Whitespaces has the # symbol in combo.
438                       
439                        this.dbGears.execute("insert into folders_sync (id_folder,folder_name,uid_usuario) values (?,?,?)",[folders[i].value,folder_name,account_id]);
440                }
441                this.dbGears.close();
442                formul.submit();
443        }
444       
445        mail_sync.prototype.fill_combos_of_folders = function(combo_sync) {
446                var folders = expresso_local_messages.get_folders_to_sync();
447
448                for(var i=0;i<folders.length;i++) {
449                        var option = document.createElement('option');
450                        option.value = folders[i][0];
451                        if (folders[i][1].indexOf("/") != "-1") {
452                                final_pos = folders[i][1].lastIndexOf("/");
453                                option.text =folders[i][1].substr(final_pos+1);
454                        }
455                        else
456                                option.text = folders[i][1];
457                        try {
458                                combo_sync.add(option,null);
459                        }catch (ex) {// I.E
460                                combo_sync.add(option);
461                        }
462
463                }
464        }
465       
466        mail_sync.prototype.add_folder = function (select_sync_folders,select_available_folders)
467        {
468                var count_available_folders = select_available_folders.length;
469                var count_sync_folders = select_sync_folders.options.length;
470                var new_options = '';
471               
472                for (i = 0 ; i < count_available_folders ; i++)
473                {
474                        if (select_available_folders.options[i].selected)
475                        {
476                                if(document.all)
477                                {
478                                        if ( (select_sync_folders.innerHTML.indexOf('value='+select_available_folders.options[i].value)) == '-1' )
479                                        {
480                                                new_options +=  '<option value='
481                                                                        + select_available_folders.options[i].value
482                                                                        + '>'
483                                                                        + select_available_folders.options[i].text
484                                                                        + '</option>';
485                                        }
486                                }
487                                else
488                                {
489                                        if ( (select_sync_folders.innerHTML.indexOf('value="'+select_available_folders.options[i].value+'"')) == '-1' )
490                                        {
491                                                new_options +=  '<option value='
492                                                                        + select_available_folders.options[i].value
493                                                                        + '>'
494                                                                        + select_available_folders.options[i].text
495                                                                        + '</option>';
496                                        }
497                                }
498                        }
499                }
500       
501                if (new_options != '')
502                {
503                        select_sync_folders.innerHTML = '&nbsp;' + new_options + select_sync_folders.innerHTML;
504                        select_sync_folders.outerHTML = select_sync_folders.outerHTML;
505                }
506        }
507       
508        mail_sync.prototype.remove_folder = function(select_sync_folders)
509        {
510                for(var i = 0;i < select_sync_folders.options.length; i++)
511                        if(select_sync_folders.options[i].selected)
512                                select_sync_folders.options[i--] = null;
513        }
514       
515        var expresso_mail_sync;
516        expresso_mail_sync = new mail_sync();
517       
Note: See TracBrowser for help on using the repository browser.