source: trunk/expressoMail1_2/js/jscode/mail_sync.js @ 2676

Revision 2676, 17.1 KB checked in by rafaelraymundo, 14 years ago (diff)

Ticket #490 - Reestabelecido o funcionamento do arquivamento local

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//              this.dbGears = null;
14//              this.localServer = null;
15//              this.store = null;
16                this.folders = new Array();
17                this.messages = null;
18                this.attachs = null;
19                this.url_attachs = null;
20                this.working = false;
21                this.is_auto = null;
22                this.errors = new Array();
23//              this.main_title = null;
24               
25                this.main_title = null;
26                this.dbGears = google.gears.factory.create('beta.database');
27                this.localServer = google.gears.factory.create('beta.localserver');
28                this.store = this.localServer.createStore('test-store');
29        }
30       
31        mail_sync.prototype.open_conn = function(){
32                var db_in_other_use = true;
33                var start_trying = new Date().getTime();
34                while (db_in_other_use) {
35                        try {
36                                this.dbGears.open('database-test');
37                                db_in_other_use = false;
38                        }
39                        catch (ex) {
40                                if(new Date().getTime()-start_trying>10000) { //too much time trying, throw an exception
41                                        throw ex;
42                                }
43                        }
44                }
45        }
46       
47        mail_sync.prototype.start_sync = function() {
48                if(this.working) {
49                        //Já está sincronizando...
50                        return;
51                }
52               
53                this.open_conn();
54
55                var rs = this.dbGears.execute("select id_folder,folder_name from folders_sync where uid_usuario=?",[account_id]);
56                if(!rs.isValidRow()) {
57                        this.dbGears.close();
58                        return;
59                }
60                       
61
62                this.working=true;
63                this.messages = null;
64                this.attachs = null;
65                this.url_attachs = null;
66
67                document.getElementById('main_title').innerHTML = get_lang("Creating folders structure");
68                while(rs.isValidRow()) {
69                        var temp = new Array();
70                        temp[0] = rs.field(0);
71                        temp[1] = rs.field(1);
72                        temp[2] = null;
73                        temp[3] = false;
74                        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]);
75                        while(rs2.isValidRow()) {
76                                if(temp[2]==null)
77                                        temp[2]=rs2.field(0)+",";
78                                else
79                                        temp[2]+=rs2.field(0)+",";
80                                rs2.next();
81                        }
82                        this.folders.push(temp);
83                       
84                       
85                        //Criando estrutura de pastas...
86                        var folders_to_check = temp[0].split("/");//Todas as pastas tem ao menos INBOX/
87                        if (folders_to_check.length == 1)
88                                var actual_check = "Inbox";
89                        else {
90                                folders_to_check = folders_to_check.slice(1);
91                                var actual_check = folders_to_check[0];
92                        }
93                        for (var i in folders_to_check) {
94                                var rs2 = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?", [actual_check, account_id]);
95                               
96                                if (!rs2.isValidRow()) {
97                                        this.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)", [actual_check, account_id]);
98                                }
99                                if(parseInt(i)+1<folders_to_check.length)
100                                        actual_check += "/"+folders_to_check[parseInt(i)+1];
101                        }
102                        ttreeBox.update_folder();
103                        rs.next();
104                }
105                this.dbGears.close();
106                this.syncronize_folders();
107        }
108       
109        mail_sync.prototype.archive_msgs = function(folder,folder_dest,ids) {
110                //this.main_title = document.getElementById('main_title').innerHTML;
111                var temp = new Array();
112                temp[0] = folder;
113                temp[1] = folder_dest.substr(6);
114                temp[2] = ids;
115                temp[3] = true;
116                this.folders.push(temp);
117                Element('chk_box_select_all_messages').checked = false;
118               
119                array_ids = ids.split(",");
120                for (var i in array_ids) {
121                        if (Element("check_box_message_" + array_ids[i]))
122                                Element("check_box_message_" + array_ids[i]).checked = false;
123                        remove_className(Element(array_ids[i]), 'selected_msg');
124                }
125                if(!this.working) {
126                        this.working=true;
127                        this.syncronize_folders();
128                }
129                else {
130                        write_msg(get_lang("An archiving is in process, but dont worry, expresso will process this messages after the actual archiving"));
131                }
132        }
133       
134        mail_sync.prototype.syncronize_folders = function() {
135                if (this.folders.length == 0) {
136                        document.getElementById('main_title').innerHTML = get_lang("Deleting downloadeds msgs...");
137                        expresso_mail_sync.remove_archived_mails();
138                        this.working=false;
139                        update_menu();
140                        return;
141                }
142                var folder_to_sync = this.folders.pop();
143                folder_to_sync[1] = folder_to_sync[0].toUpperCase()=="INBOX" && !folder_to_sync[3]?"Inbox":folder_to_sync[1];
144               
145                if(folder_to_sync[3]) { //Em caso de arquivamento normal, pode ser que a pasta inbox ainda não tenha sido criada.
146                        expresso_mail_sync.open_conn()
147                        if(folder_to_sync[1]=="Inbox" && !expresso_mail_sync.has_inbox_folder()) {
148                                expresso_mail_sync.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)",["Inbox",account_id]);
149                        }
150                        expresso_mail_sync.dbGears.close();
151                        ttreeBox.update_folder();
152                       
153                }
154               
155                var start_sync_mails = function(data) {
156                        data =  expresso.connector.unserialize( data );
157                        expresso_mail_sync.messages=data;
158                        if(expresso_mail_sync.is_auto)
159                                document.getElementById('main_title').innerHTML = get_lang("Auto archiving")+" "+lang_folder(folder_to_sync[1])+": 0 / "+data.length;
160                        else
161                                document.getElementById('main_title').innerHTML = get_lang("Archiving messages on folder")+" "+lang_folder(folder_to_sync[1])+": 0 / "+data.length;
162
163                        expresso_mail_sync.syncronize_mails(folder_to_sync[1]);
164                }
165               
166
167                if (folder_to_sync[3]) {
168                        document.getElementById('main_title').innerHTML = get_lang("Starting to archive messages");
169                        _connector.cache();
170                        _connector.go( {
171                                "access" : "expressoMail1_2.imap_functions.get_info_msgs&folder=" + folder_to_sync[0] + "&msgs_number=" + folder_to_sync[2],
172                                "cache" : true,
173                                "handler" : start_sync_mails
174                        } );
175
176                        //cExecute("expressoMail1_2.imap_functions.get_info_msgs&folder=" + folder_to_sync[0] + "&msgs_number=" + folder_to_sync[2], start_sync_mails);
177                        this.is_auto = false;
178                }
179                else {
180                        document.getElementById('main_title').innerHTML = get_lang("Starting to sync folder")+" "+lang_folder(folder_to_sync[1]);
181                        var params = "folder="+folder_to_sync[0]+"&mails="+folder_to_sync[2];
182                        _connector.cache();
183                        _connector.go( {
184                                "access" : "expressoMail1_2.imap_functions.msgs_to_archive"+params,
185                                "cache" : true,
186                                "handler" : start_sync_mails
187                        } );
188
189                        //cExecute("expressoMail1_2.imap_functions.msgs_to_archive", start_sync_mails,params);
190                        this.is_auto = true;
191                }
192                       
193        }
194       
195        mail_sync.prototype.syncronize_mails = function(folder_dest) {
196                if (expresso_mail_sync.messages == null || expresso_mail_sync.messages.length == 0) {
197                        expresso_mail_sync.syncronize_folders();
198                        return;
199                }
200               
201                msg_to_sync = expresso_mail_sync.messages.pop();
202               
203                //refresh loading
204                var value_to_change = document.getElementById('main_title').innerHTML.match(/\d+ \//);
205                value_to_change += "";
206                var new_value = value_to_change.replace(" /","");
207                new_value = parseInt(new_value) + 1;
208                document.getElementById('main_title').innerHTML = document.getElementById('main_title').innerHTML.replace(value_to_change,new_value+" /");
209                //msg_to_sync = expresso.connector.unserialize(msg_to_sync);
210               
211                var source_msg = new Array();
212                source_msg['url'] = msg_to_sync.url_export_file;
213
214                if (typeof(msg_to_sync['array_attach'])=='object'&&(msg_to_sync['array_attach'] instanceof Array))
215                        expresso_mail_sync.attachs = msg_to_sync['array_attach'].slice();
216                else
217                        expresso_mail_sync.attachs = new Array();
218                expresso_mail_sync.attachs.push(source_msg);
219                expresso_mail_sync.download_attachs(msg_to_sync,folder_dest);
220        }
221       
222        mail_sync.prototype.download_attachs = function(msg,folder_dest) {
223                if (expresso_mail_sync.attachs == null || expresso_mail_sync.attachs.length == 0) {
224                        expresso_mail_sync.insert_mail(msg, folder_dest);
225                       
226                        return;
227                }
228               
229                attach_to_capt = expresso_mail_sync.attachs.pop();
230               
231                var call_back = function(url,success,captureId) {
232                        if (!success) {
233                                /*
234                                 * 0 - original id
235                                 * 1 - message subject
236                                 * 2 - original folder
237                                 */
238                                var mail_error = new Array();
239                                mail_error[0] = msg.msg_number;
240                                mail_error[1] = msg.subject;
241                                mail_error[2] = msg.msg_folder;
242                                expresso_mail_sync.errors.push(mail_error);
243                                alert('erro ao baixar: '+url);
244                               
245                                /*if (typeof(msg['array_attach']) == 'object' && (msg['array_attach'] instanceof Array)) {
246                                        for (var i in msg['array_attach']) { //remove os anexos que já foram baixados para essa mensagem...
247                                                expresso_mail_sync.store.remove(msg['array_attach'][i]['url']);
248                                        }
249                                }*/
250                                expresso_mail_sync.syncronize_mails(folder_dest); //Pula para o próximo e-mail.
251                        }
252                        else {
253                                expresso_mail_sync.download_attachs(msg, folder_dest);//continua baixando o próximo anexo
254                        }
255                }
256                expresso_mail_sync.store.capture(attach_to_capt['url'],call_back);
257        }
258       
259        mail_sync.prototype.insert_mail = function(msg,folder) {
260                try {
261                        connector = expresso.connector;
262                        expresso_mail_sync.open_conn();
263               
264                        var msg_info = msg;
265                        var msg_header = msg['header'];
266                        var anexos = msg['array_attach'];
267                       
268                       
269                        var unseen = 0;
270                        var login = msg_info.login;
271                        var original_id = msg_info.msg_number;
272                        var original_folder = msg_info.msg_folder=='INBOX/Lixeira/tmpMoveToLocal'?msg_info.msg_folder+(Date.parse(new Date)):msg_info.msg_folder;
273
274                        //Os campos abaixo precisam estar isolados para busca de mensagens em cima deles.
275                        var from = connector.serialize(msg_info.from);
276                        var subject = msg_info.subject;
277                        var body = msg_info.body;
278                        var to = connector.serialize(msg_info.toaddress2);
279                        var cc = connector.serialize(msg_info.cc);
280                        var size = msg_header.Size;
281       
282                        //Zero os campos que foram isolados para não ter informações duplicadas
283                        msg_info.from = null;
284                        msg_info.subject = null;
285                        msg_info.body = null;
286                        msg_info.to = null;
287                        msg_info.cc = null;
288                        msg_header.Size=null;
289                       
290                        //A data no header pode vir como horário ao invés de data, caso o usuário tenha arquivado no mesmo
291                        //dia que recebeu a msg. Para esses casos, usar a data aux que vem com o dia.
292                        if(msg_header.udate.indexOf("/")==-1) {
293                                msg_header.udate = msg_header.aux_date;
294                        }
295               
296                       
297                        /**
298                         * The importance attribute can be empty, and javascript consider as null causing nullpointer.
299                         */
300                        if((msg_header.Importance == null) ||  (msg_header.Importance == ""))
301                                msg_header.Importance = "Normal";
302                       
303                        msg_header.aux_date = null; //esse dado não é mais preciso no email.
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")|| (msg_info.Recent=="N"))
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) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[mail,original_id,original_folder,header,timestamp,login,unseen,id_folder,from,subject,to,cc,body,size]);
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'");
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                                ttreeBox.update_folder();
401                                refresh();
402                                expresso_mail_sync.remove_archived_mails();
403                        }
404
405                        _connector.cache();
406                        _connector.go( {
407                                "access" : "expressoMail1_2.imap_functions.delete_msgs&folder="+folder_to_remove_msgs+"&msgs_number="+msgs,
408                                "cache" : true,
409                                "handler" : handler_delete_msgs
410                        } );
411                       
412                        //cExecute ("expressoMail1_2.imap_functions.delete_msgs&folder="+folder_to_remove_msgs+"&msgs_number="+msgs, handler_delete_msgs);
413                        this.dbGears.execute("delete from msgs_to_remove where folder=? and uid_usuario=?",[folder_to_remove_msgs,account_id]);
414                        this.dbGears.close();
415                       
416                }
417                else {
418                        this.dbGears.close();
419                        document.getElementById('main_title').innerHTML = get_lang("End of archive messages");
420                        if(this.errors.length>0) {
421                                //TODO: Tratar melhor quando existirem erros...
422                                write_msg(get_lang("at least, one of selected mails is already archived, expresso tried to archive the others, check them later"));
423                                this.errors=new Array();
424                        }
425                        window.setTimeout("eval('document.getElementById(\"main_title\").innerHTML =\"Expresso Mail\"')",3000);
426                }
427               
428        }
429       
430        mail_sync.prototype.configure_sync = function(folders,formul) {
431                this.dbGears = google.gears.factory.create('beta.database');
432                this.localServer = google.gears.factory.create('beta.localserver');
433                this.store = this.localServer.createStore('test-store');       
434                this.dbGears.open('database-test');
435                this.dbGears.execute("delete from folders_sync where uid_usuario=?",[account_id]);
436                for (var i=0;i<folders.length;i++) {
437                        var pos = folders[i].value.indexOf("/");
438                        if(pos=="-1")
439                                var folder_name = folders[i].text;
440                        else
441                                var folder_name = folders[i].value.substr(pos+1);
442                        this.dbGears.execute("insert into folders_sync (id_folder,folder_name,uid_usuario) values (?,?,?)",[folders[i].value,folder_name,account_id]);
443                }
444                this.dbGears.close();
445                formul.submit();
446        }
447       
448        mail_sync.prototype.fill_combos_of_folders = function(combo_sync) {
449                var folders = expresso_local_messages.get_folders_to_sync();
450
451                for(var i=0;i<folders.length;i++) {
452                        var option = document.createElement('option');
453                        option.value = folders[i][0];
454                        if (folders[i][1].indexOf("/") != "-1") {
455                                final_pos = folders[i][1].lastIndexOf("/");
456                                option.text =folders[i][1].substr(final_pos+1);
457                        }
458                        else
459                                option.text = folders[i][1];
460                        try {
461                                combo_sync.add(option,null);
462                        }catch (ex) {// I.E
463                                combo_sync.add(option);
464                        }
465
466                }
467        };
468       
469        mail_sync.prototype.add_folder = function (select_sync_folders,select_available_folders)
470        {
471                var count_available_folders = select_available_folders.length;
472                var count_sync_folders = select_sync_folders.options.length;
473                var new_options = '';
474               
475                for (i = 0 ; i < count_available_folders ; i++)
476                {
477                        if (select_available_folders.options[i].selected)
478                        {
479                                if(document.all)
480                                {
481                                        if ( (select_sync_folders.innerHTML.indexOf('value='+select_available_folders.options[i].value)) == '-1' )
482                                        {
483                                                new_options +=  '<option value='
484                                                                        + select_available_folders.options[i].value
485                                                                        + '>'
486                                                                        + select_available_folders.options[i].text
487                                                                        + '</option>';
488                                        }
489                                }
490                                else
491                                {
492                                        if ( (select_sync_folders.innerHTML.indexOf('value="'+select_available_folders.options[i].value+'"')) == '-1' )
493                                        {
494                                                new_options +=  '<option value='
495                                                                        + select_available_folders.options[i].value
496                                                                        + '>'
497                                                                        + select_available_folders.options[i].text
498                                                                        + '</option>';
499                                        }
500                                }
501                        }
502                }
503       
504                if (new_options != '')
505                {
506                        select_sync_folders.innerHTML = '&nbsp;' + new_options + select_sync_folders.innerHTML;
507                        select_sync_folders.outerHTML = select_sync_folders.outerHTML;
508                }
509        };
510       
511        mail_sync.prototype.remove_folder = function(select_sync_folders)
512        {
513                for(var i = 0;i < select_sync_folders.options.length; i++)
514                        if(select_sync_folders.options[i].selected)
515                                select_sync_folders.options[i--] = null;
516        };
517       
518        var expresso_mail_sync;
519        expresso_mail_sync = new mail_sync();
520       
Note: See TracBrowser for help on using the repository browser.