source: branches/2.1/expressoMail1_2/js/mail_sync.js @ 2379

Revision 2379, 16.4 KB checked in by eduardoalex, 14 years ago (diff)

Ticket #1014 - Replicando no branch 2.1 a correção descrita no ticket em questao.

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                        expresso_mail_sync.messages=data;
157                        if(expresso_mail_sync.is_auto)
158                                document.getElementById('main_title').innerHTML = get_lang("Auto archiving")+" "+lang_folder(folder_to_sync[1])+": 0 / "+data.length;
159                        else
160                                document.getElementById('main_title').innerHTML = get_lang("Archiving messages on folder")+" "+lang_folder(folder_to_sync[1])+": 0 / "+data.length;
161
162                        expresso_mail_sync.syncronize_mails(folder_to_sync[1]);
163                }
164               
165
166                if (folder_to_sync[3]) {
167                        document.getElementById('main_title').innerHTML = get_lang("Starting to archive messages");
168                        cExecute("$this.imap_functions.get_info_msgs&folder=" + folder_to_sync[0] + "&msgs_number=" + folder_to_sync[2], start_sync_mails);
169                        this.is_auto = false;
170                }
171                else {
172                        document.getElementById('main_title').innerHTML = get_lang("Starting to sync folder")+" "+lang_folder(folder_to_sync[1]);
173                        var params = "folder="+folder_to_sync[0]+"&mails="+folder_to_sync[2];
174                        cExecute("$this.imap_functions.msgs_to_archive", start_sync_mails,params);
175                        this.is_auto = true;
176                }
177                       
178        }
179       
180        mail_sync.prototype.syncronize_mails = function(folder_dest) {
181                if (expresso_mail_sync.messages == null || expresso_mail_sync.messages.length == 0) {
182                        expresso_mail_sync.syncronize_folders();
183                        return;
184                }
185               
186                msg_to_sync = expresso_mail_sync.messages.pop();
187               
188                //refresh loading
189                var value_to_change = document.getElementById('main_title').innerHTML.match(/\d+ \//);
190                value_to_change += "";
191                var new_value = value_to_change.replace(" /","");
192                new_value = parseInt(new_value) + 1;
193                document.getElementById('main_title').innerHTML = document.getElementById('main_title').innerHTML.replace(value_to_change,new_value+" /");
194                msg_to_sync = connector.unserialize(msg_to_sync);
195               
196                var source_msg = new Array();
197                source_msg['url'] = msg_to_sync.url_export_file;
198
199                if (typeof(msg_to_sync['array_attach'])=='object'&&(msg_to_sync['array_attach'] instanceof Array))
200                        expresso_mail_sync.attachs = msg_to_sync['array_attach'].slice();
201                else
202                        expresso_mail_sync.attachs = new Array();
203                expresso_mail_sync.attachs.push(source_msg);
204                expresso_mail_sync.download_attachs(msg_to_sync,folder_dest);
205        }
206       
207        mail_sync.prototype.download_attachs = function(msg,folder_dest) {
208                if (expresso_mail_sync.attachs == null || expresso_mail_sync.attachs.length == 0) {
209                        expresso_mail_sync.insert_mail(msg, folder_dest);
210                       
211                        return;
212                }
213               
214                attach_to_capt = expresso_mail_sync.attachs.pop();
215               
216                var call_back = function(url,success,captureId) {
217                       
218                        if (!success) {
219                                /*
220                                 * 0 - original id
221                                 * 1 - message subject
222                                 * 2 - original folder
223                                 */
224                                var mail_error = new Array();
225                                mail_error[0] = msg.msg_number;
226                                mail_error[1] = msg.subject;
227                                mail_error[2] = msg.msg_folder;
228                                expresso_mail_sync.errors.push(mail_error);
229                                alert('erro ao baixar: '+url);
230                               
231                                /*if (typeof(msg['array_attach']) == 'object' && (msg['array_attach'] instanceof Array)) {
232                                        for (var i in msg['array_attach']) { //remove os anexos que já foram baixados para essa mensagem...
233                                                expresso_mail_sync.store.remove(msg['array_attach'][i]['url']);
234                                        }
235                                }*/
236                                expresso_mail_sync.syncronize_mails(folder_dest); //Pula para o próximo e-mail.
237                        }
238                        else {
239                                expresso_mail_sync.download_attachs(msg, folder_dest);//continua baixando o próximo anexo
240                        }
241                }
242                expresso_mail_sync.store.capture(attach_to_capt['url'],call_back);
243        }
244       
245        mail_sync.prototype.insert_mail = function(msg,folder) {
246                try {
247
248                        expresso_mail_sync.open_conn();
249               
250                        var msg_info = msg;
251                        var msg_header = msg['header'];
252                        var anexos = msg['array_attach'];
253                       
254                       
255                        var unseen = 0;
256                        var login = msg_info.login;
257                        var original_id = msg_info.msg_number;
258                        var original_folder = msg_info.msg_folder=='INBOX/Lixeira/tmpMoveToLocal'?msg_info.msg_folder+(Date.parse(new Date)):msg_info.msg_folder;
259
260                        //Os campos abaixo precisam estar isolados para busca de mensagens em cima deles.
261                        var from = connector.serialize(msg_info.from);
262                        var subject = msg_info.subject;
263                        var body = msg_info.body;
264                        var to = connector.serialize(msg_info.toaddress2);
265                        var cc = connector.serialize(msg_info.cc);
266                        var size = msg_header.Size;
267       
268                        //Zero os campos que foram isolados para não ter informações duplicadas
269                        msg_info.from = null;
270                        msg_info.subject = null;
271                        msg_info.body = null;
272                        msg_info.to = null;
273                        msg_info.cc = null;
274                        msg_header.Size=null;
275                       
276                        //A data no header pode vir como horário ao invés de data, caso o usuário tenha arquivado no mesmo
277                        //dia que recebeu a msg. Para esses casos, usar a data aux que vem com o dia.
278                        if(msg_header.udate.indexOf("/")==-1) {
279                                msg_header.udate = msg_header.aux_date;
280                        }
281               
282                       
283                        /**
284                         * The importance attribute can be empty, and javascript consider as null causing nullpointer.
285                         */
286                        if((msg_header.Importance == null) ||  (msg_header.Importance == ""))
287                                msg_header.Importance = "Normal";
288                       
289                        msg_header.aux_date = null; //esse dado não é mais preciso no email.
290                       
291                        var mail = connector.serialize(msg_info);
292                        var header = connector.serialize(msg_header);
293       
294                        var timestamp = msg_info.timestamp;
295                        var id_folder;
296                       
297                        var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?", [folder, account_id]);
298                        id_folder = rs.field(0);
299       
300                        if((msg_info.Unseen=="U")|| (msg_info.Recent=="N"))
301                                unseen = 1;
302                        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]);
303                       
304                       
305                       
306                        //Preenche os anexos.
307                        var id_mail = this.dbGears.lastInsertRowId;
308
309                        for (var i = 0; i < anexos.length; i++) {
310                                this.dbGears.execute("insert into anexo (id_mail,nome_anexo,url,pid) values (?,?,?,?)", [id_mail, anexos[i]['name'],anexos[i]['url'],anexos[i]['pid']]);
311                        }
312                       
313                        var check_remove;
314                        if(this.is_auto)
315                                check_remove = preferences.keep_after_auto_archiving;
316                        else
317                                check_remove = preferences.keep_archived_messages;
318                       
319                       
320                       
321                        if(check_remove!=1)
322                                this.dbGears.execute("insert into msgs_to_remove (id_msg,folder,uid_usuario) values (?,?,?)",[original_id,original_folder,account_id]);
323                                               
324                } catch (error) {
325                        /*
326                         * 0 - original id
327                         * 1 - message subject
328                         * 2 - original folder
329                         */
330                        var mail_error = new Array();
331                        mail_error[0] = original_id;
332                        mail_error[1] = subject;
333                        mail_error[2] = original_folder;
334                        this.errors.push(mail_error);
335                       
336                        if (typeof(msg_info['array_attach'])=='object'&&(msg_info['array_attach'] instanceof Array)) {
337                                for(var i in msg_info['array_attach']) { //remove os anexos que já foram baixados para essa mensagem...
338                                        this.store.remove(msg_info['array_attach'][i]['url']);
339                                }
340                        }
341
342                }
343                this.dbGears.close();
344                this.syncronize_mails(folder);
345        }
346       
347        mail_sync.prototype.has_inbox_folder = function() {//This function considers that the connection with base is already opened.
348                var rs = this.dbGears.execute("select rowid from folder where folder = 'Inbox'");
349                if(rs.isValidRow())
350                        return true;
351                else
352                        return false;
353        }
354       
355        mail_sync.prototype.remove_archived_mails = function() {
356               
357                expresso_mail_sync.open_conn();
358
359                var rs = this.dbGears.execute("select distinct(folder) from msgs_to_remove where uid_usuario=?",[account_id]);
360                if(rs.isValidRow()) {
361                        var folder_to_remove_msgs = rs.field(0);
362                        var rs2 = this.dbGears.execute("select id_msg from msgs_to_remove where folder=? and uid_usuario=?",[folder_to_remove_msgs,account_id]);
363                       
364                        var msgs = null;
365                        while(rs2.isValidRow()) {
366                                if(msgs==null)
367                                        msgs = rs2.field(0);
368                                else
369                                        msgs += ","+rs2.field(0);
370                                rs2.next();
371                        }
372                       
373                       
374                        var handler_delete_msgs = function(data){
375                                if (current_folder == data.folder) {
376                                        mail_msg = Element("tbody_box");
377                                        var msg_to_delete;
378                                        for (var i = 0; i < data.msgs_number.length; i++) {
379                                                msg_to_delete = Element(data.msgs_number[i]);
380                                                if (msg_to_delete) {
381                                                        mail_msg.removeChild(msg_to_delete);
382                                                }
383                                        }
384                                        Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) - data.msgs_number.length;
385                                }
386                                ttreeBox.update_folder();
387                                refresh();
388                                expresso_mail_sync.remove_archived_mails();
389                        }
390                       
391                        cExecute ("$this.imap_functions.delete_msgs&folder="+folder_to_remove_msgs+"&msgs_number="+msgs, handler_delete_msgs);
392                        this.dbGears.execute("delete from msgs_to_remove where folder=? and uid_usuario=?",[folder_to_remove_msgs,account_id]);
393                        this.dbGears.close();
394                       
395                }
396                else {
397                        this.dbGears.close();
398                        document.getElementById('main_title').innerHTML = get_lang("End of archive messages");
399                        if(this.errors.length>0) {
400                                //TODO: Tratar melhor quando existirem erros...
401                                write_msg(get_lang("at least, one of selected mails is already archived, expresso tried to archive the others, check them later"));
402                                this.errors=new Array();
403                        }
404                        window.setTimeout("eval('document.getElementById(\"main_title\").innerHTML =\"Expresso Mail\"')",3000);
405                }
406               
407        }
408       
409        mail_sync.prototype.configure_sync = function(folders,formul) {
410                this.dbGears = google.gears.factory.create('beta.database');
411                this.localServer = google.gears.factory.create('beta.localserver');
412                this.store = this.localServer.createStore('test-store');       
413                this.dbGears.open('database-test');
414                this.dbGears.execute("delete from folders_sync where uid_usuario=?",[account_id]);
415                for (var i=0;i<folders.length;i++) {
416                        var pos = folders[i].value.indexOf("/");
417                        if(pos=="-1")
418                                var folder_name = folders[i].text;
419                        else
420                                var folder_name = folders[i].value.substr(pos+1);
421                        this.dbGears.execute("insert into folders_sync (id_folder,folder_name,uid_usuario) values (?,?,?)",[folders[i].value,folder_name,account_id]);
422                }
423                this.dbGears.close();
424                formul.submit();
425        }
426       
427        mail_sync.prototype.fill_combos_of_folders = function(combo_sync) {
428                var folders = expresso_local_messages.get_folders_to_sync();
429
430                for(var i=0;i<folders.length;i++) {
431                        var option = document.createElement('option');
432                        option.value = folders[i][0];
433                        if (folders[i][1].indexOf("/") != "-1") {
434                                final_pos = folders[i][1].lastIndexOf("/");
435                                option.text =folders[i][1].substr(final_pos+1);
436                        }
437                        else
438                                option.text = folders[i][1];
439                        try {
440                                combo_sync.add(option,null);
441                        }catch (ex) {// I.E
442                                combo_sync.add(option);
443                        }
444
445                }
446        }
447       
448        mail_sync.prototype.add_folder = function (select_sync_folders,select_available_folders)
449        {
450                var count_available_folders = select_available_folders.length;
451                var count_sync_folders = select_sync_folders.options.length;
452                var new_options = '';
453               
454                for (i = 0 ; i < count_available_folders ; i++)
455                {
456                        if (select_available_folders.options[i].selected)
457                        {
458                                if(document.all)
459                                {
460                                        if ( (select_sync_folders.innerHTML.indexOf('value='+select_available_folders.options[i].value)) == '-1' )
461                                        {
462                                                new_options +=  '<option value='
463                                                                        + select_available_folders.options[i].value
464                                                                        + '>'
465                                                                        + select_available_folders.options[i].text
466                                                                        + '</option>';
467                                        }
468                                }
469                                else
470                                {
471                                        if ( (select_sync_folders.innerHTML.indexOf('value="'+select_available_folders.options[i].value+'"')) == '-1' )
472                                        {
473                                                new_options +=  '<option value='
474                                                                        + select_available_folders.options[i].value
475                                                                        + '>'
476                                                                        + select_available_folders.options[i].text
477                                                                        + '</option>';
478                                        }
479                                }
480                        }
481                }
482       
483                if (new_options != '')
484                {
485                        select_sync_folders.innerHTML = '&nbsp;' + new_options + select_sync_folders.innerHTML;
486                        select_sync_folders.outerHTML = select_sync_folders.outerHTML;
487                }
488        }
489       
490        mail_sync.prototype.remove_folder = function(select_sync_folders)
491        {
492                for(var i = 0;i < select_sync_folders.options.length; i++)
493                        if(select_sync_folders.options[i].selected)
494                                select_sync_folders.options[i--] = null;
495        }
496       
497        var expresso_mail_sync;
498        expresso_mail_sync = new mail_sync();
499       
Note: See TracBrowser for help on using the repository browser.