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

Revision 1621, 16.3 KB checked in by eduardoalex, 14 years ago (diff)

Ticket #734 - Resolve problema reportado 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.working=true;
54                this.messages = null;
55                this.attachs = null;
56                this.url_attachs = null;
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                        return;
63                document.getElementById('main_title').innerHTML = get_lang("Creating folders structure");
64                while(rs.isValidRow()) {
65                        var temp = new Array();
66                        temp[0] = rs.field(0);
67                        temp[1] = rs.field(1);
68                        temp[2] = null;
69                        temp[3] = false;
70                        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]);
71                        while(rs2.isValidRow()) {
72                                if(temp[2]==null)
73                                        temp[2]=rs2.field(0)+",";
74                                else
75                                        temp[2]+=rs2.field(0)+",";
76                                rs2.next();
77                        }
78                        this.folders.push(temp);
79                       
80                       
81                        //Criando estrutura de pastas...
82                        var folders_to_check = temp[0].split("/");//Todas as pastas tem ao menos INBOX/
83                        if (folders_to_check.length == 1)
84                                var actual_check = "Inbox";
85                        else {
86                                folders_to_check = folders_to_check.slice(1);
87                                var actual_check = folders_to_check[0];
88                        }
89                        for (var i in folders_to_check) {
90                                var rs2 = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?", [actual_check, account_id]);
91                               
92                                if (!rs2.isValidRow()) {
93                                        this.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)", [actual_check, account_id]);
94                                }
95                                if(parseInt(i)+1<folders_to_check.length)
96                                        actual_check += "/"+folders_to_check[parseInt(i)+1];
97                        }
98                        if (is_ie)
99                                connector.loadScript('TreeShow');
100                        ttreeBox.update_folder();
101                        rs.next();
102                }
103                this.dbGears.close();
104                this.syncronize_folders();
105        }
106       
107        mail_sync.prototype.archive_msgs = function(folder,folder_dest,ids) {
108                //this.main_title = document.getElementById('main_title').innerHTML;
109                var temp = new Array();
110                temp[0] = folder;
111                temp[1] = folder_dest.substr(6);
112                temp[2] = ids;
113                temp[3] = true;
114                this.folders.push(temp);
115                Element('chk_box_select_all_messages').checked = false;
116               
117                array_ids = ids.split(",");
118                for (var i in array_ids) {
119                        if (Element("check_box_message_" + array_ids[i]))
120                                Element("check_box_message_" + array_ids[i]).checked = false;
121                        remove_className(Element(array_ids[i]), 'selected_msg');
122                }
123                if(!this.working) {
124                        this.working=true;
125                        this.syncronize_folders();
126                }
127                else {
128                        write_msg(get_lang("An archiving is in process, but dont worry, expresso will process this messages after the actual archiving"));
129                }
130        }
131       
132        mail_sync.prototype.syncronize_folders = function() {
133                if (this.folders.length == 0) {
134                        document.getElementById('main_title').innerHTML = get_lang("Deleting downloadeds msgs...");
135                        expresso_mail_sync.remove_archived_mails();
136                        this.working=false;
137                        update_menu();
138                        return;
139                }
140                var folder_to_sync = this.folders.pop();
141                folder_to_sync[1] = folder_to_sync[0].toUpperCase()=="INBOX" && !folder_to_sync[3]?"Inbox":folder_to_sync[1];
142               
143                if(folder_to_sync[3]) { //Em caso de arquivamento normal, pode ser que a pasta inbox ainda não tenha sido criada.
144                        expresso_mail_sync.open_conn()
145                        if(!expresso_mail_sync.has_local_mails()) {
146                                expresso_mail_sync.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)",["Inbox",account_id]);
147                        }
148                        expresso_mail_sync.dbGears.close();
149                        ttreeBox.update_folder();
150                       
151                }
152               
153                var start_sync_mails = function(data) {
154                        expresso_mail_sync.messages=data;
155                        if(expresso_mail_sync.is_auto)
156                                document.getElementById('main_title').innerHTML = get_lang("Auto archiving")+" "+lang_folder(folder_to_sync[1])+": 0 / "+data.length;
157                        else
158                                document.getElementById('main_title').innerHTML = get_lang("Archiving messages on folder")+" "+lang_folder(folder_to_sync[1])+": 0 / "+data.length;
159
160                        expresso_mail_sync.syncronize_mails(folder_to_sync[1]);
161                }
162               
163
164                if (folder_to_sync[3]) {
165                        document.getElementById('main_title').innerHTML = get_lang("Starting to archive messages");
166                        cExecute("$this.imap_functions.get_info_msgs&folder=" + folder_to_sync[0] + "&msgs_number=" + folder_to_sync[2], start_sync_mails);
167                        this.is_auto = false;
168                }
169                else {
170                        document.getElementById('main_title').innerHTML = get_lang("Starting to sync folder")+" "+lang_folder(folder_to_sync[1]);
171                        cExecute("$this.imap_functions.msgs_to_archive&folder=" + folder_to_sync[0] + "&mails=" + folder_to_sync[2], start_sync_mails);
172                        this.is_auto = true;
173                }
174                       
175        }
176       
177        mail_sync.prototype.syncronize_mails = function(folder_dest) {
178                if (expresso_mail_sync.messages == null || expresso_mail_sync.messages.length == 0) {
179                        expresso_mail_sync.syncronize_folders();
180                        return;
181                }
182               
183                msg_to_sync = expresso_mail_sync.messages.pop();
184               
185                //refresh loading
186                var value_to_change = document.getElementById('main_title').innerHTML.match(/\d+ \//);
187                value_to_change += "";
188                var new_value = value_to_change.replace(" /","");
189                new_value = parseInt(new_value) + 1;
190                document.getElementById('main_title').innerHTML = document.getElementById('main_title').innerHTML.replace(value_to_change,new_value+" /");
191                msg_to_sync = connector.unserialize(msg_to_sync);
192               
193                var source_msg = new Array();
194                source_msg['url'] = msg_to_sync.url_export_file;
195
196                if (typeof(msg_to_sync['array_attach'])=='object'&&(msg_to_sync['array_attach'] instanceof Array))
197                        expresso_mail_sync.attachs = msg_to_sync['array_attach'].slice();
198                else
199                        expresso_mail_sync.attachs = new Array();
200                expresso_mail_sync.attachs.push(source_msg);
201                expresso_mail_sync.download_attachs(msg_to_sync,folder_dest);
202        }
203       
204        mail_sync.prototype.download_attachs = function(msg,folder_dest) {
205                if (expresso_mail_sync.attachs == null || expresso_mail_sync.attachs.length == 0) {
206                        expresso_mail_sync.insert_mail(msg, folder_dest);
207                       
208                        return;
209                }
210               
211                attach_to_capt = expresso_mail_sync.attachs.pop();
212               
213                var call_back = function(url,success,captureId) {
214                       
215                        if (!success) {
216                                /*
217                                 * 0 - original id
218                                 * 1 - message subject
219                                 * 2 - original folder
220                                 */
221                                var mail_error = new Array();
222                                mail_error[0] = msg.msg_number;
223                                mail_error[1] = msg.subject;
224                                mail_error[2] = msg.msg_folder;
225                                expresso_mail_sync.errors.push(mail_error);
226                                alert('erro ao baixar: '+url);
227                               
228                                /*if (typeof(msg['array_attach']) == 'object' && (msg['array_attach'] instanceof Array)) {
229                                        for (var i in msg['array_attach']) { //remove os anexos que já foram baixados para essa mensagem...
230                                                expresso_mail_sync.store.remove(msg['array_attach'][i]['url']);
231                                        }
232                                }*/
233                                expresso_mail_sync.syncronize_mails(folder_dest); //Pula para o próximo e-mail.
234                        }
235                        else {
236                                expresso_mail_sync.download_attachs(msg, folder_dest);//continua baixando o próximo anexo
237                        }
238                }
239                expresso_mail_sync.store.capture(attach_to_capt['url'],call_back);
240        }
241       
242        mail_sync.prototype.insert_mail = function(msg,folder) {
243                try {
244
245                        expresso_mail_sync.open_conn();
246               
247                        var msg_info = msg;
248                        var msg_header = msg['header'];
249                        var anexos = msg['array_attach'];
250                       
251                       
252                        var unseen = 0;
253                        var login = msg_info.login;
254                        var original_id = msg_info.msg_number;
255                        var original_folder = msg_info.msg_folder=='INBOX/Lixeira/tmpMoveToLocal'?msg_info.msg_folder+(Date.parse(new Date)):msg_info.msg_folder;
256
257                        //Os campos abaixo precisam estar isolados para busca de mensagens em cima deles.
258                        var from = connector.serialize(msg_info.from);
259                        var subject = msg_info.subject;
260                        var body = msg_info.body;
261                        var to = connector.serialize(msg_info.toaddress2);
262                        var cc = connector.serialize(msg_info.cc);
263                        var size = msg_header.Size;
264       
265                        //Zero os campos que foram isolados para não ter informações duplicadas
266                        msg_info.from = null;
267                        msg_info.subject = null;
268                        msg_info.body = null;
269                        msg_info.to = null;
270                        msg_info.cc = null;
271                        msg_header.Size=null;
272                       
273                        //A data no header pode vir como horário ao invés de data, caso o usuário tenha arquivado no mesmo
274                        //dia que recebeu a msg. Para esses casos, usar a data aux que vem com o dia.
275                        if(msg_header.udate.indexOf("/")==-1) {
276                                msg_header.udate = msg_header.aux_date;
277                        }
278               
279                       
280                        /**
281                         * The importance attribute can be empty, and javascript consider as null causing nullpointer.
282                         */
283                        if((msg_header.Importance == null) ||  (msg_header.Importance == ""))
284                                msg_header.Importance = "Normal";
285                       
286                        msg_header.aux_date = null; //esse dado não é mais preciso no email.
287                       
288                        var mail = connector.serialize(msg_info);
289                        var header = connector.serialize(msg_header);
290       
291                        var timestamp = msg_info.timestamp;
292                        var id_folder;
293                       
294                        var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?", [folder, account_id]);
295                        id_folder = rs.field(0);
296       
297                        if(msg_info.Unseen=="U")
298                                unseen = 1;
299                        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]);
300                       
301                       
302                       
303                        //Preenche os anexos.
304                        var id_mail = this.dbGears.lastInsertRowId;
305
306                        for (var i = 0; i < anexos.length; i++) {
307                                this.dbGears.execute("insert into anexo (id_mail,nome_anexo,url,pid) values (?,?,?,?)", [id_mail, anexos[i]['name'],anexos[i]['url'],anexos[i]['pid']]);
308                        }
309                       
310                        var check_remove;
311                        if(this.is_auto)
312                                check_remove = preferences.keep_after_auto_archiving;
313                        else
314                                check_remove = preferences.keep_archived_messages;
315                       
316                       
317                       
318                        if(check_remove!=1)
319                                this.dbGears.execute("insert into msgs_to_remove (id_msg,folder,uid_usuario) values (?,?,?)",[original_id,original_folder,account_id]);
320                                               
321                } catch (error) {
322                        /*
323                         * 0 - original id
324                         * 1 - message subject
325                         * 2 - original folder
326                         */
327                        var mail_error = new Array();
328                        mail_error[0] = original_id;
329                        mail_error[1] = subject;
330                        mail_error[2] = original_folder;
331                        this.errors.push(mail_error);
332                       
333                        if (typeof(msg_info['array_attach'])=='object'&&(msg_info['array_attach'] instanceof Array)) {
334                                for(var i in msg_info['array_attach']) { //remove os anexos que já foram baixados para essa mensagem...
335                                        this.store.remove(msg_info['array_attach'][i]['url']);
336                                }
337                        }
338
339                }
340                this.dbGears.close();
341                this.syncronize_mails(folder);
342        }
343       
344        mail_sync.prototype.has_local_mails = function() {//This function considers that the connection with base is already opened.
345                var rs = this.dbGears.execute("select rowid from folder limit 0,1");
346                if(rs.isValidRow())
347                        return true;
348                else
349                        return false;
350        }
351       
352        mail_sync.prototype.remove_archived_mails = function() {
353               
354                expresso_mail_sync.open_conn();
355
356                var rs = this.dbGears.execute("select distinct(folder) from msgs_to_remove where uid_usuario=?",[account_id]);
357                if(rs.isValidRow()) {
358                        var folder_to_remove_msgs = rs.field(0);
359                        var rs2 = this.dbGears.execute("select id_msg from msgs_to_remove where folder=? and uid_usuario=?",[folder_to_remove_msgs,account_id]);
360                       
361                        var msgs = null;
362                        while(rs2.isValidRow()) {
363                                if(msgs==null)
364                                        msgs = rs2.field(0);
365                                else
366                                        msgs += ","+rs2.field(0);
367                                rs2.next();
368                        }
369                       
370                       
371                        var handler_delete_msgs = function(data){
372                                if (current_folder == data.folder) {
373                                        mail_msg = Element("tbody_box");
374                                        var msg_to_delete;
375                                        for (var i = 0; i < data.msgs_number.length; i++) {
376                                                msg_to_delete = Element(data.msgs_number[i]);
377                                                if (msg_to_delete) {
378                                                        mail_msg.removeChild(msg_to_delete);
379                                                }
380                                        }
381                                        Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) - data.msgs_number.length;
382                                }
383                                ttreeBox.update_folder();
384                                refresh();
385                                expresso_mail_sync.remove_archived_mails();
386                        }
387                       
388                        cExecute ("$this.imap_functions.delete_msgs&folder="+folder_to_remove_msgs+"&msgs_number="+msgs, handler_delete_msgs);
389                        this.dbGears.execute("delete from msgs_to_remove where folder=? and uid_usuario=?",[folder_to_remove_msgs,account_id]);
390                        this.dbGears.close();
391                       
392                }
393                else {
394                        this.dbGears.close();
395                        document.getElementById('main_title').innerHTML = get_lang("End of archive messages");
396                        if(this.errors.length>0) {
397                                //TODO: Tratar melhor quando existirem erros...
398                                write_msg(get_lang("at least, one of selected mails is already archived, expresso tried to archive the others, check them later"));
399                                this.errors=new Array();
400                        }
401                        window.setTimeout("eval('document.getElementById(\"main_title\").innerHTML =\"Expresso Mail\"')",3000);
402                }
403               
404        }
405       
406        mail_sync.prototype.configure_sync = function(folders,formul) {
407                this.dbGears = google.gears.factory.create('beta.database');
408                this.localServer = google.gears.factory.create('beta.localserver');
409                this.store = this.localServer.createStore('test-store');       
410                this.dbGears.open('database-test');
411                this.dbGears.execute("delete from folders_sync where uid_usuario=?",[account_id]);
412                for (var i=0;i<folders.length;i++) {
413                        var pos = folders[i].value.indexOf("/");
414                        if(pos=="-1")
415                                var folder_name = folders[i].text;
416                        else
417                                var folder_name = folders[i].value.substr(pos+1);
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.