source: branches/2.2/expressoMail1_2/js/mail_sync.js @ 3345

Revision 3345, 16.2 KB checked in by eduardoalex, 14 years ago (diff)

Ticket #1229 - Correcao do erro narrado no ticket em questão

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