source: sandbox/2.4.2-expresso2/expressoMail1_2/js/mail_sync.js @ 5134

Revision 5134, 17.2 KB checked in by wmerlotto, 12 years ago (diff)

Ticket #2305 - Enviando alteracoes, desenvolvidas internamente na Prognus, do modulo ExpressoMail?.

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