id
int64
22
34.9k
comment_id
int64
0
328
comment
stringlengths
2
2.55k
code
stringlengths
31
107k
classification
stringclasses
6 values
isFinished
bool
1 class
code_context_2
stringlengths
21
27.3k
code_context_10
stringlengths
29
27.3k
code_context_20
stringlengths
29
27.3k
32,069
14
//export the current database to a Database_Exported.csv file,which opens in MS Excel
private void init() throws Exception { loadDB();//deserialize the database outer: while (true) { //show options System.out.println("Main menu:"); System.out.println("1:Start Parsing\n2:Start Browsing\n3:Start Configuration System\n4:Export Current Database\n5:Import a database\n6:Exit"); switch (Integer.parseInt(br.readLine())) { case 1://start the parser BufferedReader br2 = new BufferedReader(new FileReader(FILES[2])); String s = br2.readLine(); while (s != null) { ar.add(s);//read the options in the parser configuration file s = br2.readLine(); } Codes.fixInput(ar);//same as before Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
NONSATD
true
ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu
Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances
System.out.println("1:Start Parsing\n2:Start Browsing\n3:Start Configuration System\n4:Export Current Database\n5:Import a database\n6:Exit"); switch (Integer.parseInt(br.readLine())) { case 1://start the parser BufferedReader br2 = new BufferedReader(new FileReader(FILES[2])); String s = br2.readLine(); while (s != null) { ar.add(s);//read the options in the parser configuration file s = br2.readLine(); } Codes.fixInput(ar);//same as before Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
32,069
15
//initializing the export system and handing over control to it!
private void init() throws Exception { loadDB();//deserialize the database outer: while (true) { //show options System.out.println("Main menu:"); System.out.println("1:Start Parsing\n2:Start Browsing\n3:Start Configuration System\n4:Export Current Database\n5:Import a database\n6:Exit"); switch (Integer.parseInt(br.readLine())) { case 1://start the parser BufferedReader br2 = new BufferedReader(new FileReader(FILES[2])); String s = br2.readLine(); while (s != null) { ar.add(s);//read the options in the parser configuration file s = br2.readLine(); } Codes.fixInput(ar);//same as before Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
NONSATD
true
break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?)
p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances }
switch (Integer.parseInt(br.readLine())) { case 1://start the parser BufferedReader br2 = new BufferedReader(new FileReader(FILES[2])); String s = br2.readLine(); while (s != null) { ar.add(s);//read the options in the parser configuration file s = br2.readLine(); } Codes.fixInput(ar);//same as before Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
32,069
16
//we can come back to the main menu
private void init() throws Exception { loadDB();//deserialize the database outer: while (true) { //show options System.out.println("Main menu:"); System.out.println("1:Start Parsing\n2:Start Browsing\n3:Start Configuration System\n4:Export Current Database\n5:Import a database\n6:Exit"); switch (Integer.parseInt(br.readLine())) { case 1://start the parser BufferedReader br2 = new BufferedReader(new FileReader(FILES[2])); String s = br2.readLine(); while (s != null) { ar.add(s);//read the options in the parser configuration file s = br2.readLine(); } Codes.fixInput(ar);//same as before Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
NONSATD
true
case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system
break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } }
case 1://start the parser BufferedReader br2 = new BufferedReader(new FileReader(FILES[2])); String s = br2.readLine(); while (s != null) { ar.add(s);//read the options in the parser configuration file s = br2.readLine(); } Codes.fixInput(ar);//same as before Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
32,069
17
//import an existing exported database(using this program on a different computer?)
private void init() throws Exception { loadDB();//deserialize the database outer: while (true) { //show options System.out.println("Main menu:"); System.out.println("1:Start Parsing\n2:Start Browsing\n3:Start Configuration System\n4:Export Current Database\n5:Import a database\n6:Exit"); switch (Integer.parseInt(br.readLine())) { case 1://start the parser BufferedReader br2 = new BufferedReader(new FileReader(FILES[2])); String s = br2.readLine(); while (s != null) { ar.add(s);//read the options in the parser configuration file s = br2.readLine(); } Codes.fixInput(ar);//same as before Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
NONSATD
true
new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4
case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
BufferedReader br2 = new BufferedReader(new FileReader(FILES[2])); String s = br2.readLine(); while (s != null) { ar.add(s);//read the options in the parser configuration file s = br2.readLine(); } Codes.fixInput(ar);//same as before Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
32,069
18
//now it's the import system
private void init() throws Exception { loadDB();//deserialize the database outer: while (true) { //show options System.out.println("Main menu:"); System.out.println("1:Start Parsing\n2:Start Browsing\n3:Start Configuration System\n4:Export Current Database\n5:Import a database\n6:Exit"); switch (Integer.parseInt(br.readLine())) { case 1://start the parser BufferedReader br2 = new BufferedReader(new FileReader(FILES[2])); String s = br2.readLine(); while (s != null) { ar.add(s);//read the options in the parser configuration file s = br2.readLine(); } Codes.fixInput(ar);//same as before Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
NONSATD
true
break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?)
Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
String s = br2.readLine(); while (s != null) { ar.add(s);//read the options in the parser configuration file s = br2.readLine(); } Codes.fixInput(ar);//same as before Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
32,069
19
//same as case 4
private void init() throws Exception { loadDB();//deserialize the database outer: while (true) { //show options System.out.println("Main menu:"); System.out.println("1:Start Parsing\n2:Start Browsing\n3:Start Configuration System\n4:Export Current Database\n5:Import a database\n6:Exit"); switch (Integer.parseInt(br.readLine())) { case 1://start the parser BufferedReader br2 = new BufferedReader(new FileReader(FILES[2])); String s = br2.readLine(); while (s != null) { ar.add(s);//read the options in the parser configuration file s = br2.readLine(); } Codes.fixInput(ar);//same as before Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
NONSATD
true
case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting...");
e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
while (s != null) { ar.add(s);//read the options in the parser configuration file s = br2.readLine(); } Codes.fixInput(ar);//same as before Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
32,069
20
//No!!! Don't leave me behind!(Can't do anything about it anyway, can I?)
private void init() throws Exception { loadDB();//deserialize the database outer: while (true) { //show options System.out.println("Main menu:"); System.out.println("1:Start Parsing\n2:Start Browsing\n3:Start Configuration System\n4:Export Current Database\n5:Import a database\n6:Exit"); switch (Integer.parseInt(br.readLine())) { case 1://start the parser BufferedReader br2 = new BufferedReader(new FileReader(FILES[2])); String s = br2.readLine(); while (s != null) { ar.add(s);//read the options in the parser configuration file s = br2.readLine(); } Codes.fixInput(ar);//same as before Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
NONSATD
true
new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye
break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
ar.add(s);//read the options in the parser configuration file s = br2.readLine(); } Codes.fixInput(ar);//same as before Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
32,069
21
//Bye-Bye
private void init() throws Exception { loadDB();//deserialize the database outer: while (true) { //show options System.out.println("Main menu:"); System.out.println("1:Start Parsing\n2:Start Browsing\n3:Start Configuration System\n4:Export Current Database\n5:Import a database\n6:Exit"); switch (Integer.parseInt(br.readLine())) { case 1://start the parser BufferedReader br2 = new BufferedReader(new FileReader(FILES[2])); String s = br2.readLine(); while (s != null) { ar.add(s);//read the options in the parser configuration file s = br2.readLine(); } Codes.fixInput(ar);//same as before Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
NONSATD
true
case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances
ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
} Codes.fixInput(ar);//same as before Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
32,069
22
//Stop making mistakes in input!
private void init() throws Exception { loadDB();//deserialize the database outer: while (true) { //show options System.out.println("Main menu:"); System.out.println("1:Start Parsing\n2:Start Browsing\n3:Start Configuration System\n4:Export Current Database\n5:Import a database\n6:Exit"); switch (Integer.parseInt(br.readLine())) { case 1://start the parser BufferedReader br2 = new BufferedReader(new FileReader(FILES[2])); String s = br2.readLine(); while (s != null) { ar.add(s);//read the options in the parser configuration file s = br2.readLine(); } Codes.fixInput(ar);//same as before Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
NONSATD
true
System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances }
break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
Codes.fixInput(ar);//same as before Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
32,069
23
//I'm very considerate, I give everybody infinite chances
private void init() throws Exception { loadDB();//deserialize the database outer: while (true) { //show options System.out.println("Main menu:"); System.out.println("1:Start Parsing\n2:Start Browsing\n3:Start Configuration System\n4:Export Current Database\n5:Import a database\n6:Exit"); switch (Integer.parseInt(br.readLine())) { case 1://start the parser BufferedReader br2 = new BufferedReader(new FileReader(FILES[2])); String s = br2.readLine(); while (s != null) { ar.add(s);//read the options in the parser configuration file s = br2.readLine(); } Codes.fixInput(ar);//same as before Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
NONSATD
true
System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } }
case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
Parser p = new Parser(db, ar.toArray(new String[ar.size()]), status);//initializing the database parser p.parse();//handing control to the parser break; case 2://start the editor Editor e = new Editor(db, auto_entry);//initializing the editor e.browse(); break;//the editor is capable of returning to the main menu case 3://configure everything again? ConfigCLI.init();//configuration system is self-initialising, just hand over control to it break outer;//that's all, after configuration, the program needs to be restarted anyway case 4://export the current database to a Database_Exported.csv file,which opens in MS Excel new ExportImport().exporter(db, auto_entry);//initializing the export system and handing over control to it! break;//we can come back to the main menu case 5://import an existing exported database(using this program on a different computer?) new ExportImport().importer(db, auto_entry);//now it's the import system break;//same as case 4 case 6://No!!! Don't leave me behind!(Can't do anything about it anyway, can I?) System.out.println("Exiting..."); System.exit(0);//Bye-Bye default://Stop making mistakes in input! //I'm very considerate, I give everybody infinite chances } } }
23,877
0
// TODO: Manage sizes to avoid specific ones. It always must be parent size (match_parent)
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO: Manage sizes to avoid specific ones. It always must be parent size (match_parent) int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); mWidth.set(widthSize); mHeight.set(heightSize); mQuadrangle.set(0, 0, widthSize, heightSize); super.onMeasure(widthMeasureSpec, heightMeasureSpec); }
IMPLEMENTATION
true
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO: Manage sizes to avoid specific ones. It always must be parent size (match_parent) int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec);
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO: Manage sizes to avoid specific ones. It always must be parent size (match_parent) int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); mWidth.set(widthSize); mHeight.set(heightSize); mQuadrangle.set(0, 0, widthSize, heightSize); super.onMeasure(widthMeasureSpec, heightMeasureSpec); }
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO: Manage sizes to avoid specific ones. It always must be parent size (match_parent) int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); mWidth.set(widthSize); mHeight.set(heightSize); mQuadrangle.set(0, 0, widthSize, heightSize); super.onMeasure(widthMeasureSpec, heightMeasureSpec); }
32,072
0
// TODO: WHAT HAPPENS IF FINAL COUNT IS 63 AND WE SMELT DOUBLE?
private void craftRecipe( Recipe<?> currentRecipe) { if (currentRecipe != null && this.canAcceptRecipeOutput(currentRecipe)) { ItemStack inputStack = this.inventory.get(0); ItemStack outputStack = this.inventory.get(2); ItemStack recipeResultStack = currentRecipe.getOutput(); int resultCount = world.random.nextInt(100) < dupeChance100 ? 2 : 1; if (outputStack.isEmpty()) { ItemStack newResultStack = recipeResultStack.copy(); newResultStack.setAmount(resultCount); this.inventory.set(2, newResultStack); } else if (outputStack.getItem() == recipeResultStack.getItem()) { // TODO: WHAT HAPPENS IF FINAL COUNT IS 63 AND WE SMELT DOUBLE? outputStack.addAmount(resultCount); } if (!this.world.isClient) this.setLastRecipe(currentRecipe); if (inputStack.getItem() == Blocks.WET_SPONGE.getItem() && !((ItemStack) this.inventory.get(1)).isEmpty() && ((ItemStack) this.inventory.get(1)).getItem() == Items.BUCKET) { this.inventory.set(1, new ItemStack(Items.WATER_BUCKET)); } inputStack.subtractAmount(1); } }
DESIGN
true
else if (outputStack.getItem() == recipeResultStack.getItem()) { // TODO: WHAT HAPPENS IF FINAL COUNT IS 63 AND WE SMELT DOUBLE? outputStack.addAmount(resultCount); }
ItemStack recipeResultStack = currentRecipe.getOutput(); int resultCount = world.random.nextInt(100) < dupeChance100 ? 2 : 1; if (outputStack.isEmpty()) { ItemStack newResultStack = recipeResultStack.copy(); newResultStack.setAmount(resultCount); this.inventory.set(2, newResultStack); } else if (outputStack.getItem() == recipeResultStack.getItem()) { // TODO: WHAT HAPPENS IF FINAL COUNT IS 63 AND WE SMELT DOUBLE? outputStack.addAmount(resultCount); } if (!this.world.isClient) this.setLastRecipe(currentRecipe); if (inputStack.getItem() == Blocks.WET_SPONGE.getItem() && !((ItemStack) this.inventory.get(1)).isEmpty() && ((ItemStack) this.inventory.get(1)).getItem() == Items.BUCKET) { this.inventory.set(1, new ItemStack(Items.WATER_BUCKET)); } inputStack.subtractAmount(1); }
private void craftRecipe( Recipe<?> currentRecipe) { if (currentRecipe != null && this.canAcceptRecipeOutput(currentRecipe)) { ItemStack inputStack = this.inventory.get(0); ItemStack outputStack = this.inventory.get(2); ItemStack recipeResultStack = currentRecipe.getOutput(); int resultCount = world.random.nextInt(100) < dupeChance100 ? 2 : 1; if (outputStack.isEmpty()) { ItemStack newResultStack = recipeResultStack.copy(); newResultStack.setAmount(resultCount); this.inventory.set(2, newResultStack); } else if (outputStack.getItem() == recipeResultStack.getItem()) { // TODO: WHAT HAPPENS IF FINAL COUNT IS 63 AND WE SMELT DOUBLE? outputStack.addAmount(resultCount); } if (!this.world.isClient) this.setLastRecipe(currentRecipe); if (inputStack.getItem() == Blocks.WET_SPONGE.getItem() && !((ItemStack) this.inventory.get(1)).isEmpty() && ((ItemStack) this.inventory.get(1)).getItem() == Items.BUCKET) { this.inventory.set(1, new ItemStack(Items.WATER_BUCKET)); } inputStack.subtractAmount(1); } }
15,691
0
/** * Test to see if the subject is empty. * * @return boolean. */ // TODO: this will likely go away when composeArea.focus() is implemented // after all the widget control is moved over.
public boolean isSubjectEmpty() { return TextUtils.getTrimmedLength(mSubject.getText()) == 0; }
DESIGN
true
public boolean isSubjectEmpty() { return TextUtils.getTrimmedLength(mSubject.getText()) == 0; }
public boolean isSubjectEmpty() { return TextUtils.getTrimmedLength(mSubject.getText()) == 0; }
public boolean isSubjectEmpty() { return TextUtils.getTrimmedLength(mSubject.getText()) == 0; }
23,891
0
// TODO: Error.
public void buildOutAssignment(StringBuilder sb, PLSQLargument outArg, PLSQLStoredProcedureCall call) { String sql2PlName = call.getPl2SQLName(this); if (sql2PlName == null) { // TODO: Error. throw new NullPointerException("no Pl2SQL conversion routine for " + typeName); } String target = databaseTypeHelper.buildTarget(outArg); sb.append(" :"); sb.append(outArg.outIndex); sb.append(" := "); sb.append(sql2PlName); sb.append("("); sb.append(target); sb.append(");"); sb.append(NL); }
DEFECT
true
String sql2PlName = call.getPl2SQLName(this); if (sql2PlName == null) { // TODO: Error. throw new NullPointerException("no Pl2SQL conversion routine for " + typeName); }
public void buildOutAssignment(StringBuilder sb, PLSQLargument outArg, PLSQLStoredProcedureCall call) { String sql2PlName = call.getPl2SQLName(this); if (sql2PlName == null) { // TODO: Error. throw new NullPointerException("no Pl2SQL conversion routine for " + typeName); } String target = databaseTypeHelper.buildTarget(outArg); sb.append(" :"); sb.append(outArg.outIndex); sb.append(" := "); sb.append(sql2PlName); sb.append("("); sb.append(target); sb.append(");");
public void buildOutAssignment(StringBuilder sb, PLSQLargument outArg, PLSQLStoredProcedureCall call) { String sql2PlName = call.getPl2SQLName(this); if (sql2PlName == null) { // TODO: Error. throw new NullPointerException("no Pl2SQL conversion routine for " + typeName); } String target = databaseTypeHelper.buildTarget(outArg); sb.append(" :"); sb.append(outArg.outIndex); sb.append(" := "); sb.append(sql2PlName); sb.append("("); sb.append(target); sb.append(");"); sb.append(NL); }
15,703
0
/** * Generic synchronizer - used for POP3 and IMAP. * * TODO Break this method up into smaller chunks. * * @param account the account to sync * @param folder the mailbox to sync * @return results of the sync pass * @throws MessagingException */
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
15,703
1
// 0. We do not ever sync DRAFTS or OUTBOX (down or up)
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null);
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI,
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor);
15,703
2
// 1. Get the message list from the local store and create an index of the uids
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>();
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId),
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close();
15,703
3
// 1a. Count the unread messages before changing anything
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
} } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null);
try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) {
15,703
4
// 2. Open the remote folder and create the remote folder if necessary
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName);
} // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT
}, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally.
15,703
5
/* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) {
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null);
LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault;
15,703
6
// 3, Open the remote folder. This pre-loads certain metadata like message count.
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
} } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally.
* to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext);
String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1.
15,703
7
// 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count.
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
IMPLEMENTATION
true
// 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download
if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0];
// 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null);
15,703
8
// 6. Determine the limit # of messages to download
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
// 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) {
return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
* If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message);
15,703
9
// 7. Create a list of messages to download
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
// TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount;
|| folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from
15,703
10
/* * Message numbers start at 1. */
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); }
LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit;
15,703
11
/* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) {
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally.
LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; }
15,703
12
// localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) {
* on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to
*/ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS);
15,703
13
// 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
} } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /*
// mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy =
* because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null;
15,703
14
/* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code.
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } }
LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) {
15,703
15
// Determine if the new message was already known (e.g. partial) // And create or reload the full message info
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid());
if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) {
/* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); }
15,703
16
// Copy the fields that are available into the message
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId);
localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG,
fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } });
15,703
17
// Commit the message to the local store
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message
localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } }
remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile();
15,703
18
// Track the "new" ness of the downloaded message
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
// Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message);
localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) {
public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null);
15,703
19
// 9. Refresh the flags for any messages in the local store that we didn't just download.
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
}); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS);
} } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) {
message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; }
15,703
20
// Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3)
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
} } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) {
boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite;
Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); }
15,703
21
// 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store.
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
} } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet());
if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId);
LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size)
15,703
22
// Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself
// } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId(
// * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>();
15,703
23
// Delete the message itself
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
// Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId);
// updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null);
// remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) {
15,703
24
// Delete extra rows (e.g. synced or deleted)
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId);
localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much
// * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message);
15,703
25
// 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet....
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
DEFECT
true
resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>();
EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages
// 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded
15,703
26
// 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments)
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
DESIGN
true
} } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY);
// (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } });
resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download.
15,703
27
// Store the updated message locally and mark it fully loaded
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE);
// 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) {
// (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null);
15,703
28
// 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments.
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
} }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE);
fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE);
largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store.
15,703
29
// POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download.
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE);
EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else {
// this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear();
15,703
30
// TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
DESIGN
true
fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded
fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>();
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); }
15,703
31
// Store the partially-loaded message and mark it partially loaded
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
// they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL);
if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments);
copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder,
15,703
32
// We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later.
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>();
fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null);
// 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done.
15,703
33
// Download the viewables immediately
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear();
copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE);
// POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */
15,703
34
// TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored.
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
DEFECT
true
fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); }
// we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more
fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) {
15,703
35
// Store the updated message locally and mark it fully loaded
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE);
// 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) {
// (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null);
15,703
36
// 15. Clean up and report results
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
} } // 15. Clean up and report results remoteFolder.close(false); // TODO - more
fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]),
// We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear();
15,703
37
// TODO - more // Original sync code. Using for reference, will delete when done.
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
// 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /*
// messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) {
// Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set
15,703
38
/* * Now do the large messages that require more round trips. */
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); }
LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit;
15,703
39
/* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count.
LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext);
15,703
40
/* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
DESIGN
true
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } }
LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext),
15,703
41
// Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
// 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set
// (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded
15,703
42
/* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count.
LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext);
15,703
43
/* * Now download the parts we're interested in storing. */
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); }
LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit;
15,703
44
// TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored.
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
DEFECT
true
fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); }
// we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more
fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) {
15,703
45
// Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
// 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set
// (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded
15,703
46
// Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // }
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
// localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /*
} // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; }
MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
15,703
47
/* * Report successful sync */
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); }
LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit;
15,703
48
// localFolder.close(false);
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageRetrieved(Message message) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
NONSATD
true
remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; }
// localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
// Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
15,705
0
/** * Process a pending trash message command. * * @param remoteStore the remote store we're working in * @param account The account in which we are working * @param newMailbox The local trash mailbox * @param oldMessage The message copy that was saved in the updates shadow table * @param newMessage The message that was moved to the mailbox */
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
15,705
1
// 0. No remote move if the message is local-only
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) {
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return;
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code
15,705
2
// 1. Escape early if we can't find the local mailbox // TODO smaller projection here
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
IMPLEMENTATION
true
return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) {
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED;
15,705
3
// can't find old mailbox, it may have been deleted. just return.
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; }
final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext);
15,705
4
// 2. We don't support delete-from-trash here
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return;
|| newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) {
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion
15,705
5
// 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us.
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message();
// TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; }
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return;
15,705
6
// The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) {
if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message
// 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it.
15,705
7
// 5. Find the remote original message
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) {
// 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it.
EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null);
15,705
8
// 6. Find the remote trash folder, and create it if not found
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) {
if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) {
sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder,
15,705
9
/* * If the remote trash folder doesn't exist we try to create it. */
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); }
} // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) {
// The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues();
15,705
10
// 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /*
return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; }
} remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /**
15,705
11
/* * Because remoteTrashFolder may be new, we need to explicitly open it */
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); }
} // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) {
// The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues();
15,705
12
// update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid);
*/ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) {
/* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false);
15,705
13
/** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null);
} remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge();
// Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
15,705
14
// 8. Delete the message from the remote source folder
private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
NONSATD
true
remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge();
* deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); }
32,092
0
/* consider doing this in the tosca yaml parser */
private boolean validParameters(List<String> parameters) { // TODO: throw a parsing error exception on the YAML parser when params size is less than 2. return CollectionUtils.isNotEmpty(parameters) && parameters.size() >= 2; }
NONSATD
true
private boolean validParameters(List<String> parameters) { // TODO: throw a parsing error exception on the YAML parser when params size is less than 2. return CollectionUtils.isNotEmpty(parameters) && parameters.size() >= 2; }
private boolean validParameters(List<String> parameters) { // TODO: throw a parsing error exception on the YAML parser when params size is less than 2. return CollectionUtils.isNotEmpty(parameters) && parameters.size() >= 2; }
private boolean validParameters(List<String> parameters) { // TODO: throw a parsing error exception on the YAML parser when params size is less than 2. return CollectionUtils.isNotEmpty(parameters) && parameters.size() >= 2; }
32,092
1
// TODO: throw a parsing error exception on the YAML parser when params size is less than 2.
private boolean validParameters(List<String> parameters) { // TODO: throw a parsing error exception on the YAML parser when params size is less than 2. return CollectionUtils.isNotEmpty(parameters) && parameters.size() >= 2; }
IMPLEMENTATION
true
private boolean validParameters(List<String> parameters) { // TODO: throw a parsing error exception on the YAML parser when params size is less than 2. return CollectionUtils.isNotEmpty(parameters) && parameters.size() >= 2; }
private boolean validParameters(List<String> parameters) { // TODO: throw a parsing error exception on the YAML parser when params size is less than 2. return CollectionUtils.isNotEmpty(parameters) && parameters.size() >= 2; }
private boolean validParameters(List<String> parameters) { // TODO: throw a parsing error exception on the YAML parser when params size is less than 2. return CollectionUtils.isNotEmpty(parameters) && parameters.size() >= 2; }
23,901
0
//GEN-FIRST:event_guestSearchActionPerformed
private void guestSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guestSearchActionPerformed // TODO add your handling code here: //Guestsearch guestsearch = new Guestsearch(jFrameInstance, email); //jFrameInstance.changePanelToSpecific(guestsearch); }
NONSATD
true
private void guestSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guestSearchActionPerformed // TODO add your handling code here: //Guestsearch guestsearch = new Guestsearch(jFrameInstance, email);
private void guestSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guestSearchActionPerformed // TODO add your handling code here: //Guestsearch guestsearch = new Guestsearch(jFrameInstance, email); //jFrameInstance.changePanelToSpecific(guestsearch); }
private void guestSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guestSearchActionPerformed // TODO add your handling code here: //Guestsearch guestsearch = new Guestsearch(jFrameInstance, email); //jFrameInstance.changePanelToSpecific(guestsearch); }
23,901
1
// TODO add your handling code here: //Guestsearch guestsearch = new Guestsearch(jFrameInstance, email); //jFrameInstance.changePanelToSpecific(guestsearch);
private void guestSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guestSearchActionPerformed // TODO add your handling code here: //Guestsearch guestsearch = new Guestsearch(jFrameInstance, email); //jFrameInstance.changePanelToSpecific(guestsearch); }
IMPLEMENTATION
true
private void guestSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guestSearchActionPerformed // TODO add your handling code here: //Guestsearch guestsearch = new Guestsearch(jFrameInstance, email); //jFrameInstance.changePanelToSpecific(guestsearch); }
private void guestSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guestSearchActionPerformed // TODO add your handling code here: //Guestsearch guestsearch = new Guestsearch(jFrameInstance, email); //jFrameInstance.changePanelToSpecific(guestsearch); }
private void guestSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guestSearchActionPerformed // TODO add your handling code here: //Guestsearch guestsearch = new Guestsearch(jFrameInstance, email); //jFrameInstance.changePanelToSpecific(guestsearch); }
32,099
0
/** * Creates the rectangles that contain matched characters in the given text. * <p> * TODO: Improve partial clipped matches: If one of the matched characters * is clipped, the remaining characters lose their highlight; just the * ellipsis is highlighted. * </p> * * @param fullText * useful for highlighting if matches exist in clipped text and * in the ellipsis * @param clippedText * the clipped text to search (could be the same as fullText) * @param fm * the font metrics of the rendered font * @param xOffset * the x offset at which text rendering starts * @param yOffset * the y offset at which text rendering starts (e.g. different * rowHeights) * @param height * the height of painted highlights * @return a <code>List</code> of highlight areas to paint */
protected List<Rectangle> createHighlightAreas2(String fullText, String clippedText, FontMetrics fm, int xOffset, int yOffset, int height) { if (matchPattern == null) { return Collections.emptyList(); } Matcher matcher = matchPattern.matcher(clippedText); List<Rectangle> highlightAreas = null; int startFrom = 0; while (startFrom < clippedText.length() && matcher.find(startFrom)) { if (highlightAreas == null) { highlightAreas = new ArrayList<Rectangle>(); } int start = matcher.start(); int end = matcher.end(); if (start == end) { // empty matcher will cause infinite loop break; } startFrom = end; int highlightx; int highlightWidth; if (start == 0) { // start highlight from the start of the field highlightx = xOffset; } else { // Calculate the width of the unhighlighted text to get the // start of the highlighted region. String strToStart = clippedText.substring(0, start); highlightx = fm.stringWidth(strToStart) + xOffset; } // Get the width of the highlighted region String highlightText = clippedText.substring(start, end); highlightWidth = fm.stringWidth(highlightText); highlightAreas.add(new Rectangle(highlightx, yOffset, highlightWidth, height)); }// while ( startFrom < text.length() && matcher.find( startFrom ) ) if (highlightAreas == null) { highlightAreas = Collections.emptyList(); } else { coalesceHighlightAreas(highlightAreas); } return highlightAreas; }
DESIGN
true
protected List<Rectangle> createHighlightAreas2(String fullText, String clippedText, FontMetrics fm, int xOffset, int yOffset, int height) { if (matchPattern == null) { return Collections.emptyList(); } Matcher matcher = matchPattern.matcher(clippedText); List<Rectangle> highlightAreas = null; int startFrom = 0; while (startFrom < clippedText.length() && matcher.find(startFrom)) { if (highlightAreas == null) { highlightAreas = new ArrayList<Rectangle>(); } int start = matcher.start(); int end = matcher.end(); if (start == end) { // empty matcher will cause infinite loop break; } startFrom = end; int highlightx; int highlightWidth; if (start == 0) { // start highlight from the start of the field highlightx = xOffset; } else { // Calculate the width of the unhighlighted text to get the // start of the highlighted region. String strToStart = clippedText.substring(0, start); highlightx = fm.stringWidth(strToStart) + xOffset; } // Get the width of the highlighted region String highlightText = clippedText.substring(start, end); highlightWidth = fm.stringWidth(highlightText); highlightAreas.add(new Rectangle(highlightx, yOffset, highlightWidth, height)); }// while ( startFrom < text.length() && matcher.find( startFrom ) ) if (highlightAreas == null) { highlightAreas = Collections.emptyList(); } else { coalesceHighlightAreas(highlightAreas); } return highlightAreas; }
protected List<Rectangle> createHighlightAreas2(String fullText, String clippedText, FontMetrics fm, int xOffset, int yOffset, int height) { if (matchPattern == null) { return Collections.emptyList(); } Matcher matcher = matchPattern.matcher(clippedText); List<Rectangle> highlightAreas = null; int startFrom = 0; while (startFrom < clippedText.length() && matcher.find(startFrom)) { if (highlightAreas == null) { highlightAreas = new ArrayList<Rectangle>(); } int start = matcher.start(); int end = matcher.end(); if (start == end) { // empty matcher will cause infinite loop break; } startFrom = end; int highlightx; int highlightWidth; if (start == 0) { // start highlight from the start of the field highlightx = xOffset; } else { // Calculate the width of the unhighlighted text to get the // start of the highlighted region. String strToStart = clippedText.substring(0, start); highlightx = fm.stringWidth(strToStart) + xOffset; } // Get the width of the highlighted region String highlightText = clippedText.substring(start, end); highlightWidth = fm.stringWidth(highlightText); highlightAreas.add(new Rectangle(highlightx, yOffset, highlightWidth, height)); }// while ( startFrom < text.length() && matcher.find( startFrom ) ) if (highlightAreas == null) { highlightAreas = Collections.emptyList(); } else { coalesceHighlightAreas(highlightAreas); } return highlightAreas; }
protected List<Rectangle> createHighlightAreas2(String fullText, String clippedText, FontMetrics fm, int xOffset, int yOffset, int height) { if (matchPattern == null) { return Collections.emptyList(); } Matcher matcher = matchPattern.matcher(clippedText); List<Rectangle> highlightAreas = null; int startFrom = 0; while (startFrom < clippedText.length() && matcher.find(startFrom)) { if (highlightAreas == null) { highlightAreas = new ArrayList<Rectangle>(); } int start = matcher.start(); int end = matcher.end(); if (start == end) { // empty matcher will cause infinite loop break; } startFrom = end; int highlightx; int highlightWidth; if (start == 0) { // start highlight from the start of the field highlightx = xOffset; } else { // Calculate the width of the unhighlighted text to get the // start of the highlighted region. String strToStart = clippedText.substring(0, start); highlightx = fm.stringWidth(strToStart) + xOffset; } // Get the width of the highlighted region String highlightText = clippedText.substring(start, end); highlightWidth = fm.stringWidth(highlightText); highlightAreas.add(new Rectangle(highlightx, yOffset, highlightWidth, height)); }// while ( startFrom < text.length() && matcher.find( startFrom ) ) if (highlightAreas == null) { highlightAreas = Collections.emptyList(); } else { coalesceHighlightAreas(highlightAreas); } return highlightAreas; }
32,099
1
// empty matcher will cause infinite loop
protected List<Rectangle> createHighlightAreas2(String fullText, String clippedText, FontMetrics fm, int xOffset, int yOffset, int height) { if (matchPattern == null) { return Collections.emptyList(); } Matcher matcher = matchPattern.matcher(clippedText); List<Rectangle> highlightAreas = null; int startFrom = 0; while (startFrom < clippedText.length() && matcher.find(startFrom)) { if (highlightAreas == null) { highlightAreas = new ArrayList<Rectangle>(); } int start = matcher.start(); int end = matcher.end(); if (start == end) { // empty matcher will cause infinite loop break; } startFrom = end; int highlightx; int highlightWidth; if (start == 0) { // start highlight from the start of the field highlightx = xOffset; } else { // Calculate the width of the unhighlighted text to get the // start of the highlighted region. String strToStart = clippedText.substring(0, start); highlightx = fm.stringWidth(strToStart) + xOffset; } // Get the width of the highlighted region String highlightText = clippedText.substring(start, end); highlightWidth = fm.stringWidth(highlightText); highlightAreas.add(new Rectangle(highlightx, yOffset, highlightWidth, height)); }// while ( startFrom < text.length() && matcher.find( startFrom ) ) if (highlightAreas == null) { highlightAreas = Collections.emptyList(); } else { coalesceHighlightAreas(highlightAreas); } return highlightAreas; }
NONSATD
true
int end = matcher.end(); if (start == end) { // empty matcher will cause infinite loop break; }
Matcher matcher = matchPattern.matcher(clippedText); List<Rectangle> highlightAreas = null; int startFrom = 0; while (startFrom < clippedText.length() && matcher.find(startFrom)) { if (highlightAreas == null) { highlightAreas = new ArrayList<Rectangle>(); } int start = matcher.start(); int end = matcher.end(); if (start == end) { // empty matcher will cause infinite loop break; } startFrom = end; int highlightx; int highlightWidth; if (start == 0) { // start highlight from the start of the field highlightx = xOffset; } else { // Calculate the width of the unhighlighted text to get the
protected List<Rectangle> createHighlightAreas2(String fullText, String clippedText, FontMetrics fm, int xOffset, int yOffset, int height) { if (matchPattern == null) { return Collections.emptyList(); } Matcher matcher = matchPattern.matcher(clippedText); List<Rectangle> highlightAreas = null; int startFrom = 0; while (startFrom < clippedText.length() && matcher.find(startFrom)) { if (highlightAreas == null) { highlightAreas = new ArrayList<Rectangle>(); } int start = matcher.start(); int end = matcher.end(); if (start == end) { // empty matcher will cause infinite loop break; } startFrom = end; int highlightx; int highlightWidth; if (start == 0) { // start highlight from the start of the field highlightx = xOffset; } else { // Calculate the width of the unhighlighted text to get the // start of the highlighted region. String strToStart = clippedText.substring(0, start); highlightx = fm.stringWidth(strToStart) + xOffset; } // Get the width of the highlighted region String highlightText = clippedText.substring(start, end); highlightWidth = fm.stringWidth(highlightText); highlightAreas.add(new Rectangle(highlightx, yOffset, highlightWidth, height)); }// while ( startFrom < text.length() && matcher.find( startFrom ) ) if (highlightAreas == null) {
32,099
2
// start highlight from the start of the field
protected List<Rectangle> createHighlightAreas2(String fullText, String clippedText, FontMetrics fm, int xOffset, int yOffset, int height) { if (matchPattern == null) { return Collections.emptyList(); } Matcher matcher = matchPattern.matcher(clippedText); List<Rectangle> highlightAreas = null; int startFrom = 0; while (startFrom < clippedText.length() && matcher.find(startFrom)) { if (highlightAreas == null) { highlightAreas = new ArrayList<Rectangle>(); } int start = matcher.start(); int end = matcher.end(); if (start == end) { // empty matcher will cause infinite loop break; } startFrom = end; int highlightx; int highlightWidth; if (start == 0) { // start highlight from the start of the field highlightx = xOffset; } else { // Calculate the width of the unhighlighted text to get the // start of the highlighted region. String strToStart = clippedText.substring(0, start); highlightx = fm.stringWidth(strToStart) + xOffset; } // Get the width of the highlighted region String highlightText = clippedText.substring(start, end); highlightWidth = fm.stringWidth(highlightText); highlightAreas.add(new Rectangle(highlightx, yOffset, highlightWidth, height)); }// while ( startFrom < text.length() && matcher.find( startFrom ) ) if (highlightAreas == null) { highlightAreas = Collections.emptyList(); } else { coalesceHighlightAreas(highlightAreas); } return highlightAreas; }
NONSATD
true
int highlightWidth; if (start == 0) { // start highlight from the start of the field highlightx = xOffset; } else {
int start = matcher.start(); int end = matcher.end(); if (start == end) { // empty matcher will cause infinite loop break; } startFrom = end; int highlightx; int highlightWidth; if (start == 0) { // start highlight from the start of the field highlightx = xOffset; } else { // Calculate the width of the unhighlighted text to get the // start of the highlighted region. String strToStart = clippedText.substring(0, start); highlightx = fm.stringWidth(strToStart) + xOffset; } // Get the width of the highlighted region String highlightText = clippedText.substring(start, end); highlightWidth = fm.stringWidth(highlightText);
if (matchPattern == null) { return Collections.emptyList(); } Matcher matcher = matchPattern.matcher(clippedText); List<Rectangle> highlightAreas = null; int startFrom = 0; while (startFrom < clippedText.length() && matcher.find(startFrom)) { if (highlightAreas == null) { highlightAreas = new ArrayList<Rectangle>(); } int start = matcher.start(); int end = matcher.end(); if (start == end) { // empty matcher will cause infinite loop break; } startFrom = end; int highlightx; int highlightWidth; if (start == 0) { // start highlight from the start of the field highlightx = xOffset; } else { // Calculate the width of the unhighlighted text to get the // start of the highlighted region. String strToStart = clippedText.substring(0, start); highlightx = fm.stringWidth(strToStart) + xOffset; } // Get the width of the highlighted region String highlightText = clippedText.substring(start, end); highlightWidth = fm.stringWidth(highlightText); highlightAreas.add(new Rectangle(highlightx, yOffset, highlightWidth, height)); }// while ( startFrom < text.length() && matcher.find( startFrom ) ) if (highlightAreas == null) { highlightAreas = Collections.emptyList(); } else { coalesceHighlightAreas(highlightAreas); } return highlightAreas; }
32,099
3
// Calculate the width of the unhighlighted text to get the // start of the highlighted region.
protected List<Rectangle> createHighlightAreas2(String fullText, String clippedText, FontMetrics fm, int xOffset, int yOffset, int height) { if (matchPattern == null) { return Collections.emptyList(); } Matcher matcher = matchPattern.matcher(clippedText); List<Rectangle> highlightAreas = null; int startFrom = 0; while (startFrom < clippedText.length() && matcher.find(startFrom)) { if (highlightAreas == null) { highlightAreas = new ArrayList<Rectangle>(); } int start = matcher.start(); int end = matcher.end(); if (start == end) { // empty matcher will cause infinite loop break; } startFrom = end; int highlightx; int highlightWidth; if (start == 0) { // start highlight from the start of the field highlightx = xOffset; } else { // Calculate the width of the unhighlighted text to get the // start of the highlighted region. String strToStart = clippedText.substring(0, start); highlightx = fm.stringWidth(strToStart) + xOffset; } // Get the width of the highlighted region String highlightText = clippedText.substring(start, end); highlightWidth = fm.stringWidth(highlightText); highlightAreas.add(new Rectangle(highlightx, yOffset, highlightWidth, height)); }// while ( startFrom < text.length() && matcher.find( startFrom ) ) if (highlightAreas == null) { highlightAreas = Collections.emptyList(); } else { coalesceHighlightAreas(highlightAreas); } return highlightAreas; }
NONSATD
true
highlightx = xOffset; } else { // Calculate the width of the unhighlighted text to get the // start of the highlighted region. String strToStart = clippedText.substring(0, start); highlightx = fm.stringWidth(strToStart) + xOffset;
// empty matcher will cause infinite loop break; } startFrom = end; int highlightx; int highlightWidth; if (start == 0) { // start highlight from the start of the field highlightx = xOffset; } else { // Calculate the width of the unhighlighted text to get the // start of the highlighted region. String strToStart = clippedText.substring(0, start); highlightx = fm.stringWidth(strToStart) + xOffset; } // Get the width of the highlighted region String highlightText = clippedText.substring(start, end); highlightWidth = fm.stringWidth(highlightText); highlightAreas.add(new Rectangle(highlightx, yOffset, highlightWidth, height)); }// while ( startFrom < text.length() && matcher.find( startFrom ) ) if (highlightAreas == null) { highlightAreas = Collections.emptyList();
Matcher matcher = matchPattern.matcher(clippedText); List<Rectangle> highlightAreas = null; int startFrom = 0; while (startFrom < clippedText.length() && matcher.find(startFrom)) { if (highlightAreas == null) { highlightAreas = new ArrayList<Rectangle>(); } int start = matcher.start(); int end = matcher.end(); if (start == end) { // empty matcher will cause infinite loop break; } startFrom = end; int highlightx; int highlightWidth; if (start == 0) { // start highlight from the start of the field highlightx = xOffset; } else { // Calculate the width of the unhighlighted text to get the // start of the highlighted region. String strToStart = clippedText.substring(0, start); highlightx = fm.stringWidth(strToStart) + xOffset; } // Get the width of the highlighted region String highlightText = clippedText.substring(start, end); highlightWidth = fm.stringWidth(highlightText); highlightAreas.add(new Rectangle(highlightx, yOffset, highlightWidth, height)); }// while ( startFrom < text.length() && matcher.find( startFrom ) ) if (highlightAreas == null) { highlightAreas = Collections.emptyList(); } else { coalesceHighlightAreas(highlightAreas); } return highlightAreas; }
32,099
4
// Get the width of the highlighted region
protected List<Rectangle> createHighlightAreas2(String fullText, String clippedText, FontMetrics fm, int xOffset, int yOffset, int height) { if (matchPattern == null) { return Collections.emptyList(); } Matcher matcher = matchPattern.matcher(clippedText); List<Rectangle> highlightAreas = null; int startFrom = 0; while (startFrom < clippedText.length() && matcher.find(startFrom)) { if (highlightAreas == null) { highlightAreas = new ArrayList<Rectangle>(); } int start = matcher.start(); int end = matcher.end(); if (start == end) { // empty matcher will cause infinite loop break; } startFrom = end; int highlightx; int highlightWidth; if (start == 0) { // start highlight from the start of the field highlightx = xOffset; } else { // Calculate the width of the unhighlighted text to get the // start of the highlighted region. String strToStart = clippedText.substring(0, start); highlightx = fm.stringWidth(strToStart) + xOffset; } // Get the width of the highlighted region String highlightText = clippedText.substring(start, end); highlightWidth = fm.stringWidth(highlightText); highlightAreas.add(new Rectangle(highlightx, yOffset, highlightWidth, height)); }// while ( startFrom < text.length() && matcher.find( startFrom ) ) if (highlightAreas == null) { highlightAreas = Collections.emptyList(); } else { coalesceHighlightAreas(highlightAreas); } return highlightAreas; }
NONSATD
true
highlightx = fm.stringWidth(strToStart) + xOffset; } // Get the width of the highlighted region String highlightText = clippedText.substring(start, end); highlightWidth = fm.stringWidth(highlightText);
int highlightWidth; if (start == 0) { // start highlight from the start of the field highlightx = xOffset; } else { // Calculate the width of the unhighlighted text to get the // start of the highlighted region. String strToStart = clippedText.substring(0, start); highlightx = fm.stringWidth(strToStart) + xOffset; } // Get the width of the highlighted region String highlightText = clippedText.substring(start, end); highlightWidth = fm.stringWidth(highlightText); highlightAreas.add(new Rectangle(highlightx, yOffset, highlightWidth, height)); }// while ( startFrom < text.length() && matcher.find( startFrom ) ) if (highlightAreas == null) { highlightAreas = Collections.emptyList(); } else { coalesceHighlightAreas(highlightAreas); } return highlightAreas;
highlightAreas = new ArrayList<Rectangle>(); } int start = matcher.start(); int end = matcher.end(); if (start == end) { // empty matcher will cause infinite loop break; } startFrom = end; int highlightx; int highlightWidth; if (start == 0) { // start highlight from the start of the field highlightx = xOffset; } else { // Calculate the width of the unhighlighted text to get the // start of the highlighted region. String strToStart = clippedText.substring(0, start); highlightx = fm.stringWidth(strToStart) + xOffset; } // Get the width of the highlighted region String highlightText = clippedText.substring(start, end); highlightWidth = fm.stringWidth(highlightText); highlightAreas.add(new Rectangle(highlightx, yOffset, highlightWidth, height)); }// while ( startFrom < text.length() && matcher.find( startFrom ) ) if (highlightAreas == null) { highlightAreas = Collections.emptyList(); } else { coalesceHighlightAreas(highlightAreas); } return highlightAreas; }
32,099
5
// while ( startFrom < text.length() && matcher.find( startFrom ) )
protected List<Rectangle> createHighlightAreas2(String fullText, String clippedText, FontMetrics fm, int xOffset, int yOffset, int height) { if (matchPattern == null) { return Collections.emptyList(); } Matcher matcher = matchPattern.matcher(clippedText); List<Rectangle> highlightAreas = null; int startFrom = 0; while (startFrom < clippedText.length() && matcher.find(startFrom)) { if (highlightAreas == null) { highlightAreas = new ArrayList<Rectangle>(); } int start = matcher.start(); int end = matcher.end(); if (start == end) { // empty matcher will cause infinite loop break; } startFrom = end; int highlightx; int highlightWidth; if (start == 0) { // start highlight from the start of the field highlightx = xOffset; } else { // Calculate the width of the unhighlighted text to get the // start of the highlighted region. String strToStart = clippedText.substring(0, start); highlightx = fm.stringWidth(strToStart) + xOffset; } // Get the width of the highlighted region String highlightText = clippedText.substring(start, end); highlightWidth = fm.stringWidth(highlightText); highlightAreas.add(new Rectangle(highlightx, yOffset, highlightWidth, height)); }// while ( startFrom < text.length() && matcher.find( startFrom ) ) if (highlightAreas == null) { highlightAreas = Collections.emptyList(); } else { coalesceHighlightAreas(highlightAreas); } return highlightAreas; }
NONSATD
true
highlightWidth = fm.stringWidth(highlightText); highlightAreas.add(new Rectangle(highlightx, yOffset, highlightWidth, height)); }// while ( startFrom < text.length() && matcher.find( startFrom ) ) if (highlightAreas == null) { highlightAreas = Collections.emptyList();
} else { // Calculate the width of the unhighlighted text to get the // start of the highlighted region. String strToStart = clippedText.substring(0, start); highlightx = fm.stringWidth(strToStart) + xOffset; } // Get the width of the highlighted region String highlightText = clippedText.substring(start, end); highlightWidth = fm.stringWidth(highlightText); highlightAreas.add(new Rectangle(highlightx, yOffset, highlightWidth, height)); }// while ( startFrom < text.length() && matcher.find( startFrom ) ) if (highlightAreas == null) { highlightAreas = Collections.emptyList(); } else { coalesceHighlightAreas(highlightAreas); } return highlightAreas; }
if (start == end) { // empty matcher will cause infinite loop break; } startFrom = end; int highlightx; int highlightWidth; if (start == 0) { // start highlight from the start of the field highlightx = xOffset; } else { // Calculate the width of the unhighlighted text to get the // start of the highlighted region. String strToStart = clippedText.substring(0, start); highlightx = fm.stringWidth(strToStart) + xOffset; } // Get the width of the highlighted region String highlightText = clippedText.substring(start, end); highlightWidth = fm.stringWidth(highlightText); highlightAreas.add(new Rectangle(highlightx, yOffset, highlightWidth, height)); }// while ( startFrom < text.length() && matcher.find( startFrom ) ) if (highlightAreas == null) { highlightAreas = Collections.emptyList(); } else { coalesceHighlightAreas(highlightAreas); } return highlightAreas; }
32,106
0
//FIXME why one day in future payment is allowed
@Test public void testMakePaymentForSavingsAccountOnDeposit() throws Exception { savingsBO = createClientSavingsAccount(); String deposit = "400"; CustomerDto clientDto = new CustomerDto(); clientDto.setCustomerId(client.getCustomerId()); //FIXME why one day in future payment is allowed LocalDate paymentDate = new LocalDate().plusDays(1); LocalDate receiptDate = new LocalDate().minusDays(3); String receiptNumber = "AA/03/UX-9Q"; Assert.assertEquals(0, savingsBO.getAccountPayments().size()); AccountPaymentParametersDto depositPayment = new AccountPaymentParametersDto(new UserReferenceDto(savingsBO .getPersonnel().getPersonnelId()), new AccountReferenceDto(savingsBO.getAccountId()), new BigDecimal( deposit), paymentDate, defaultPaymentType, "comment", receiptDate, receiptNumber, clientDto); standardAccountService.makePayment(depositPayment); TestObjectFactory.updateObject(savingsBO); Assert.assertEquals("The amount returned for the payment should have been " + deposit, Double .parseDouble(deposit), savingsBO.getLastPmntAmnt()); Assert.assertEquals(1, savingsBO.getAccountPayments().size()); for (AccountPaymentEntity payment : savingsBO.getAccountPayments()) { Assert.assertEquals(TestUtils.createMoney(deposit), payment.getAmount()); Assert.assertEquals(1, payment.getAccountTrxns().size()); Assert.assertEquals(paymentDate.toDateMidnight().toDate(), payment.getPaymentDate()); Assert.assertEquals(defaultPaymentType.getName(), payment.getPaymentType().getName()); Assert.assertEquals("comment", payment.getComment()); Assert.assertEquals(savingsBO, payment.getAccount()); Assert.assertEquals(savingsBO.getPersonnel(), payment.getCreatedByUser()); Assert.assertEquals(receiptDate.toDateMidnight().toDate(), payment.getReceiptDate()); Assert.assertEquals(receiptNumber, payment.getReceiptNumber()); Assert.assertNull(payment.getCheckNumber()); Assert.assertNull(payment.getBankName()); Assert.assertNull(payment.getVoucherNumber()); Assert.assertTrue(payment.isSavingsDeposit()); Assert.assertFalse(payment.isSavingsWithdrawal()); Assert.assertTrue(payment.isSavingsDepositOrWithdrawal()); for (AccountTrxnEntity accountTrxn : payment.getAccountTrxns()) { Assert.assertEquals(client.getCustomerId(), accountTrxn.getCustomer().getCustomerId()); } } }
DESIGN
true
CustomerDto clientDto = new CustomerDto(); clientDto.setCustomerId(client.getCustomerId()); //FIXME why one day in future payment is allowed LocalDate paymentDate = new LocalDate().plusDays(1); LocalDate receiptDate = new LocalDate().minusDays(3);
@Test public void testMakePaymentForSavingsAccountOnDeposit() throws Exception { savingsBO = createClientSavingsAccount(); String deposit = "400"; CustomerDto clientDto = new CustomerDto(); clientDto.setCustomerId(client.getCustomerId()); //FIXME why one day in future payment is allowed LocalDate paymentDate = new LocalDate().plusDays(1); LocalDate receiptDate = new LocalDate().minusDays(3); String receiptNumber = "AA/03/UX-9Q"; Assert.assertEquals(0, savingsBO.getAccountPayments().size()); AccountPaymentParametersDto depositPayment = new AccountPaymentParametersDto(new UserReferenceDto(savingsBO .getPersonnel().getPersonnelId()), new AccountReferenceDto(savingsBO.getAccountId()), new BigDecimal( deposit), paymentDate, defaultPaymentType, "comment", receiptDate, receiptNumber, clientDto); standardAccountService.makePayment(depositPayment); TestObjectFactory.updateObject(savingsBO);
@Test public void testMakePaymentForSavingsAccountOnDeposit() throws Exception { savingsBO = createClientSavingsAccount(); String deposit = "400"; CustomerDto clientDto = new CustomerDto(); clientDto.setCustomerId(client.getCustomerId()); //FIXME why one day in future payment is allowed LocalDate paymentDate = new LocalDate().plusDays(1); LocalDate receiptDate = new LocalDate().minusDays(3); String receiptNumber = "AA/03/UX-9Q"; Assert.assertEquals(0, savingsBO.getAccountPayments().size()); AccountPaymentParametersDto depositPayment = new AccountPaymentParametersDto(new UserReferenceDto(savingsBO .getPersonnel().getPersonnelId()), new AccountReferenceDto(savingsBO.getAccountId()), new BigDecimal( deposit), paymentDate, defaultPaymentType, "comment", receiptDate, receiptNumber, clientDto); standardAccountService.makePayment(depositPayment); TestObjectFactory.updateObject(savingsBO); Assert.assertEquals("The amount returned for the payment should have been " + deposit, Double .parseDouble(deposit), savingsBO.getLastPmntAmnt()); Assert.assertEquals(1, savingsBO.getAccountPayments().size()); for (AccountPaymentEntity payment : savingsBO.getAccountPayments()) { Assert.assertEquals(TestUtils.createMoney(deposit), payment.getAmount()); Assert.assertEquals(1, payment.getAccountTrxns().size()); Assert.assertEquals(paymentDate.toDateMidnight().toDate(), payment.getPaymentDate()); Assert.assertEquals(defaultPaymentType.getName(), payment.getPaymentType().getName()); Assert.assertEquals("comment", payment.getComment()); Assert.assertEquals(savingsBO, payment.getAccount());
32,108
0
// WELCOME TO MADNESS
private static boolean step(int faceIndex) { Triangle t = faces.get(faceIndex); // 2. Get most distant point of the face's point set Vector3f furthestPoint = null; int furthestPointID = -1; Vector3f A = vertices.get(t.a); List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear(); lightFaceVerticesToTriangles.put(t.a, vertsA); lightFaceVerticesToTriangles.put(t.b, vertsB); lightFaceVerticesToTriangles.put(t.c, vertsC); for (int i = faces.size() - 1; i >= 0; i--) { Triangle tri = faces.get(i); Vector3f triA = vertices.get(tri.a); if (VecMath.dotproduct(tri.normal, VecMath.subtraction(furthestPoint, triA, tmpvec)) > 0) { lastremovedTriangles.add(faces.remove(i)); lightFaceVertices.add(tri.a); lightFaceVertices.add(tri.b); lightFaceVertices.add(tri.c); if ((vertsA = lightFaceVerticesToTriangles.get(tri.a)) != null) { vertsA.add(tri); } else { vertsA = new ArrayList<Triangle>(); vertsA.add(tri); lightFaceVerticesToTriangles.put(tri.a, vertsA); } if ((vertsB = lightFaceVerticesToTriangles.get(tri.b)) != null) { vertsB.add(tri); } else { vertsB = new ArrayList<Triangle>(); vertsB.add(tri); lightFaceVerticesToTriangles.put(tri.b, vertsB); } if ((vertsC = lightFaceVerticesToTriangles.get(tri.c)) != null) { vertsC.add(tri); } else { vertsC = new ArrayList<Triangle>(); vertsC.add(tri); lightFaceVerticesToTriangles.put(tri.c, vertsC); } facepoints.addAll(listsOfFacePoints.remove(i)); } } // 4.0 Remove all vertices that are only connected to lightFaceVertices Iterator<Integer> iter = lightFaceVertices.iterator(); toRemove.clear(); for (int i = 0; i < lightFaceVertices.size(); i++) { int vert = iter.next(); // TODO: check if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) { toRemove.add(vert); } } for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) { adjacentsMap.get(adj).remove(i); tmppair.set(i, adj); edgesToTriangles.remove(tmppair); } lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert); List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert); for (int j = 0; j < adjs.size(); j++) { Integer currAdj = adjs.get(j); if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) { int tricount = 0; for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) { Triangle kTri = vertexLightTriangles.get(k); if (kTri.a == currAdj || kTri.b == currAdj || kTri.c == currAdj) { tricount++; } } if (tricount == 1) { currentVert = currAdj; break; } } } } // 4.2.1 remove old adjacents (crossing triangle hole) int edgesize = edge.size(); int edgesizeMinusOne = edgesize - 1; for (int i = 0; i < edgesize; i++) { currentVert = edge.get(i); removeAdj.clear(); for (Integer adj : adjacentsMap.get(currentVert)) { if (edge.contains(adj)) { int adjIndexOnEdge = edge.indexOf(adj); if (Math.abs(i - adjIndexOnEdge) > 1 && !(i == 0 && adjIndexOnEdge == edgesizeMinusOne) && !(i == edgesizeMinusOne && adjIndexOnEdge == 0)) { tmppair.set(currentVert, adj); Pair<Triangle, Triangle> edgeTriangles = edgesToTriangles.get(tmppair); // TODO: performance if (lastremovedTriangles.contains(edgeTriangles.getFirst()) && lastremovedTriangles.contains(edgeTriangles.getSecond())) { removeAdj.add(adj); edgesToTriangles.remove(edgeTriangles); } } } } for (Integer removAdjacent : removeAdj) { // TODO: make faster adjacentsMap.get(currentVert).remove(removAdjacent); } } // 4.3 Stitch holes using edge newLightFaces.clear(); ArrayList<Integer> furthestPointNeighbours = new ArrayList<Integer>(edge.size()); A = vertices.get(edge.get(0)); Vector3f B = vertices.get(edge.get(1)); Vector3f C = vertices.get(edge.get(2)); for (int i = 3; i < edge.size() && !linearIndependent(A, B, C); i++) { C = vertices.get(edge.get(i)); } Vector3f normal = VecMath.computeNormal(A, B, C); boolean correctOrientation = VecMath.dotproduct(normal, VecMath.subtraction(A, furthestPoint, tmpvec)) < 0; int vertIDb = edge.get(0); for (int i = 0; i < edge.size(); i++) { int vertIDa = vertIDb; if (i < edge.size() - 1) { vertIDb = edge.get(i + 1); } else { vertIDb = edge.get(0); } Vector3f vA = vertices.get(vertIDa); Vector3f vB = vertices.get(vertIDb); Vector3f norm = VecMath.computeNormal(vA, vB, furthestPoint); Triangle stitchTriangle; if (correctOrientation) { stitchTriangle = new Triangle(vertIDa, vertIDb, furthestPointID, norm); } else { norm.negate(); stitchTriangle = new Triangle(vertIDa, furthestPointID, vertIDb, norm); } faces.add(0, stitchTriangle); newLightFaces.add(stitchTriangle); // Update adjacents map adjacentsMap.get(vertIDa).add(furthestPointID); tmppair.set(vertIDa, vertIDb); Pair<Triangle, Triangle> oldEdgeInfo = edgesToTriangles.get(tmppair); // find out which triangle got deleted if (lastremovedTriangles.contains(oldEdgeInfo.getFirst())) { oldEdgeInfo.setFirst(stitchTriangle); } else { oldEdgeInfo.setSecond(stitchTriangle); } tmppair.set(vertIDa, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { oldEdgeInfo.setSecond(stitchTriangle); } else { // TODO: just relevant for first iteration, move before loop edgesToTriangles.put(new Pair<Integer, Integer>(vertIDa, furthestPointID), new Pair<Triangle, Triangle>(null, stitchTriangle)); } tmppair.set(vertIDb, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { // TODO: just relevant for last iteration oldEdgeInfo.setFirst(stitchTriangle); } else { edgesToTriangles.put(new Pair<Integer, Integer>(vertIDb, furthestPointID), new Pair<Triangle, Triangle>(stitchTriangle, null)); } furthestPointNeighbours.add(vertIDa); } // 5. Assign all points of all light-faces to the new created faces adjacentsMap.put(furthestPointID, furthestPointNeighbours); for (Triangle tri : newLightFaces) { listsOfFacePoints.add(0, getLightPoints(tri, facepoints)); } // 6. Push new created faces on the stack and start at (1)) return false; }
NONSATD
true
private static boolean step(int faceIndex) { Triangle t = faces.get(faceIndex); // 2. Get most distant point of the face's point set Vector3f furthestPoint = null; int furthestPointID = -1; Vector3f A = vertices.get(t.a); List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear(); lightFaceVerticesToTriangles.put(t.a, vertsA); lightFaceVerticesToTriangles.put(t.b, vertsB); lightFaceVerticesToTriangles.put(t.c, vertsC); for (int i = faces.size() - 1; i >= 0; i--) { Triangle tri = faces.get(i); Vector3f triA = vertices.get(tri.a); if (VecMath.dotproduct(tri.normal, VecMath.subtraction(furthestPoint, triA, tmpvec)) > 0) { lastremovedTriangles.add(faces.remove(i)); lightFaceVertices.add(tri.a); lightFaceVertices.add(tri.b); lightFaceVertices.add(tri.c); if ((vertsA = lightFaceVerticesToTriangles.get(tri.a)) != null) { vertsA.add(tri); } else { vertsA = new ArrayList<Triangle>(); vertsA.add(tri); lightFaceVerticesToTriangles.put(tri.a, vertsA); } if ((vertsB = lightFaceVerticesToTriangles.get(tri.b)) != null) { vertsB.add(tri); } else { vertsB = new ArrayList<Triangle>(); vertsB.add(tri); lightFaceVerticesToTriangles.put(tri.b, vertsB); } if ((vertsC = lightFaceVerticesToTriangles.get(tri.c)) != null) { vertsC.add(tri); } else { vertsC = new ArrayList<Triangle>(); vertsC.add(tri); lightFaceVerticesToTriangles.put(tri.c, vertsC); } facepoints.addAll(listsOfFacePoints.remove(i)); } } // 4.0 Remove all vertices that are only connected to lightFaceVertices Iterator<Integer> iter = lightFaceVertices.iterator(); toRemove.clear(); for (int i = 0; i < lightFaceVertices.size(); i++) { int vert = iter.next(); // TODO: check if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) { toRemove.add(vert); } } for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) { adjacentsMap.get(adj).remove(i); tmppair.set(i, adj); edgesToTriangles.remove(tmppair); } lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert); List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert); for (int j = 0; j < adjs.size(); j++) { Integer currAdj = adjs.get(j); if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) { int tricount = 0; for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) { Triangle kTri = vertexLightTriangles.get(k); if (kTri.a == currAdj || kTri.b == currAdj || kTri.c == currAdj) { tricount++; } } if (tricount == 1) { currentVert = currAdj; break; } } } } // 4.2.1 remove old adjacents (crossing triangle hole) int edgesize = edge.size(); int edgesizeMinusOne = edgesize - 1; for (int i = 0; i < edgesize; i++) { currentVert = edge.get(i); removeAdj.clear(); for (Integer adj : adjacentsMap.get(currentVert)) { if (edge.contains(adj)) { int adjIndexOnEdge = edge.indexOf(adj); if (Math.abs(i - adjIndexOnEdge) > 1 && !(i == 0 && adjIndexOnEdge == edgesizeMinusOne) && !(i == edgesizeMinusOne && adjIndexOnEdge == 0)) { tmppair.set(currentVert, adj); Pair<Triangle, Triangle> edgeTriangles = edgesToTriangles.get(tmppair); // TODO: performance if (lastremovedTriangles.contains(edgeTriangles.getFirst()) && lastremovedTriangles.contains(edgeTriangles.getSecond())) { removeAdj.add(adj); edgesToTriangles.remove(edgeTriangles); } } } } for (Integer removAdjacent : removeAdj) { // TODO: make faster adjacentsMap.get(currentVert).remove(removAdjacent); } } // 4.3 Stitch holes using edge newLightFaces.clear(); ArrayList<Integer> furthestPointNeighbours = new ArrayList<Integer>(edge.size()); A = vertices.get(edge.get(0)); Vector3f B = vertices.get(edge.get(1)); Vector3f C = vertices.get(edge.get(2)); for (int i = 3; i < edge.size() && !linearIndependent(A, B, C); i++) { C = vertices.get(edge.get(i)); } Vector3f normal = VecMath.computeNormal(A, B, C); boolean correctOrientation = VecMath.dotproduct(normal, VecMath.subtraction(A, furthestPoint, tmpvec)) < 0; int vertIDb = edge.get(0); for (int i = 0; i < edge.size(); i++) { int vertIDa = vertIDb; if (i < edge.size() - 1) { vertIDb = edge.get(i + 1); } else { vertIDb = edge.get(0); } Vector3f vA = vertices.get(vertIDa); Vector3f vB = vertices.get(vertIDb); Vector3f norm = VecMath.computeNormal(vA, vB, furthestPoint); Triangle stitchTriangle; if (correctOrientation) { stitchTriangle = new Triangle(vertIDa, vertIDb, furthestPointID, norm); } else { norm.negate(); stitchTriangle = new Triangle(vertIDa, furthestPointID, vertIDb, norm); } faces.add(0, stitchTriangle); newLightFaces.add(stitchTriangle); // Update adjacents map adjacentsMap.get(vertIDa).add(furthestPointID); tmppair.set(vertIDa, vertIDb); Pair<Triangle, Triangle> oldEdgeInfo = edgesToTriangles.get(tmppair); // find out which triangle got deleted if (lastremovedTriangles.contains(oldEdgeInfo.getFirst())) { oldEdgeInfo.setFirst(stitchTriangle); } else { oldEdgeInfo.setSecond(stitchTriangle); } tmppair.set(vertIDa, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { oldEdgeInfo.setSecond(stitchTriangle); } else { // TODO: just relevant for first iteration, move before loop edgesToTriangles.put(new Pair<Integer, Integer>(vertIDa, furthestPointID), new Pair<Triangle, Triangle>(null, stitchTriangle)); } tmppair.set(vertIDb, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { // TODO: just relevant for last iteration oldEdgeInfo.setFirst(stitchTriangle); } else { edgesToTriangles.put(new Pair<Integer, Integer>(vertIDb, furthestPointID), new Pair<Triangle, Triangle>(stitchTriangle, null)); } furthestPointNeighbours.add(vertIDa); } // 5. Assign all points of all light-faces to the new created faces adjacentsMap.put(furthestPointID, furthestPointNeighbours); for (Triangle tri : newLightFaces) { listsOfFacePoints.add(0, getLightPoints(tri, facepoints)); } // 6. Push new created faces on the stack and start at (1)) return false; }
private static boolean step(int faceIndex) { Triangle t = faces.get(faceIndex); // 2. Get most distant point of the face's point set Vector3f furthestPoint = null; int furthestPointID = -1; Vector3f A = vertices.get(t.a); List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear(); lightFaceVerticesToTriangles.put(t.a, vertsA); lightFaceVerticesToTriangles.put(t.b, vertsB); lightFaceVerticesToTriangles.put(t.c, vertsC); for (int i = faces.size() - 1; i >= 0; i--) { Triangle tri = faces.get(i); Vector3f triA = vertices.get(tri.a); if (VecMath.dotproduct(tri.normal, VecMath.subtraction(furthestPoint, triA, tmpvec)) > 0) { lastremovedTriangles.add(faces.remove(i)); lightFaceVertices.add(tri.a); lightFaceVertices.add(tri.b); lightFaceVertices.add(tri.c); if ((vertsA = lightFaceVerticesToTriangles.get(tri.a)) != null) { vertsA.add(tri); } else { vertsA = new ArrayList<Triangle>(); vertsA.add(tri); lightFaceVerticesToTriangles.put(tri.a, vertsA); } if ((vertsB = lightFaceVerticesToTriangles.get(tri.b)) != null) { vertsB.add(tri); } else { vertsB = new ArrayList<Triangle>(); vertsB.add(tri); lightFaceVerticesToTriangles.put(tri.b, vertsB); } if ((vertsC = lightFaceVerticesToTriangles.get(tri.c)) != null) { vertsC.add(tri); } else { vertsC = new ArrayList<Triangle>(); vertsC.add(tri); lightFaceVerticesToTriangles.put(tri.c, vertsC); } facepoints.addAll(listsOfFacePoints.remove(i)); } } // 4.0 Remove all vertices that are only connected to lightFaceVertices Iterator<Integer> iter = lightFaceVertices.iterator(); toRemove.clear(); for (int i = 0; i < lightFaceVertices.size(); i++) { int vert = iter.next(); // TODO: check if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) { toRemove.add(vert); } } for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) { adjacentsMap.get(adj).remove(i); tmppair.set(i, adj); edgesToTriangles.remove(tmppair); } lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert); List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert); for (int j = 0; j < adjs.size(); j++) { Integer currAdj = adjs.get(j); if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) { int tricount = 0; for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) { Triangle kTri = vertexLightTriangles.get(k); if (kTri.a == currAdj || kTri.b == currAdj || kTri.c == currAdj) { tricount++; } } if (tricount == 1) { currentVert = currAdj; break; } } } } // 4.2.1 remove old adjacents (crossing triangle hole) int edgesize = edge.size(); int edgesizeMinusOne = edgesize - 1; for (int i = 0; i < edgesize; i++) { currentVert = edge.get(i); removeAdj.clear(); for (Integer adj : adjacentsMap.get(currentVert)) { if (edge.contains(adj)) { int adjIndexOnEdge = edge.indexOf(adj); if (Math.abs(i - adjIndexOnEdge) > 1 && !(i == 0 && adjIndexOnEdge == edgesizeMinusOne) && !(i == edgesizeMinusOne && adjIndexOnEdge == 0)) { tmppair.set(currentVert, adj); Pair<Triangle, Triangle> edgeTriangles = edgesToTriangles.get(tmppair); // TODO: performance if (lastremovedTriangles.contains(edgeTriangles.getFirst()) && lastremovedTriangles.contains(edgeTriangles.getSecond())) { removeAdj.add(adj); edgesToTriangles.remove(edgeTriangles); } } } } for (Integer removAdjacent : removeAdj) { // TODO: make faster adjacentsMap.get(currentVert).remove(removAdjacent); } } // 4.3 Stitch holes using edge newLightFaces.clear(); ArrayList<Integer> furthestPointNeighbours = new ArrayList<Integer>(edge.size()); A = vertices.get(edge.get(0)); Vector3f B = vertices.get(edge.get(1)); Vector3f C = vertices.get(edge.get(2)); for (int i = 3; i < edge.size() && !linearIndependent(A, B, C); i++) { C = vertices.get(edge.get(i)); } Vector3f normal = VecMath.computeNormal(A, B, C); boolean correctOrientation = VecMath.dotproduct(normal, VecMath.subtraction(A, furthestPoint, tmpvec)) < 0; int vertIDb = edge.get(0); for (int i = 0; i < edge.size(); i++) { int vertIDa = vertIDb; if (i < edge.size() - 1) { vertIDb = edge.get(i + 1); } else { vertIDb = edge.get(0); } Vector3f vA = vertices.get(vertIDa); Vector3f vB = vertices.get(vertIDb); Vector3f norm = VecMath.computeNormal(vA, vB, furthestPoint); Triangle stitchTriangle; if (correctOrientation) { stitchTriangle = new Triangle(vertIDa, vertIDb, furthestPointID, norm); } else { norm.negate(); stitchTriangle = new Triangle(vertIDa, furthestPointID, vertIDb, norm); } faces.add(0, stitchTriangle); newLightFaces.add(stitchTriangle); // Update adjacents map adjacentsMap.get(vertIDa).add(furthestPointID); tmppair.set(vertIDa, vertIDb); Pair<Triangle, Triangle> oldEdgeInfo = edgesToTriangles.get(tmppair); // find out which triangle got deleted if (lastremovedTriangles.contains(oldEdgeInfo.getFirst())) { oldEdgeInfo.setFirst(stitchTriangle); } else { oldEdgeInfo.setSecond(stitchTriangle); } tmppair.set(vertIDa, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { oldEdgeInfo.setSecond(stitchTriangle); } else { // TODO: just relevant for first iteration, move before loop edgesToTriangles.put(new Pair<Integer, Integer>(vertIDa, furthestPointID), new Pair<Triangle, Triangle>(null, stitchTriangle)); } tmppair.set(vertIDb, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { // TODO: just relevant for last iteration oldEdgeInfo.setFirst(stitchTriangle); } else { edgesToTriangles.put(new Pair<Integer, Integer>(vertIDb, furthestPointID), new Pair<Triangle, Triangle>(stitchTriangle, null)); } furthestPointNeighbours.add(vertIDa); } // 5. Assign all points of all light-faces to the new created faces adjacentsMap.put(furthestPointID, furthestPointNeighbours); for (Triangle tri : newLightFaces) { listsOfFacePoints.add(0, getLightPoints(tri, facepoints)); } // 6. Push new created faces on the stack and start at (1)) return false; }
private static boolean step(int faceIndex) { Triangle t = faces.get(faceIndex); // 2. Get most distant point of the face's point set Vector3f furthestPoint = null; int furthestPointID = -1; Vector3f A = vertices.get(t.a); List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear(); lightFaceVerticesToTriangles.put(t.a, vertsA); lightFaceVerticesToTriangles.put(t.b, vertsB); lightFaceVerticesToTriangles.put(t.c, vertsC); for (int i = faces.size() - 1; i >= 0; i--) { Triangle tri = faces.get(i); Vector3f triA = vertices.get(tri.a); if (VecMath.dotproduct(tri.normal, VecMath.subtraction(furthestPoint, triA, tmpvec)) > 0) { lastremovedTriangles.add(faces.remove(i)); lightFaceVertices.add(tri.a); lightFaceVertices.add(tri.b); lightFaceVertices.add(tri.c); if ((vertsA = lightFaceVerticesToTriangles.get(tri.a)) != null) { vertsA.add(tri); } else { vertsA = new ArrayList<Triangle>(); vertsA.add(tri); lightFaceVerticesToTriangles.put(tri.a, vertsA); } if ((vertsB = lightFaceVerticesToTriangles.get(tri.b)) != null) { vertsB.add(tri); } else { vertsB = new ArrayList<Triangle>(); vertsB.add(tri); lightFaceVerticesToTriangles.put(tri.b, vertsB); } if ((vertsC = lightFaceVerticesToTriangles.get(tri.c)) != null) { vertsC.add(tri); } else { vertsC = new ArrayList<Triangle>(); vertsC.add(tri); lightFaceVerticesToTriangles.put(tri.c, vertsC); } facepoints.addAll(listsOfFacePoints.remove(i)); } } // 4.0 Remove all vertices that are only connected to lightFaceVertices Iterator<Integer> iter = lightFaceVertices.iterator(); toRemove.clear(); for (int i = 0; i < lightFaceVertices.size(); i++) { int vert = iter.next(); // TODO: check if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) { toRemove.add(vert); } } for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) { adjacentsMap.get(adj).remove(i); tmppair.set(i, adj); edgesToTriangles.remove(tmppair); } lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert); List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert); for (int j = 0; j < adjs.size(); j++) { Integer currAdj = adjs.get(j); if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) { int tricount = 0; for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) { Triangle kTri = vertexLightTriangles.get(k); if (kTri.a == currAdj || kTri.b == currAdj || kTri.c == currAdj) { tricount++; } } if (tricount == 1) { currentVert = currAdj; break; } } } } // 4.2.1 remove old adjacents (crossing triangle hole) int edgesize = edge.size(); int edgesizeMinusOne = edgesize - 1; for (int i = 0; i < edgesize; i++) { currentVert = edge.get(i); removeAdj.clear(); for (Integer adj : adjacentsMap.get(currentVert)) { if (edge.contains(adj)) { int adjIndexOnEdge = edge.indexOf(adj); if (Math.abs(i - adjIndexOnEdge) > 1 && !(i == 0 && adjIndexOnEdge == edgesizeMinusOne) && !(i == edgesizeMinusOne && adjIndexOnEdge == 0)) { tmppair.set(currentVert, adj); Pair<Triangle, Triangle> edgeTriangles = edgesToTriangles.get(tmppair); // TODO: performance if (lastremovedTriangles.contains(edgeTriangles.getFirst()) && lastremovedTriangles.contains(edgeTriangles.getSecond())) { removeAdj.add(adj); edgesToTriangles.remove(edgeTriangles); } } } } for (Integer removAdjacent : removeAdj) { // TODO: make faster adjacentsMap.get(currentVert).remove(removAdjacent); } } // 4.3 Stitch holes using edge newLightFaces.clear(); ArrayList<Integer> furthestPointNeighbours = new ArrayList<Integer>(edge.size()); A = vertices.get(edge.get(0)); Vector3f B = vertices.get(edge.get(1)); Vector3f C = vertices.get(edge.get(2)); for (int i = 3; i < edge.size() && !linearIndependent(A, B, C); i++) { C = vertices.get(edge.get(i)); } Vector3f normal = VecMath.computeNormal(A, B, C); boolean correctOrientation = VecMath.dotproduct(normal, VecMath.subtraction(A, furthestPoint, tmpvec)) < 0; int vertIDb = edge.get(0); for (int i = 0; i < edge.size(); i++) { int vertIDa = vertIDb; if (i < edge.size() - 1) { vertIDb = edge.get(i + 1); } else { vertIDb = edge.get(0); } Vector3f vA = vertices.get(vertIDa); Vector3f vB = vertices.get(vertIDb); Vector3f norm = VecMath.computeNormal(vA, vB, furthestPoint); Triangle stitchTriangle; if (correctOrientation) { stitchTriangle = new Triangle(vertIDa, vertIDb, furthestPointID, norm); } else { norm.negate(); stitchTriangle = new Triangle(vertIDa, furthestPointID, vertIDb, norm); } faces.add(0, stitchTriangle); newLightFaces.add(stitchTriangle); // Update adjacents map adjacentsMap.get(vertIDa).add(furthestPointID); tmppair.set(vertIDa, vertIDb); Pair<Triangle, Triangle> oldEdgeInfo = edgesToTriangles.get(tmppair); // find out which triangle got deleted if (lastremovedTriangles.contains(oldEdgeInfo.getFirst())) { oldEdgeInfo.setFirst(stitchTriangle); } else { oldEdgeInfo.setSecond(stitchTriangle); } tmppair.set(vertIDa, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { oldEdgeInfo.setSecond(stitchTriangle); } else { // TODO: just relevant for first iteration, move before loop edgesToTriangles.put(new Pair<Integer, Integer>(vertIDa, furthestPointID), new Pair<Triangle, Triangle>(null, stitchTriangle)); } tmppair.set(vertIDb, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { // TODO: just relevant for last iteration oldEdgeInfo.setFirst(stitchTriangle); } else { edgesToTriangles.put(new Pair<Integer, Integer>(vertIDb, furthestPointID), new Pair<Triangle, Triangle>(stitchTriangle, null)); } furthestPointNeighbours.add(vertIDa); } // 5. Assign all points of all light-faces to the new created faces adjacentsMap.put(furthestPointID, furthestPointNeighbours); for (Triangle tri : newLightFaces) { listsOfFacePoints.add(0, getLightPoints(tri, facepoints)); } // 6. Push new created faces on the stack and start at (1)) return false; }
32,108
1
// 2. Get most distant point of the face's point set
private static boolean step(int faceIndex) { Triangle t = faces.get(faceIndex); // 2. Get most distant point of the face's point set Vector3f furthestPoint = null; int furthestPointID = -1; Vector3f A = vertices.get(t.a); List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear(); lightFaceVerticesToTriangles.put(t.a, vertsA); lightFaceVerticesToTriangles.put(t.b, vertsB); lightFaceVerticesToTriangles.put(t.c, vertsC); for (int i = faces.size() - 1; i >= 0; i--) { Triangle tri = faces.get(i); Vector3f triA = vertices.get(tri.a); if (VecMath.dotproduct(tri.normal, VecMath.subtraction(furthestPoint, triA, tmpvec)) > 0) { lastremovedTriangles.add(faces.remove(i)); lightFaceVertices.add(tri.a); lightFaceVertices.add(tri.b); lightFaceVertices.add(tri.c); if ((vertsA = lightFaceVerticesToTriangles.get(tri.a)) != null) { vertsA.add(tri); } else { vertsA = new ArrayList<Triangle>(); vertsA.add(tri); lightFaceVerticesToTriangles.put(tri.a, vertsA); } if ((vertsB = lightFaceVerticesToTriangles.get(tri.b)) != null) { vertsB.add(tri); } else { vertsB = new ArrayList<Triangle>(); vertsB.add(tri); lightFaceVerticesToTriangles.put(tri.b, vertsB); } if ((vertsC = lightFaceVerticesToTriangles.get(tri.c)) != null) { vertsC.add(tri); } else { vertsC = new ArrayList<Triangle>(); vertsC.add(tri); lightFaceVerticesToTriangles.put(tri.c, vertsC); } facepoints.addAll(listsOfFacePoints.remove(i)); } } // 4.0 Remove all vertices that are only connected to lightFaceVertices Iterator<Integer> iter = lightFaceVertices.iterator(); toRemove.clear(); for (int i = 0; i < lightFaceVertices.size(); i++) { int vert = iter.next(); // TODO: check if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) { toRemove.add(vert); } } for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) { adjacentsMap.get(adj).remove(i); tmppair.set(i, adj); edgesToTriangles.remove(tmppair); } lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert); List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert); for (int j = 0; j < adjs.size(); j++) { Integer currAdj = adjs.get(j); if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) { int tricount = 0; for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) { Triangle kTri = vertexLightTriangles.get(k); if (kTri.a == currAdj || kTri.b == currAdj || kTri.c == currAdj) { tricount++; } } if (tricount == 1) { currentVert = currAdj; break; } } } } // 4.2.1 remove old adjacents (crossing triangle hole) int edgesize = edge.size(); int edgesizeMinusOne = edgesize - 1; for (int i = 0; i < edgesize; i++) { currentVert = edge.get(i); removeAdj.clear(); for (Integer adj : adjacentsMap.get(currentVert)) { if (edge.contains(adj)) { int adjIndexOnEdge = edge.indexOf(adj); if (Math.abs(i - adjIndexOnEdge) > 1 && !(i == 0 && adjIndexOnEdge == edgesizeMinusOne) && !(i == edgesizeMinusOne && adjIndexOnEdge == 0)) { tmppair.set(currentVert, adj); Pair<Triangle, Triangle> edgeTriangles = edgesToTriangles.get(tmppair); // TODO: performance if (lastremovedTriangles.contains(edgeTriangles.getFirst()) && lastremovedTriangles.contains(edgeTriangles.getSecond())) { removeAdj.add(adj); edgesToTriangles.remove(edgeTriangles); } } } } for (Integer removAdjacent : removeAdj) { // TODO: make faster adjacentsMap.get(currentVert).remove(removAdjacent); } } // 4.3 Stitch holes using edge newLightFaces.clear(); ArrayList<Integer> furthestPointNeighbours = new ArrayList<Integer>(edge.size()); A = vertices.get(edge.get(0)); Vector3f B = vertices.get(edge.get(1)); Vector3f C = vertices.get(edge.get(2)); for (int i = 3; i < edge.size() && !linearIndependent(A, B, C); i++) { C = vertices.get(edge.get(i)); } Vector3f normal = VecMath.computeNormal(A, B, C); boolean correctOrientation = VecMath.dotproduct(normal, VecMath.subtraction(A, furthestPoint, tmpvec)) < 0; int vertIDb = edge.get(0); for (int i = 0; i < edge.size(); i++) { int vertIDa = vertIDb; if (i < edge.size() - 1) { vertIDb = edge.get(i + 1); } else { vertIDb = edge.get(0); } Vector3f vA = vertices.get(vertIDa); Vector3f vB = vertices.get(vertIDb); Vector3f norm = VecMath.computeNormal(vA, vB, furthestPoint); Triangle stitchTriangle; if (correctOrientation) { stitchTriangle = new Triangle(vertIDa, vertIDb, furthestPointID, norm); } else { norm.negate(); stitchTriangle = new Triangle(vertIDa, furthestPointID, vertIDb, norm); } faces.add(0, stitchTriangle); newLightFaces.add(stitchTriangle); // Update adjacents map adjacentsMap.get(vertIDa).add(furthestPointID); tmppair.set(vertIDa, vertIDb); Pair<Triangle, Triangle> oldEdgeInfo = edgesToTriangles.get(tmppair); // find out which triangle got deleted if (lastremovedTriangles.contains(oldEdgeInfo.getFirst())) { oldEdgeInfo.setFirst(stitchTriangle); } else { oldEdgeInfo.setSecond(stitchTriangle); } tmppair.set(vertIDa, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { oldEdgeInfo.setSecond(stitchTriangle); } else { // TODO: just relevant for first iteration, move before loop edgesToTriangles.put(new Pair<Integer, Integer>(vertIDa, furthestPointID), new Pair<Triangle, Triangle>(null, stitchTriangle)); } tmppair.set(vertIDb, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { // TODO: just relevant for last iteration oldEdgeInfo.setFirst(stitchTriangle); } else { edgesToTriangles.put(new Pair<Integer, Integer>(vertIDb, furthestPointID), new Pair<Triangle, Triangle>(stitchTriangle, null)); } furthestPointNeighbours.add(vertIDa); } // 5. Assign all points of all light-faces to the new created faces adjacentsMap.put(furthestPointID, furthestPointNeighbours); for (Triangle tri : newLightFaces) { listsOfFacePoints.add(0, getLightPoints(tri, facepoints)); } // 6. Push new created faces on the stack and start at (1)) return false; }
NONSATD
true
private static boolean step(int faceIndex) { Triangle t = faces.get(faceIndex); // 2. Get most distant point of the face's point set Vector3f furthestPoint = null; int furthestPointID = -1;
private static boolean step(int faceIndex) { Triangle t = faces.get(faceIndex); // 2. Get most distant point of the face's point set Vector3f furthestPoint = null; int furthestPointID = -1; Vector3f A = vertices.get(t.a); List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist;
private static boolean step(int faceIndex) { Triangle t = faces.get(faceIndex); // 2. Get most distant point of the face's point set Vector3f furthestPoint = null; int furthestPointID = -1; Vector3f A = vertices.get(t.a); List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1;
32,108
2
// TODO: check
private static boolean step(int faceIndex) { Triangle t = faces.get(faceIndex); // 2. Get most distant point of the face's point set Vector3f furthestPoint = null; int furthestPointID = -1; Vector3f A = vertices.get(t.a); List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear(); lightFaceVerticesToTriangles.put(t.a, vertsA); lightFaceVerticesToTriangles.put(t.b, vertsB); lightFaceVerticesToTriangles.put(t.c, vertsC); for (int i = faces.size() - 1; i >= 0; i--) { Triangle tri = faces.get(i); Vector3f triA = vertices.get(tri.a); if (VecMath.dotproduct(tri.normal, VecMath.subtraction(furthestPoint, triA, tmpvec)) > 0) { lastremovedTriangles.add(faces.remove(i)); lightFaceVertices.add(tri.a); lightFaceVertices.add(tri.b); lightFaceVertices.add(tri.c); if ((vertsA = lightFaceVerticesToTriangles.get(tri.a)) != null) { vertsA.add(tri); } else { vertsA = new ArrayList<Triangle>(); vertsA.add(tri); lightFaceVerticesToTriangles.put(tri.a, vertsA); } if ((vertsB = lightFaceVerticesToTriangles.get(tri.b)) != null) { vertsB.add(tri); } else { vertsB = new ArrayList<Triangle>(); vertsB.add(tri); lightFaceVerticesToTriangles.put(tri.b, vertsB); } if ((vertsC = lightFaceVerticesToTriangles.get(tri.c)) != null) { vertsC.add(tri); } else { vertsC = new ArrayList<Triangle>(); vertsC.add(tri); lightFaceVerticesToTriangles.put(tri.c, vertsC); } facepoints.addAll(listsOfFacePoints.remove(i)); } } // 4.0 Remove all vertices that are only connected to lightFaceVertices Iterator<Integer> iter = lightFaceVertices.iterator(); toRemove.clear(); for (int i = 0; i < lightFaceVertices.size(); i++) { int vert = iter.next(); // TODO: check if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) { toRemove.add(vert); } } for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) { adjacentsMap.get(adj).remove(i); tmppair.set(i, adj); edgesToTriangles.remove(tmppair); } lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert); List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert); for (int j = 0; j < adjs.size(); j++) { Integer currAdj = adjs.get(j); if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) { int tricount = 0; for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) { Triangle kTri = vertexLightTriangles.get(k); if (kTri.a == currAdj || kTri.b == currAdj || kTri.c == currAdj) { tricount++; } } if (tricount == 1) { currentVert = currAdj; break; } } } } // 4.2.1 remove old adjacents (crossing triangle hole) int edgesize = edge.size(); int edgesizeMinusOne = edgesize - 1; for (int i = 0; i < edgesize; i++) { currentVert = edge.get(i); removeAdj.clear(); for (Integer adj : adjacentsMap.get(currentVert)) { if (edge.contains(adj)) { int adjIndexOnEdge = edge.indexOf(adj); if (Math.abs(i - adjIndexOnEdge) > 1 && !(i == 0 && adjIndexOnEdge == edgesizeMinusOne) && !(i == edgesizeMinusOne && adjIndexOnEdge == 0)) { tmppair.set(currentVert, adj); Pair<Triangle, Triangle> edgeTriangles = edgesToTriangles.get(tmppair); // TODO: performance if (lastremovedTriangles.contains(edgeTriangles.getFirst()) && lastremovedTriangles.contains(edgeTriangles.getSecond())) { removeAdj.add(adj); edgesToTriangles.remove(edgeTriangles); } } } } for (Integer removAdjacent : removeAdj) { // TODO: make faster adjacentsMap.get(currentVert).remove(removAdjacent); } } // 4.3 Stitch holes using edge newLightFaces.clear(); ArrayList<Integer> furthestPointNeighbours = new ArrayList<Integer>(edge.size()); A = vertices.get(edge.get(0)); Vector3f B = vertices.get(edge.get(1)); Vector3f C = vertices.get(edge.get(2)); for (int i = 3; i < edge.size() && !linearIndependent(A, B, C); i++) { C = vertices.get(edge.get(i)); } Vector3f normal = VecMath.computeNormal(A, B, C); boolean correctOrientation = VecMath.dotproduct(normal, VecMath.subtraction(A, furthestPoint, tmpvec)) < 0; int vertIDb = edge.get(0); for (int i = 0; i < edge.size(); i++) { int vertIDa = vertIDb; if (i < edge.size() - 1) { vertIDb = edge.get(i + 1); } else { vertIDb = edge.get(0); } Vector3f vA = vertices.get(vertIDa); Vector3f vB = vertices.get(vertIDb); Vector3f norm = VecMath.computeNormal(vA, vB, furthestPoint); Triangle stitchTriangle; if (correctOrientation) { stitchTriangle = new Triangle(vertIDa, vertIDb, furthestPointID, norm); } else { norm.negate(); stitchTriangle = new Triangle(vertIDa, furthestPointID, vertIDb, norm); } faces.add(0, stitchTriangle); newLightFaces.add(stitchTriangle); // Update adjacents map adjacentsMap.get(vertIDa).add(furthestPointID); tmppair.set(vertIDa, vertIDb); Pair<Triangle, Triangle> oldEdgeInfo = edgesToTriangles.get(tmppair); // find out which triangle got deleted if (lastremovedTriangles.contains(oldEdgeInfo.getFirst())) { oldEdgeInfo.setFirst(stitchTriangle); } else { oldEdgeInfo.setSecond(stitchTriangle); } tmppair.set(vertIDa, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { oldEdgeInfo.setSecond(stitchTriangle); } else { // TODO: just relevant for first iteration, move before loop edgesToTriangles.put(new Pair<Integer, Integer>(vertIDa, furthestPointID), new Pair<Triangle, Triangle>(null, stitchTriangle)); } tmppair.set(vertIDb, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { // TODO: just relevant for last iteration oldEdgeInfo.setFirst(stitchTriangle); } else { edgesToTriangles.put(new Pair<Integer, Integer>(vertIDb, furthestPointID), new Pair<Triangle, Triangle>(stitchTriangle, null)); } furthestPointNeighbours.add(vertIDa); } // 5. Assign all points of all light-faces to the new created faces adjacentsMap.put(furthestPointID, furthestPointNeighbours); for (Triangle tri : newLightFaces) { listsOfFacePoints.add(0, getLightPoints(tri, facepoints)); } // 6. Push new created faces on the stack and start at (1)) return false; }
NONSATD
true
} } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; }
float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why.
private static boolean step(int faceIndex) { Triangle t = faces.get(faceIndex); // 2. Get most distant point of the face's point set Vector3f furthestPoint = null; int furthestPointID = -1; Vector3f A = vertices.get(t.a); List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear();
32,108
3
// 3. Find all faces that can be seen from this point
private static boolean step(int faceIndex) { Triangle t = faces.get(faceIndex); // 2. Get most distant point of the face's point set Vector3f furthestPoint = null; int furthestPointID = -1; Vector3f A = vertices.get(t.a); List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear(); lightFaceVerticesToTriangles.put(t.a, vertsA); lightFaceVerticesToTriangles.put(t.b, vertsB); lightFaceVerticesToTriangles.put(t.c, vertsC); for (int i = faces.size() - 1; i >= 0; i--) { Triangle tri = faces.get(i); Vector3f triA = vertices.get(tri.a); if (VecMath.dotproduct(tri.normal, VecMath.subtraction(furthestPoint, triA, tmpvec)) > 0) { lastremovedTriangles.add(faces.remove(i)); lightFaceVertices.add(tri.a); lightFaceVertices.add(tri.b); lightFaceVertices.add(tri.c); if ((vertsA = lightFaceVerticesToTriangles.get(tri.a)) != null) { vertsA.add(tri); } else { vertsA = new ArrayList<Triangle>(); vertsA.add(tri); lightFaceVerticesToTriangles.put(tri.a, vertsA); } if ((vertsB = lightFaceVerticesToTriangles.get(tri.b)) != null) { vertsB.add(tri); } else { vertsB = new ArrayList<Triangle>(); vertsB.add(tri); lightFaceVerticesToTriangles.put(tri.b, vertsB); } if ((vertsC = lightFaceVerticesToTriangles.get(tri.c)) != null) { vertsC.add(tri); } else { vertsC = new ArrayList<Triangle>(); vertsC.add(tri); lightFaceVerticesToTriangles.put(tri.c, vertsC); } facepoints.addAll(listsOfFacePoints.remove(i)); } } // 4.0 Remove all vertices that are only connected to lightFaceVertices Iterator<Integer> iter = lightFaceVertices.iterator(); toRemove.clear(); for (int i = 0; i < lightFaceVertices.size(); i++) { int vert = iter.next(); // TODO: check if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) { toRemove.add(vert); } } for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) { adjacentsMap.get(adj).remove(i); tmppair.set(i, adj); edgesToTriangles.remove(tmppair); } lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert); List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert); for (int j = 0; j < adjs.size(); j++) { Integer currAdj = adjs.get(j); if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) { int tricount = 0; for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) { Triangle kTri = vertexLightTriangles.get(k); if (kTri.a == currAdj || kTri.b == currAdj || kTri.c == currAdj) { tricount++; } } if (tricount == 1) { currentVert = currAdj; break; } } } } // 4.2.1 remove old adjacents (crossing triangle hole) int edgesize = edge.size(); int edgesizeMinusOne = edgesize - 1; for (int i = 0; i < edgesize; i++) { currentVert = edge.get(i); removeAdj.clear(); for (Integer adj : adjacentsMap.get(currentVert)) { if (edge.contains(adj)) { int adjIndexOnEdge = edge.indexOf(adj); if (Math.abs(i - adjIndexOnEdge) > 1 && !(i == 0 && adjIndexOnEdge == edgesizeMinusOne) && !(i == edgesizeMinusOne && adjIndexOnEdge == 0)) { tmppair.set(currentVert, adj); Pair<Triangle, Triangle> edgeTriangles = edgesToTriangles.get(tmppair); // TODO: performance if (lastremovedTriangles.contains(edgeTriangles.getFirst()) && lastremovedTriangles.contains(edgeTriangles.getSecond())) { removeAdj.add(adj); edgesToTriangles.remove(edgeTriangles); } } } } for (Integer removAdjacent : removeAdj) { // TODO: make faster adjacentsMap.get(currentVert).remove(removAdjacent); } } // 4.3 Stitch holes using edge newLightFaces.clear(); ArrayList<Integer> furthestPointNeighbours = new ArrayList<Integer>(edge.size()); A = vertices.get(edge.get(0)); Vector3f B = vertices.get(edge.get(1)); Vector3f C = vertices.get(edge.get(2)); for (int i = 3; i < edge.size() && !linearIndependent(A, B, C); i++) { C = vertices.get(edge.get(i)); } Vector3f normal = VecMath.computeNormal(A, B, C); boolean correctOrientation = VecMath.dotproduct(normal, VecMath.subtraction(A, furthestPoint, tmpvec)) < 0; int vertIDb = edge.get(0); for (int i = 0; i < edge.size(); i++) { int vertIDa = vertIDb; if (i < edge.size() - 1) { vertIDb = edge.get(i + 1); } else { vertIDb = edge.get(0); } Vector3f vA = vertices.get(vertIDa); Vector3f vB = vertices.get(vertIDb); Vector3f norm = VecMath.computeNormal(vA, vB, furthestPoint); Triangle stitchTriangle; if (correctOrientation) { stitchTriangle = new Triangle(vertIDa, vertIDb, furthestPointID, norm); } else { norm.negate(); stitchTriangle = new Triangle(vertIDa, furthestPointID, vertIDb, norm); } faces.add(0, stitchTriangle); newLightFaces.add(stitchTriangle); // Update adjacents map adjacentsMap.get(vertIDa).add(furthestPointID); tmppair.set(vertIDa, vertIDb); Pair<Triangle, Triangle> oldEdgeInfo = edgesToTriangles.get(tmppair); // find out which triangle got deleted if (lastremovedTriangles.contains(oldEdgeInfo.getFirst())) { oldEdgeInfo.setFirst(stitchTriangle); } else { oldEdgeInfo.setSecond(stitchTriangle); } tmppair.set(vertIDa, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { oldEdgeInfo.setSecond(stitchTriangle); } else { // TODO: just relevant for first iteration, move before loop edgesToTriangles.put(new Pair<Integer, Integer>(vertIDa, furthestPointID), new Pair<Triangle, Triangle>(null, stitchTriangle)); } tmppair.set(vertIDb, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { // TODO: just relevant for last iteration oldEdgeInfo.setFirst(stitchTriangle); } else { edgesToTriangles.put(new Pair<Integer, Integer>(vertIDb, furthestPointID), new Pair<Triangle, Triangle>(stitchTriangle, null)); } furthestPointNeighbours.add(vertIDa); } // 5. Assign all points of all light-faces to the new created faces adjacentsMap.put(furthestPointID, furthestPointNeighbours); for (Triangle tri : newLightFaces) { listsOfFacePoints.add(0, getLightPoints(tri, facepoints)); } // 6. Push new created faces on the stack and start at (1)) return false; }
NONSATD
true
lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a);
} if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t);
List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear(); lightFaceVerticesToTriangles.put(t.a, vertsA); lightFaceVerticesToTriangles.put(t.b, vertsB); lightFaceVerticesToTriangles.put(t.c, vertsC); for (int i = faces.size() - 1; i >= 0; i--) { Triangle tri = faces.get(i); Vector3f triA = vertices.get(tri.a); if (VecMath.dotproduct(tri.normal, VecMath.subtraction(furthestPoint, triA, tmpvec)) > 0) { lastremovedTriangles.add(faces.remove(i)); lightFaceVertices.add(tri.a);
32,108
4
// HAS TO BE REINITIALIZED... don't ask why.
private static boolean step(int faceIndex) { Triangle t = faces.get(faceIndex); // 2. Get most distant point of the face's point set Vector3f furthestPoint = null; int furthestPointID = -1; Vector3f A = vertices.get(t.a); List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear(); lightFaceVerticesToTriangles.put(t.a, vertsA); lightFaceVerticesToTriangles.put(t.b, vertsB); lightFaceVerticesToTriangles.put(t.c, vertsC); for (int i = faces.size() - 1; i >= 0; i--) { Triangle tri = faces.get(i); Vector3f triA = vertices.get(tri.a); if (VecMath.dotproduct(tri.normal, VecMath.subtraction(furthestPoint, triA, tmpvec)) > 0) { lastremovedTriangles.add(faces.remove(i)); lightFaceVertices.add(tri.a); lightFaceVertices.add(tri.b); lightFaceVertices.add(tri.c); if ((vertsA = lightFaceVerticesToTriangles.get(tri.a)) != null) { vertsA.add(tri); } else { vertsA = new ArrayList<Triangle>(); vertsA.add(tri); lightFaceVerticesToTriangles.put(tri.a, vertsA); } if ((vertsB = lightFaceVerticesToTriangles.get(tri.b)) != null) { vertsB.add(tri); } else { vertsB = new ArrayList<Triangle>(); vertsB.add(tri); lightFaceVerticesToTriangles.put(tri.b, vertsB); } if ((vertsC = lightFaceVerticesToTriangles.get(tri.c)) != null) { vertsC.add(tri); } else { vertsC = new ArrayList<Triangle>(); vertsC.add(tri); lightFaceVerticesToTriangles.put(tri.c, vertsC); } facepoints.addAll(listsOfFacePoints.remove(i)); } } // 4.0 Remove all vertices that are only connected to lightFaceVertices Iterator<Integer> iter = lightFaceVertices.iterator(); toRemove.clear(); for (int i = 0; i < lightFaceVertices.size(); i++) { int vert = iter.next(); // TODO: check if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) { toRemove.add(vert); } } for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) { adjacentsMap.get(adj).remove(i); tmppair.set(i, adj); edgesToTriangles.remove(tmppair); } lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert); List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert); for (int j = 0; j < adjs.size(); j++) { Integer currAdj = adjs.get(j); if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) { int tricount = 0; for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) { Triangle kTri = vertexLightTriangles.get(k); if (kTri.a == currAdj || kTri.b == currAdj || kTri.c == currAdj) { tricount++; } } if (tricount == 1) { currentVert = currAdj; break; } } } } // 4.2.1 remove old adjacents (crossing triangle hole) int edgesize = edge.size(); int edgesizeMinusOne = edgesize - 1; for (int i = 0; i < edgesize; i++) { currentVert = edge.get(i); removeAdj.clear(); for (Integer adj : adjacentsMap.get(currentVert)) { if (edge.contains(adj)) { int adjIndexOnEdge = edge.indexOf(adj); if (Math.abs(i - adjIndexOnEdge) > 1 && !(i == 0 && adjIndexOnEdge == edgesizeMinusOne) && !(i == edgesizeMinusOne && adjIndexOnEdge == 0)) { tmppair.set(currentVert, adj); Pair<Triangle, Triangle> edgeTriangles = edgesToTriangles.get(tmppair); // TODO: performance if (lastremovedTriangles.contains(edgeTriangles.getFirst()) && lastremovedTriangles.contains(edgeTriangles.getSecond())) { removeAdj.add(adj); edgesToTriangles.remove(edgeTriangles); } } } } for (Integer removAdjacent : removeAdj) { // TODO: make faster adjacentsMap.get(currentVert).remove(removAdjacent); } } // 4.3 Stitch holes using edge newLightFaces.clear(); ArrayList<Integer> furthestPointNeighbours = new ArrayList<Integer>(edge.size()); A = vertices.get(edge.get(0)); Vector3f B = vertices.get(edge.get(1)); Vector3f C = vertices.get(edge.get(2)); for (int i = 3; i < edge.size() && !linearIndependent(A, B, C); i++) { C = vertices.get(edge.get(i)); } Vector3f normal = VecMath.computeNormal(A, B, C); boolean correctOrientation = VecMath.dotproduct(normal, VecMath.subtraction(A, furthestPoint, tmpvec)) < 0; int vertIDb = edge.get(0); for (int i = 0; i < edge.size(); i++) { int vertIDa = vertIDb; if (i < edge.size() - 1) { vertIDb = edge.get(i + 1); } else { vertIDb = edge.get(0); } Vector3f vA = vertices.get(vertIDa); Vector3f vB = vertices.get(vertIDb); Vector3f norm = VecMath.computeNormal(vA, vB, furthestPoint); Triangle stitchTriangle; if (correctOrientation) { stitchTriangle = new Triangle(vertIDa, vertIDb, furthestPointID, norm); } else { norm.negate(); stitchTriangle = new Triangle(vertIDa, furthestPointID, vertIDb, norm); } faces.add(0, stitchTriangle); newLightFaces.add(stitchTriangle); // Update adjacents map adjacentsMap.get(vertIDa).add(furthestPointID); tmppair.set(vertIDa, vertIDb); Pair<Triangle, Triangle> oldEdgeInfo = edgesToTriangles.get(tmppair); // find out which triangle got deleted if (lastremovedTriangles.contains(oldEdgeInfo.getFirst())) { oldEdgeInfo.setFirst(stitchTriangle); } else { oldEdgeInfo.setSecond(stitchTriangle); } tmppair.set(vertIDa, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { oldEdgeInfo.setSecond(stitchTriangle); } else { // TODO: just relevant for first iteration, move before loop edgesToTriangles.put(new Pair<Integer, Integer>(vertIDa, furthestPointID), new Pair<Triangle, Triangle>(null, stitchTriangle)); } tmppair.set(vertIDb, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { // TODO: just relevant for last iteration oldEdgeInfo.setFirst(stitchTriangle); } else { edgesToTriangles.put(new Pair<Integer, Integer>(vertIDb, furthestPointID), new Pair<Triangle, Triangle>(stitchTriangle, null)); } furthestPointNeighbours.add(vertIDa); } // 5. Assign all points of all light-faces to the new created faces adjacentsMap.put(furthestPointID, furthestPointNeighbours); for (Triangle tri : newLightFaces) { listsOfFacePoints.add(0, getLightPoints(tri, facepoints)); } // 6. Push new created faces on the stack and start at (1)) return false; }
DESIGN
true
listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b);
if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear();
float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear(); lightFaceVerticesToTriangles.put(t.a, vertsA); lightFaceVerticesToTriangles.put(t.b, vertsB); lightFaceVerticesToTriangles.put(t.c, vertsC); for (int i = faces.size() - 1; i >= 0; i--) { Triangle tri = faces.get(i); Vector3f triA = vertices.get(tri.a); if (VecMath.dotproduct(tri.normal, VecMath.subtraction(furthestPoint, triA, tmpvec)) > 0) { lastremovedTriangles.add(faces.remove(i)); lightFaceVertices.add(tri.a); lightFaceVertices.add(tri.b);
32,108
5
// 4.0 Remove all vertices that are only connected to lightFaceVertices
private static boolean step(int faceIndex) { Triangle t = faces.get(faceIndex); // 2. Get most distant point of the face's point set Vector3f furthestPoint = null; int furthestPointID = -1; Vector3f A = vertices.get(t.a); List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear(); lightFaceVerticesToTriangles.put(t.a, vertsA); lightFaceVerticesToTriangles.put(t.b, vertsB); lightFaceVerticesToTriangles.put(t.c, vertsC); for (int i = faces.size() - 1; i >= 0; i--) { Triangle tri = faces.get(i); Vector3f triA = vertices.get(tri.a); if (VecMath.dotproduct(tri.normal, VecMath.subtraction(furthestPoint, triA, tmpvec)) > 0) { lastremovedTriangles.add(faces.remove(i)); lightFaceVertices.add(tri.a); lightFaceVertices.add(tri.b); lightFaceVertices.add(tri.c); if ((vertsA = lightFaceVerticesToTriangles.get(tri.a)) != null) { vertsA.add(tri); } else { vertsA = new ArrayList<Triangle>(); vertsA.add(tri); lightFaceVerticesToTriangles.put(tri.a, vertsA); } if ((vertsB = lightFaceVerticesToTriangles.get(tri.b)) != null) { vertsB.add(tri); } else { vertsB = new ArrayList<Triangle>(); vertsB.add(tri); lightFaceVerticesToTriangles.put(tri.b, vertsB); } if ((vertsC = lightFaceVerticesToTriangles.get(tri.c)) != null) { vertsC.add(tri); } else { vertsC = new ArrayList<Triangle>(); vertsC.add(tri); lightFaceVerticesToTriangles.put(tri.c, vertsC); } facepoints.addAll(listsOfFacePoints.remove(i)); } } // 4.0 Remove all vertices that are only connected to lightFaceVertices Iterator<Integer> iter = lightFaceVertices.iterator(); toRemove.clear(); for (int i = 0; i < lightFaceVertices.size(); i++) { int vert = iter.next(); // TODO: check if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) { toRemove.add(vert); } } for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) { adjacentsMap.get(adj).remove(i); tmppair.set(i, adj); edgesToTriangles.remove(tmppair); } lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert); List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert); for (int j = 0; j < adjs.size(); j++) { Integer currAdj = adjs.get(j); if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) { int tricount = 0; for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) { Triangle kTri = vertexLightTriangles.get(k); if (kTri.a == currAdj || kTri.b == currAdj || kTri.c == currAdj) { tricount++; } } if (tricount == 1) { currentVert = currAdj; break; } } } } // 4.2.1 remove old adjacents (crossing triangle hole) int edgesize = edge.size(); int edgesizeMinusOne = edgesize - 1; for (int i = 0; i < edgesize; i++) { currentVert = edge.get(i); removeAdj.clear(); for (Integer adj : adjacentsMap.get(currentVert)) { if (edge.contains(adj)) { int adjIndexOnEdge = edge.indexOf(adj); if (Math.abs(i - adjIndexOnEdge) > 1 && !(i == 0 && adjIndexOnEdge == edgesizeMinusOne) && !(i == edgesizeMinusOne && adjIndexOnEdge == 0)) { tmppair.set(currentVert, adj); Pair<Triangle, Triangle> edgeTriangles = edgesToTriangles.get(tmppair); // TODO: performance if (lastremovedTriangles.contains(edgeTriangles.getFirst()) && lastremovedTriangles.contains(edgeTriangles.getSecond())) { removeAdj.add(adj); edgesToTriangles.remove(edgeTriangles); } } } } for (Integer removAdjacent : removeAdj) { // TODO: make faster adjacentsMap.get(currentVert).remove(removAdjacent); } } // 4.3 Stitch holes using edge newLightFaces.clear(); ArrayList<Integer> furthestPointNeighbours = new ArrayList<Integer>(edge.size()); A = vertices.get(edge.get(0)); Vector3f B = vertices.get(edge.get(1)); Vector3f C = vertices.get(edge.get(2)); for (int i = 3; i < edge.size() && !linearIndependent(A, B, C); i++) { C = vertices.get(edge.get(i)); } Vector3f normal = VecMath.computeNormal(A, B, C); boolean correctOrientation = VecMath.dotproduct(normal, VecMath.subtraction(A, furthestPoint, tmpvec)) < 0; int vertIDb = edge.get(0); for (int i = 0; i < edge.size(); i++) { int vertIDa = vertIDb; if (i < edge.size() - 1) { vertIDb = edge.get(i + 1); } else { vertIDb = edge.get(0); } Vector3f vA = vertices.get(vertIDa); Vector3f vB = vertices.get(vertIDb); Vector3f norm = VecMath.computeNormal(vA, vB, furthestPoint); Triangle stitchTriangle; if (correctOrientation) { stitchTriangle = new Triangle(vertIDa, vertIDb, furthestPointID, norm); } else { norm.negate(); stitchTriangle = new Triangle(vertIDa, furthestPointID, vertIDb, norm); } faces.add(0, stitchTriangle); newLightFaces.add(stitchTriangle); // Update adjacents map adjacentsMap.get(vertIDa).add(furthestPointID); tmppair.set(vertIDa, vertIDb); Pair<Triangle, Triangle> oldEdgeInfo = edgesToTriangles.get(tmppair); // find out which triangle got deleted if (lastremovedTriangles.contains(oldEdgeInfo.getFirst())) { oldEdgeInfo.setFirst(stitchTriangle); } else { oldEdgeInfo.setSecond(stitchTriangle); } tmppair.set(vertIDa, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { oldEdgeInfo.setSecond(stitchTriangle); } else { // TODO: just relevant for first iteration, move before loop edgesToTriangles.put(new Pair<Integer, Integer>(vertIDa, furthestPointID), new Pair<Triangle, Triangle>(null, stitchTriangle)); } tmppair.set(vertIDb, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { // TODO: just relevant for last iteration oldEdgeInfo.setFirst(stitchTriangle); } else { edgesToTriangles.put(new Pair<Integer, Integer>(vertIDb, furthestPointID), new Pair<Triangle, Triangle>(stitchTriangle, null)); } furthestPointNeighbours.add(vertIDa); } // 5. Assign all points of all light-faces to the new created faces adjacentsMap.put(furthestPointID, furthestPointNeighbours); for (Triangle tri : newLightFaces) { listsOfFacePoints.add(0, getLightPoints(tri, facepoints)); } // 6. Push new created faces on the stack and start at (1)) return false; }
NONSATD
true
} } // 4.0 Remove all vertices that are only connected to lightFaceVertices Iterator<Integer> iter = lightFaceVertices.iterator(); toRemove.clear();
if ((vertsC = lightFaceVerticesToTriangles.get(tri.c)) != null) { vertsC.add(tri); } else { vertsC = new ArrayList<Triangle>(); vertsC.add(tri); lightFaceVerticesToTriangles.put(tri.c, vertsC); } facepoints.addAll(listsOfFacePoints.remove(i)); } } // 4.0 Remove all vertices that are only connected to lightFaceVertices Iterator<Integer> iter = lightFaceVertices.iterator(); toRemove.clear(); for (int i = 0; i < lightFaceVertices.size(); i++) { int vert = iter.next(); // TODO: check if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) { toRemove.add(vert); } } for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) {
vertsA.add(tri); lightFaceVerticesToTriangles.put(tri.a, vertsA); } if ((vertsB = lightFaceVerticesToTriangles.get(tri.b)) != null) { vertsB.add(tri); } else { vertsB = new ArrayList<Triangle>(); vertsB.add(tri); lightFaceVerticesToTriangles.put(tri.b, vertsB); } if ((vertsC = lightFaceVerticesToTriangles.get(tri.c)) != null) { vertsC.add(tri); } else { vertsC = new ArrayList<Triangle>(); vertsC.add(tri); lightFaceVerticesToTriangles.put(tri.c, vertsC); } facepoints.addAll(listsOfFacePoints.remove(i)); } } // 4.0 Remove all vertices that are only connected to lightFaceVertices Iterator<Integer> iter = lightFaceVertices.iterator(); toRemove.clear(); for (int i = 0; i < lightFaceVertices.size(); i++) { int vert = iter.next(); // TODO: check if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) { toRemove.add(vert); } } for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) { adjacentsMap.get(adj).remove(i); tmppair.set(i, adj); edgesToTriangles.remove(tmppair); } lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED
32,108
6
// TODO: check
private static boolean step(int faceIndex) { Triangle t = faces.get(faceIndex); // 2. Get most distant point of the face's point set Vector3f furthestPoint = null; int furthestPointID = -1; Vector3f A = vertices.get(t.a); List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear(); lightFaceVerticesToTriangles.put(t.a, vertsA); lightFaceVerticesToTriangles.put(t.b, vertsB); lightFaceVerticesToTriangles.put(t.c, vertsC); for (int i = faces.size() - 1; i >= 0; i--) { Triangle tri = faces.get(i); Vector3f triA = vertices.get(tri.a); if (VecMath.dotproduct(tri.normal, VecMath.subtraction(furthestPoint, triA, tmpvec)) > 0) { lastremovedTriangles.add(faces.remove(i)); lightFaceVertices.add(tri.a); lightFaceVertices.add(tri.b); lightFaceVertices.add(tri.c); if ((vertsA = lightFaceVerticesToTriangles.get(tri.a)) != null) { vertsA.add(tri); } else { vertsA = new ArrayList<Triangle>(); vertsA.add(tri); lightFaceVerticesToTriangles.put(tri.a, vertsA); } if ((vertsB = lightFaceVerticesToTriangles.get(tri.b)) != null) { vertsB.add(tri); } else { vertsB = new ArrayList<Triangle>(); vertsB.add(tri); lightFaceVerticesToTriangles.put(tri.b, vertsB); } if ((vertsC = lightFaceVerticesToTriangles.get(tri.c)) != null) { vertsC.add(tri); } else { vertsC = new ArrayList<Triangle>(); vertsC.add(tri); lightFaceVerticesToTriangles.put(tri.c, vertsC); } facepoints.addAll(listsOfFacePoints.remove(i)); } } // 4.0 Remove all vertices that are only connected to lightFaceVertices Iterator<Integer> iter = lightFaceVertices.iterator(); toRemove.clear(); for (int i = 0; i < lightFaceVertices.size(); i++) { int vert = iter.next(); // TODO: check if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) { toRemove.add(vert); } } for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) { adjacentsMap.get(adj).remove(i); tmppair.set(i, adj); edgesToTriangles.remove(tmppair); } lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert); List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert); for (int j = 0; j < adjs.size(); j++) { Integer currAdj = adjs.get(j); if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) { int tricount = 0; for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) { Triangle kTri = vertexLightTriangles.get(k); if (kTri.a == currAdj || kTri.b == currAdj || kTri.c == currAdj) { tricount++; } } if (tricount == 1) { currentVert = currAdj; break; } } } } // 4.2.1 remove old adjacents (crossing triangle hole) int edgesize = edge.size(); int edgesizeMinusOne = edgesize - 1; for (int i = 0; i < edgesize; i++) { currentVert = edge.get(i); removeAdj.clear(); for (Integer adj : adjacentsMap.get(currentVert)) { if (edge.contains(adj)) { int adjIndexOnEdge = edge.indexOf(adj); if (Math.abs(i - adjIndexOnEdge) > 1 && !(i == 0 && adjIndexOnEdge == edgesizeMinusOne) && !(i == edgesizeMinusOne && adjIndexOnEdge == 0)) { tmppair.set(currentVert, adj); Pair<Triangle, Triangle> edgeTriangles = edgesToTriangles.get(tmppair); // TODO: performance if (lastremovedTriangles.contains(edgeTriangles.getFirst()) && lastremovedTriangles.contains(edgeTriangles.getSecond())) { removeAdj.add(adj); edgesToTriangles.remove(edgeTriangles); } } } } for (Integer removAdjacent : removeAdj) { // TODO: make faster adjacentsMap.get(currentVert).remove(removAdjacent); } } // 4.3 Stitch holes using edge newLightFaces.clear(); ArrayList<Integer> furthestPointNeighbours = new ArrayList<Integer>(edge.size()); A = vertices.get(edge.get(0)); Vector3f B = vertices.get(edge.get(1)); Vector3f C = vertices.get(edge.get(2)); for (int i = 3; i < edge.size() && !linearIndependent(A, B, C); i++) { C = vertices.get(edge.get(i)); } Vector3f normal = VecMath.computeNormal(A, B, C); boolean correctOrientation = VecMath.dotproduct(normal, VecMath.subtraction(A, furthestPoint, tmpvec)) < 0; int vertIDb = edge.get(0); for (int i = 0; i < edge.size(); i++) { int vertIDa = vertIDb; if (i < edge.size() - 1) { vertIDb = edge.get(i + 1); } else { vertIDb = edge.get(0); } Vector3f vA = vertices.get(vertIDa); Vector3f vB = vertices.get(vertIDb); Vector3f norm = VecMath.computeNormal(vA, vB, furthestPoint); Triangle stitchTriangle; if (correctOrientation) { stitchTriangle = new Triangle(vertIDa, vertIDb, furthestPointID, norm); } else { norm.negate(); stitchTriangle = new Triangle(vertIDa, furthestPointID, vertIDb, norm); } faces.add(0, stitchTriangle); newLightFaces.add(stitchTriangle); // Update adjacents map adjacentsMap.get(vertIDa).add(furthestPointID); tmppair.set(vertIDa, vertIDb); Pair<Triangle, Triangle> oldEdgeInfo = edgesToTriangles.get(tmppair); // find out which triangle got deleted if (lastremovedTriangles.contains(oldEdgeInfo.getFirst())) { oldEdgeInfo.setFirst(stitchTriangle); } else { oldEdgeInfo.setSecond(stitchTriangle); } tmppair.set(vertIDa, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { oldEdgeInfo.setSecond(stitchTriangle); } else { // TODO: just relevant for first iteration, move before loop edgesToTriangles.put(new Pair<Integer, Integer>(vertIDa, furthestPointID), new Pair<Triangle, Triangle>(null, stitchTriangle)); } tmppair.set(vertIDb, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { // TODO: just relevant for last iteration oldEdgeInfo.setFirst(stitchTriangle); } else { edgesToTriangles.put(new Pair<Integer, Integer>(vertIDb, furthestPointID), new Pair<Triangle, Triangle>(stitchTriangle, null)); } furthestPointNeighbours.add(vertIDa); } // 5. Assign all points of all light-faces to the new created faces adjacentsMap.put(furthestPointID, furthestPointNeighbours); for (Triangle tri : newLightFaces) { listsOfFacePoints.add(0, getLightPoints(tri, facepoints)); } // 6. Push new created faces on the stack and start at (1)) return false; }
NONSATD
true
} } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; }
float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why.
private static boolean step(int faceIndex) { Triangle t = faces.get(faceIndex); // 2. Get most distant point of the face's point set Vector3f furthestPoint = null; int furthestPointID = -1; Vector3f A = vertices.get(t.a); List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear();
32,108
7
// 4.1 Get vertices on border between lit and unlit triangles
private static boolean step(int faceIndex) { Triangle t = faces.get(faceIndex); // 2. Get most distant point of the face's point set Vector3f furthestPoint = null; int furthestPointID = -1; Vector3f A = vertices.get(t.a); List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear(); lightFaceVerticesToTriangles.put(t.a, vertsA); lightFaceVerticesToTriangles.put(t.b, vertsB); lightFaceVerticesToTriangles.put(t.c, vertsC); for (int i = faces.size() - 1; i >= 0; i--) { Triangle tri = faces.get(i); Vector3f triA = vertices.get(tri.a); if (VecMath.dotproduct(tri.normal, VecMath.subtraction(furthestPoint, triA, tmpvec)) > 0) { lastremovedTriangles.add(faces.remove(i)); lightFaceVertices.add(tri.a); lightFaceVertices.add(tri.b); lightFaceVertices.add(tri.c); if ((vertsA = lightFaceVerticesToTriangles.get(tri.a)) != null) { vertsA.add(tri); } else { vertsA = new ArrayList<Triangle>(); vertsA.add(tri); lightFaceVerticesToTriangles.put(tri.a, vertsA); } if ((vertsB = lightFaceVerticesToTriangles.get(tri.b)) != null) { vertsB.add(tri); } else { vertsB = new ArrayList<Triangle>(); vertsB.add(tri); lightFaceVerticesToTriangles.put(tri.b, vertsB); } if ((vertsC = lightFaceVerticesToTriangles.get(tri.c)) != null) { vertsC.add(tri); } else { vertsC = new ArrayList<Triangle>(); vertsC.add(tri); lightFaceVerticesToTriangles.put(tri.c, vertsC); } facepoints.addAll(listsOfFacePoints.remove(i)); } } // 4.0 Remove all vertices that are only connected to lightFaceVertices Iterator<Integer> iter = lightFaceVertices.iterator(); toRemove.clear(); for (int i = 0; i < lightFaceVertices.size(); i++) { int vert = iter.next(); // TODO: check if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) { toRemove.add(vert); } } for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) { adjacentsMap.get(adj).remove(i); tmppair.set(i, adj); edgesToTriangles.remove(tmppair); } lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert); List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert); for (int j = 0; j < adjs.size(); j++) { Integer currAdj = adjs.get(j); if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) { int tricount = 0; for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) { Triangle kTri = vertexLightTriangles.get(k); if (kTri.a == currAdj || kTri.b == currAdj || kTri.c == currAdj) { tricount++; } } if (tricount == 1) { currentVert = currAdj; break; } } } } // 4.2.1 remove old adjacents (crossing triangle hole) int edgesize = edge.size(); int edgesizeMinusOne = edgesize - 1; for (int i = 0; i < edgesize; i++) { currentVert = edge.get(i); removeAdj.clear(); for (Integer adj : adjacentsMap.get(currentVert)) { if (edge.contains(adj)) { int adjIndexOnEdge = edge.indexOf(adj); if (Math.abs(i - adjIndexOnEdge) > 1 && !(i == 0 && adjIndexOnEdge == edgesizeMinusOne) && !(i == edgesizeMinusOne && adjIndexOnEdge == 0)) { tmppair.set(currentVert, adj); Pair<Triangle, Triangle> edgeTriangles = edgesToTriangles.get(tmppair); // TODO: performance if (lastremovedTriangles.contains(edgeTriangles.getFirst()) && lastremovedTriangles.contains(edgeTriangles.getSecond())) { removeAdj.add(adj); edgesToTriangles.remove(edgeTriangles); } } } } for (Integer removAdjacent : removeAdj) { // TODO: make faster adjacentsMap.get(currentVert).remove(removAdjacent); } } // 4.3 Stitch holes using edge newLightFaces.clear(); ArrayList<Integer> furthestPointNeighbours = new ArrayList<Integer>(edge.size()); A = vertices.get(edge.get(0)); Vector3f B = vertices.get(edge.get(1)); Vector3f C = vertices.get(edge.get(2)); for (int i = 3; i < edge.size() && !linearIndependent(A, B, C); i++) { C = vertices.get(edge.get(i)); } Vector3f normal = VecMath.computeNormal(A, B, C); boolean correctOrientation = VecMath.dotproduct(normal, VecMath.subtraction(A, furthestPoint, tmpvec)) < 0; int vertIDb = edge.get(0); for (int i = 0; i < edge.size(); i++) { int vertIDa = vertIDb; if (i < edge.size() - 1) { vertIDb = edge.get(i + 1); } else { vertIDb = edge.get(0); } Vector3f vA = vertices.get(vertIDa); Vector3f vB = vertices.get(vertIDb); Vector3f norm = VecMath.computeNormal(vA, vB, furthestPoint); Triangle stitchTriangle; if (correctOrientation) { stitchTriangle = new Triangle(vertIDa, vertIDb, furthestPointID, norm); } else { norm.negate(); stitchTriangle = new Triangle(vertIDa, furthestPointID, vertIDb, norm); } faces.add(0, stitchTriangle); newLightFaces.add(stitchTriangle); // Update adjacents map adjacentsMap.get(vertIDa).add(furthestPointID); tmppair.set(vertIDa, vertIDb); Pair<Triangle, Triangle> oldEdgeInfo = edgesToTriangles.get(tmppair); // find out which triangle got deleted if (lastremovedTriangles.contains(oldEdgeInfo.getFirst())) { oldEdgeInfo.setFirst(stitchTriangle); } else { oldEdgeInfo.setSecond(stitchTriangle); } tmppair.set(vertIDa, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { oldEdgeInfo.setSecond(stitchTriangle); } else { // TODO: just relevant for first iteration, move before loop edgesToTriangles.put(new Pair<Integer, Integer>(vertIDa, furthestPointID), new Pair<Triangle, Triangle>(null, stitchTriangle)); } tmppair.set(vertIDb, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { // TODO: just relevant for last iteration oldEdgeInfo.setFirst(stitchTriangle); } else { edgesToTriangles.put(new Pair<Integer, Integer>(vertIDb, furthestPointID), new Pair<Triangle, Triangle>(stitchTriangle, null)); } furthestPointNeighbours.add(vertIDa); } // 5. Assign all points of all light-faces to the new created faces adjacentsMap.put(furthestPointID, furthestPointNeighbours); for (Triangle tri : newLightFaces) { listsOfFacePoints.add(0, getLightPoints(tri, facepoints)); } // 6. Push new created faces on the stack and start at (1)) return false; }
NONSATD
true
freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) {
for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) { adjacentsMap.get(adj).remove(i); tmppair.set(i, adj); edgesToTriangles.remove(tmppair); } lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert);
} // 4.0 Remove all vertices that are only connected to lightFaceVertices Iterator<Integer> iter = lightFaceVertices.iterator(); toRemove.clear(); for (int i = 0; i < lightFaceVertices.size(); i++) { int vert = iter.next(); // TODO: check if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) { toRemove.add(vert); } } for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) { adjacentsMap.get(adj).remove(i); tmppair.set(i, adj); edgesToTriangles.remove(tmppair); } lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert); List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert); for (int j = 0; j < adjs.size(); j++) { Integer currAdj = adjs.get(j); if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) { int tricount = 0; for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) { Triangle kTri = vertexLightTriangles.get(k); if (kTri.a == currAdj || kTri.b == currAdj || kTri.c == currAdj) { tricount++; }
32,108
8
// HAS TO BE REINITIALIZED
private static boolean step(int faceIndex) { Triangle t = faces.get(faceIndex); // 2. Get most distant point of the face's point set Vector3f furthestPoint = null; int furthestPointID = -1; Vector3f A = vertices.get(t.a); List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear(); lightFaceVerticesToTriangles.put(t.a, vertsA); lightFaceVerticesToTriangles.put(t.b, vertsB); lightFaceVerticesToTriangles.put(t.c, vertsC); for (int i = faces.size() - 1; i >= 0; i--) { Triangle tri = faces.get(i); Vector3f triA = vertices.get(tri.a); if (VecMath.dotproduct(tri.normal, VecMath.subtraction(furthestPoint, triA, tmpvec)) > 0) { lastremovedTriangles.add(faces.remove(i)); lightFaceVertices.add(tri.a); lightFaceVertices.add(tri.b); lightFaceVertices.add(tri.c); if ((vertsA = lightFaceVerticesToTriangles.get(tri.a)) != null) { vertsA.add(tri); } else { vertsA = new ArrayList<Triangle>(); vertsA.add(tri); lightFaceVerticesToTriangles.put(tri.a, vertsA); } if ((vertsB = lightFaceVerticesToTriangles.get(tri.b)) != null) { vertsB.add(tri); } else { vertsB = new ArrayList<Triangle>(); vertsB.add(tri); lightFaceVerticesToTriangles.put(tri.b, vertsB); } if ((vertsC = lightFaceVerticesToTriangles.get(tri.c)) != null) { vertsC.add(tri); } else { vertsC = new ArrayList<Triangle>(); vertsC.add(tri); lightFaceVerticesToTriangles.put(tri.c, vertsC); } facepoints.addAll(listsOfFacePoints.remove(i)); } } // 4.0 Remove all vertices that are only connected to lightFaceVertices Iterator<Integer> iter = lightFaceVertices.iterator(); toRemove.clear(); for (int i = 0; i < lightFaceVertices.size(); i++) { int vert = iter.next(); // TODO: check if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) { toRemove.add(vert); } } for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) { adjacentsMap.get(adj).remove(i); tmppair.set(i, adj); edgesToTriangles.remove(tmppair); } lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert); List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert); for (int j = 0; j < adjs.size(); j++) { Integer currAdj = adjs.get(j); if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) { int tricount = 0; for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) { Triangle kTri = vertexLightTriangles.get(k); if (kTri.a == currAdj || kTri.b == currAdj || kTri.c == currAdj) { tricount++; } } if (tricount == 1) { currentVert = currAdj; break; } } } } // 4.2.1 remove old adjacents (crossing triangle hole) int edgesize = edge.size(); int edgesizeMinusOne = edgesize - 1; for (int i = 0; i < edgesize; i++) { currentVert = edge.get(i); removeAdj.clear(); for (Integer adj : adjacentsMap.get(currentVert)) { if (edge.contains(adj)) { int adjIndexOnEdge = edge.indexOf(adj); if (Math.abs(i - adjIndexOnEdge) > 1 && !(i == 0 && adjIndexOnEdge == edgesizeMinusOne) && !(i == edgesizeMinusOne && adjIndexOnEdge == 0)) { tmppair.set(currentVert, adj); Pair<Triangle, Triangle> edgeTriangles = edgesToTriangles.get(tmppair); // TODO: performance if (lastremovedTriangles.contains(edgeTriangles.getFirst()) && lastremovedTriangles.contains(edgeTriangles.getSecond())) { removeAdj.add(adj); edgesToTriangles.remove(edgeTriangles); } } } } for (Integer removAdjacent : removeAdj) { // TODO: make faster adjacentsMap.get(currentVert).remove(removAdjacent); } } // 4.3 Stitch holes using edge newLightFaces.clear(); ArrayList<Integer> furthestPointNeighbours = new ArrayList<Integer>(edge.size()); A = vertices.get(edge.get(0)); Vector3f B = vertices.get(edge.get(1)); Vector3f C = vertices.get(edge.get(2)); for (int i = 3; i < edge.size() && !linearIndependent(A, B, C); i++) { C = vertices.get(edge.get(i)); } Vector3f normal = VecMath.computeNormal(A, B, C); boolean correctOrientation = VecMath.dotproduct(normal, VecMath.subtraction(A, furthestPoint, tmpvec)) < 0; int vertIDb = edge.get(0); for (int i = 0; i < edge.size(); i++) { int vertIDa = vertIDb; if (i < edge.size() - 1) { vertIDb = edge.get(i + 1); } else { vertIDb = edge.get(0); } Vector3f vA = vertices.get(vertIDa); Vector3f vB = vertices.get(vertIDb); Vector3f norm = VecMath.computeNormal(vA, vB, furthestPoint); Triangle stitchTriangle; if (correctOrientation) { stitchTriangle = new Triangle(vertIDa, vertIDb, furthestPointID, norm); } else { norm.negate(); stitchTriangle = new Triangle(vertIDa, furthestPointID, vertIDb, norm); } faces.add(0, stitchTriangle); newLightFaces.add(stitchTriangle); // Update adjacents map adjacentsMap.get(vertIDa).add(furthestPointID); tmppair.set(vertIDa, vertIDb); Pair<Triangle, Triangle> oldEdgeInfo = edgesToTriangles.get(tmppair); // find out which triangle got deleted if (lastremovedTriangles.contains(oldEdgeInfo.getFirst())) { oldEdgeInfo.setFirst(stitchTriangle); } else { oldEdgeInfo.setSecond(stitchTriangle); } tmppair.set(vertIDa, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { oldEdgeInfo.setSecond(stitchTriangle); } else { // TODO: just relevant for first iteration, move before loop edgesToTriangles.put(new Pair<Integer, Integer>(vertIDa, furthestPointID), new Pair<Triangle, Triangle>(null, stitchTriangle)); } tmppair.set(vertIDb, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { // TODO: just relevant for last iteration oldEdgeInfo.setFirst(stitchTriangle); } else { edgesToTriangles.put(new Pair<Integer, Integer>(vertIDb, furthestPointID), new Pair<Triangle, Triangle>(stitchTriangle, null)); } furthestPointNeighbours.add(vertIDa); } // 5. Assign all points of all light-faces to the new created faces adjacentsMap.put(furthestPointID, furthestPointNeighbours); for (Triangle tri : newLightFaces) { listsOfFacePoints.add(0, getLightPoints(tri, facepoints)); } // 6. Push new created faces on the stack and start at (1)) return false; }
DESIGN
true
listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b);
if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear();
float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear(); lightFaceVerticesToTriangles.put(t.a, vertsA); lightFaceVerticesToTriangles.put(t.b, vertsB); lightFaceVerticesToTriangles.put(t.c, vertsC); for (int i = faces.size() - 1; i >= 0; i--) { Triangle tri = faces.get(i); Vector3f triA = vertices.get(tri.a); if (VecMath.dotproduct(tri.normal, VecMath.subtraction(furthestPoint, triA, tmpvec)) > 0) { lastremovedTriangles.add(faces.remove(i)); lightFaceVertices.add(tri.a); lightFaceVertices.add(tri.b);
32,108
9
// 4.2 Get edges on border
private static boolean step(int faceIndex) { Triangle t = faces.get(faceIndex); // 2. Get most distant point of the face's point set Vector3f furthestPoint = null; int furthestPointID = -1; Vector3f A = vertices.get(t.a); List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear(); lightFaceVerticesToTriangles.put(t.a, vertsA); lightFaceVerticesToTriangles.put(t.b, vertsB); lightFaceVerticesToTriangles.put(t.c, vertsC); for (int i = faces.size() - 1; i >= 0; i--) { Triangle tri = faces.get(i); Vector3f triA = vertices.get(tri.a); if (VecMath.dotproduct(tri.normal, VecMath.subtraction(furthestPoint, triA, tmpvec)) > 0) { lastremovedTriangles.add(faces.remove(i)); lightFaceVertices.add(tri.a); lightFaceVertices.add(tri.b); lightFaceVertices.add(tri.c); if ((vertsA = lightFaceVerticesToTriangles.get(tri.a)) != null) { vertsA.add(tri); } else { vertsA = new ArrayList<Triangle>(); vertsA.add(tri); lightFaceVerticesToTriangles.put(tri.a, vertsA); } if ((vertsB = lightFaceVerticesToTriangles.get(tri.b)) != null) { vertsB.add(tri); } else { vertsB = new ArrayList<Triangle>(); vertsB.add(tri); lightFaceVerticesToTriangles.put(tri.b, vertsB); } if ((vertsC = lightFaceVerticesToTriangles.get(tri.c)) != null) { vertsC.add(tri); } else { vertsC = new ArrayList<Triangle>(); vertsC.add(tri); lightFaceVerticesToTriangles.put(tri.c, vertsC); } facepoints.addAll(listsOfFacePoints.remove(i)); } } // 4.0 Remove all vertices that are only connected to lightFaceVertices Iterator<Integer> iter = lightFaceVertices.iterator(); toRemove.clear(); for (int i = 0; i < lightFaceVertices.size(); i++) { int vert = iter.next(); // TODO: check if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) { toRemove.add(vert); } } for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) { adjacentsMap.get(adj).remove(i); tmppair.set(i, adj); edgesToTriangles.remove(tmppair); } lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert); List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert); for (int j = 0; j < adjs.size(); j++) { Integer currAdj = adjs.get(j); if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) { int tricount = 0; for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) { Triangle kTri = vertexLightTriangles.get(k); if (kTri.a == currAdj || kTri.b == currAdj || kTri.c == currAdj) { tricount++; } } if (tricount == 1) { currentVert = currAdj; break; } } } } // 4.2.1 remove old adjacents (crossing triangle hole) int edgesize = edge.size(); int edgesizeMinusOne = edgesize - 1; for (int i = 0; i < edgesize; i++) { currentVert = edge.get(i); removeAdj.clear(); for (Integer adj : adjacentsMap.get(currentVert)) { if (edge.contains(adj)) { int adjIndexOnEdge = edge.indexOf(adj); if (Math.abs(i - adjIndexOnEdge) > 1 && !(i == 0 && adjIndexOnEdge == edgesizeMinusOne) && !(i == edgesizeMinusOne && adjIndexOnEdge == 0)) { tmppair.set(currentVert, adj); Pair<Triangle, Triangle> edgeTriangles = edgesToTriangles.get(tmppair); // TODO: performance if (lastremovedTriangles.contains(edgeTriangles.getFirst()) && lastremovedTriangles.contains(edgeTriangles.getSecond())) { removeAdj.add(adj); edgesToTriangles.remove(edgeTriangles); } } } } for (Integer removAdjacent : removeAdj) { // TODO: make faster adjacentsMap.get(currentVert).remove(removAdjacent); } } // 4.3 Stitch holes using edge newLightFaces.clear(); ArrayList<Integer> furthestPointNeighbours = new ArrayList<Integer>(edge.size()); A = vertices.get(edge.get(0)); Vector3f B = vertices.get(edge.get(1)); Vector3f C = vertices.get(edge.get(2)); for (int i = 3; i < edge.size() && !linearIndependent(A, B, C); i++) { C = vertices.get(edge.get(i)); } Vector3f normal = VecMath.computeNormal(A, B, C); boolean correctOrientation = VecMath.dotproduct(normal, VecMath.subtraction(A, furthestPoint, tmpvec)) < 0; int vertIDb = edge.get(0); for (int i = 0; i < edge.size(); i++) { int vertIDa = vertIDb; if (i < edge.size() - 1) { vertIDb = edge.get(i + 1); } else { vertIDb = edge.get(0); } Vector3f vA = vertices.get(vertIDa); Vector3f vB = vertices.get(vertIDb); Vector3f norm = VecMath.computeNormal(vA, vB, furthestPoint); Triangle stitchTriangle; if (correctOrientation) { stitchTriangle = new Triangle(vertIDa, vertIDb, furthestPointID, norm); } else { norm.negate(); stitchTriangle = new Triangle(vertIDa, furthestPointID, vertIDb, norm); } faces.add(0, stitchTriangle); newLightFaces.add(stitchTriangle); // Update adjacents map adjacentsMap.get(vertIDa).add(furthestPointID); tmppair.set(vertIDa, vertIDb); Pair<Triangle, Triangle> oldEdgeInfo = edgesToTriangles.get(tmppair); // find out which triangle got deleted if (lastremovedTriangles.contains(oldEdgeInfo.getFirst())) { oldEdgeInfo.setFirst(stitchTriangle); } else { oldEdgeInfo.setSecond(stitchTriangle); } tmppair.set(vertIDa, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { oldEdgeInfo.setSecond(stitchTriangle); } else { // TODO: just relevant for first iteration, move before loop edgesToTriangles.put(new Pair<Integer, Integer>(vertIDa, furthestPointID), new Pair<Triangle, Triangle>(null, stitchTriangle)); } tmppair.set(vertIDb, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { // TODO: just relevant for last iteration oldEdgeInfo.setFirst(stitchTriangle); } else { edgesToTriangles.put(new Pair<Integer, Integer>(vertIDb, furthestPointID), new Pair<Triangle, Triangle>(stitchTriangle, null)); } furthestPointNeighbours.add(vertIDa); } // 5. Assign all points of all light-faces to the new created faces adjacentsMap.put(furthestPointID, furthestPointNeighbours); for (Triangle tri : newLightFaces) { listsOfFacePoints.add(0, getLightPoints(tri, facepoints)); } // 6. Push new created faces on the stack and start at (1)) return false; }
NONSATD
true
vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!)
} lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert); List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert); for (int j = 0; j < adjs.size(); j++) { Integer currAdj = adjs.get(j); if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) { int tricount = 0;
int vert = iter.next(); // TODO: check if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) { toRemove.add(vert); } } for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) { adjacentsMap.get(adj).remove(i); tmppair.set(i, adj); edgesToTriangles.remove(tmppair); } lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert); List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert); for (int j = 0; j < adjs.size(); j++) { Integer currAdj = adjs.get(j); if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) { int tricount = 0; for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) { Triangle kTri = vertexLightTriangles.get(k); if (kTri.a == currAdj || kTri.b == currAdj || kTri.c == currAdj) { tricount++; } } if (tricount == 1) { currentVert = currAdj; break; }
32,108
10
// TODO: make HashSet (no! has to be ordered list!)
private static boolean step(int faceIndex) { Triangle t = faces.get(faceIndex); // 2. Get most distant point of the face's point set Vector3f furthestPoint = null; int furthestPointID = -1; Vector3f A = vertices.get(t.a); List<Vector3f> facepoints = listsOfFacePoints.get(faceIndex); float distance = 0; for (int i = 0; i < facepoints.size(); i++) { Vector3f P = facepoints.get(i); float dist = VecMath.dotproduct(VecMath.subtraction(P, A, tmpvec), t.normal); if (dist >= distance) { distance = dist; furthestPoint = P; furthestPointID = i; } } if (furthestPointID == -1 || vertices.contains(furthestPoint)) { // TODO: check return true; } facepoints.remove(furthestPointID); vertices.add(furthestPoint); furthestPointID = vertices.size() - 1; lastremovedTriangles.clear(); lastremovedTriangles.add(faces.remove(faceIndex)); listsOfFacePoints.remove(faceIndex); // 3. Find all faces that can be seen from this point HashSet<Integer> lightFaceVertices = new HashSet<Integer>(); // HAS TO BE REINITIALIZED... don't ask why. lightFaceVertices.add(t.a); lightFaceVertices.add(t.b); lightFaceVertices.add(t.c); List<Triangle> vertsA = new ArrayList<Triangle>(); List<Triangle> vertsB = new ArrayList<Triangle>(); List<Triangle> vertsC = new ArrayList<Triangle>(); vertsA.add(t); vertsB.add(t); vertsC.add(t); lightFaceVerticesToTriangles.clear(); lightFaceVerticesToTriangles.put(t.a, vertsA); lightFaceVerticesToTriangles.put(t.b, vertsB); lightFaceVerticesToTriangles.put(t.c, vertsC); for (int i = faces.size() - 1; i >= 0; i--) { Triangle tri = faces.get(i); Vector3f triA = vertices.get(tri.a); if (VecMath.dotproduct(tri.normal, VecMath.subtraction(furthestPoint, triA, tmpvec)) > 0) { lastremovedTriangles.add(faces.remove(i)); lightFaceVertices.add(tri.a); lightFaceVertices.add(tri.b); lightFaceVertices.add(tri.c); if ((vertsA = lightFaceVerticesToTriangles.get(tri.a)) != null) { vertsA.add(tri); } else { vertsA = new ArrayList<Triangle>(); vertsA.add(tri); lightFaceVerticesToTriangles.put(tri.a, vertsA); } if ((vertsB = lightFaceVerticesToTriangles.get(tri.b)) != null) { vertsB.add(tri); } else { vertsB = new ArrayList<Triangle>(); vertsB.add(tri); lightFaceVerticesToTriangles.put(tri.b, vertsB); } if ((vertsC = lightFaceVerticesToTriangles.get(tri.c)) != null) { vertsC.add(tri); } else { vertsC = new ArrayList<Triangle>(); vertsC.add(tri); lightFaceVerticesToTriangles.put(tri.c, vertsC); } facepoints.addAll(listsOfFacePoints.remove(i)); } } // 4.0 Remove all vertices that are only connected to lightFaceVertices Iterator<Integer> iter = lightFaceVertices.iterator(); toRemove.clear(); for (int i = 0; i < lightFaceVertices.size(); i++) { int vert = iter.next(); // TODO: check if (lightFaceVerticesToTriangles.get(vert).size() == adjacentsMap.get(vert).size()) { toRemove.add(vert); } } for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) { adjacentsMap.get(adj).remove(i); tmppair.set(i, adj); edgesToTriangles.remove(tmppair); } lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert); List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert); for (int j = 0; j < adjs.size(); j++) { Integer currAdj = adjs.get(j); if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) { int tricount = 0; for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) { Triangle kTri = vertexLightTriangles.get(k); if (kTri.a == currAdj || kTri.b == currAdj || kTri.c == currAdj) { tricount++; } } if (tricount == 1) { currentVert = currAdj; break; } } } } // 4.2.1 remove old adjacents (crossing triangle hole) int edgesize = edge.size(); int edgesizeMinusOne = edgesize - 1; for (int i = 0; i < edgesize; i++) { currentVert = edge.get(i); removeAdj.clear(); for (Integer adj : adjacentsMap.get(currentVert)) { if (edge.contains(adj)) { int adjIndexOnEdge = edge.indexOf(adj); if (Math.abs(i - adjIndexOnEdge) > 1 && !(i == 0 && adjIndexOnEdge == edgesizeMinusOne) && !(i == edgesizeMinusOne && adjIndexOnEdge == 0)) { tmppair.set(currentVert, adj); Pair<Triangle, Triangle> edgeTriangles = edgesToTriangles.get(tmppair); // TODO: performance if (lastremovedTriangles.contains(edgeTriangles.getFirst()) && lastremovedTriangles.contains(edgeTriangles.getSecond())) { removeAdj.add(adj); edgesToTriangles.remove(edgeTriangles); } } } } for (Integer removAdjacent : removeAdj) { // TODO: make faster adjacentsMap.get(currentVert).remove(removAdjacent); } } // 4.3 Stitch holes using edge newLightFaces.clear(); ArrayList<Integer> furthestPointNeighbours = new ArrayList<Integer>(edge.size()); A = vertices.get(edge.get(0)); Vector3f B = vertices.get(edge.get(1)); Vector3f C = vertices.get(edge.get(2)); for (int i = 3; i < edge.size() && !linearIndependent(A, B, C); i++) { C = vertices.get(edge.get(i)); } Vector3f normal = VecMath.computeNormal(A, B, C); boolean correctOrientation = VecMath.dotproduct(normal, VecMath.subtraction(A, furthestPoint, tmpvec)) < 0; int vertIDb = edge.get(0); for (int i = 0; i < edge.size(); i++) { int vertIDa = vertIDb; if (i < edge.size() - 1) { vertIDb = edge.get(i + 1); } else { vertIDb = edge.get(0); } Vector3f vA = vertices.get(vertIDa); Vector3f vB = vertices.get(vertIDb); Vector3f norm = VecMath.computeNormal(vA, vB, furthestPoint); Triangle stitchTriangle; if (correctOrientation) { stitchTriangle = new Triangle(vertIDa, vertIDb, furthestPointID, norm); } else { norm.negate(); stitchTriangle = new Triangle(vertIDa, furthestPointID, vertIDb, norm); } faces.add(0, stitchTriangle); newLightFaces.add(stitchTriangle); // Update adjacents map adjacentsMap.get(vertIDa).add(furthestPointID); tmppair.set(vertIDa, vertIDb); Pair<Triangle, Triangle> oldEdgeInfo = edgesToTriangles.get(tmppair); // find out which triangle got deleted if (lastremovedTriangles.contains(oldEdgeInfo.getFirst())) { oldEdgeInfo.setFirst(stitchTriangle); } else { oldEdgeInfo.setSecond(stitchTriangle); } tmppair.set(vertIDa, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { oldEdgeInfo.setSecond(stitchTriangle); } else { // TODO: just relevant for first iteration, move before loop edgesToTriangles.put(new Pair<Integer, Integer>(vertIDa, furthestPointID), new Pair<Triangle, Triangle>(null, stitchTriangle)); } tmppair.set(vertIDb, furthestPointID); oldEdgeInfo = edgesToTriangles.get(tmppair); if (oldEdgeInfo != null) { // TODO: just relevant for last iteration oldEdgeInfo.setFirst(stitchTriangle); } else { edgesToTriangles.put(new Pair<Integer, Integer>(vertIDb, furthestPointID), new Pair<Triangle, Triangle>(stitchTriangle, null)); } furthestPointNeighbours.add(vertIDa); } // 5. Assign all points of all light-faces to the new created faces adjacentsMap.put(furthestPointID, furthestPointNeighbours); for (Triangle tri : newLightFaces) { listsOfFacePoints.add(0, getLightPoints(tri, facepoints)); } // 6. Push new created faces on the stack and start at (1)) return false; }
DESIGN
true
// 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert);
vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert); List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert); for (int j = 0; j < adjs.size(); j++) { Integer currAdj = adjs.get(j); if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) { int tricount = 0; for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) { Triangle kTri = vertexLightTriangles.get(k);
toRemove.add(vert); } } for (Integer i : toRemove) { for (Integer adj : adjacentsMap.get(i)) { adjacentsMap.get(adj).remove(i); tmppair.set(i, adj); edgesToTriangles.remove(tmppair); } lightFaceVertices.remove((int) i); vertices.set((int) i, null); freeVertexPositions.add(i); } // 4.1 Get vertices on border between lit and unlit triangles HashSet<Integer> vertsOnEdge = new HashSet<Integer>(); // HAS TO BE REINITIALIZED for (Integer vert : lightFaceVertices) { vertsOnEdge.add(vert); } // 4.2 Get edges on border int currentVert = vertsOnEdge.iterator().next(); edge.clear(); // TODO: make HashSet (no! has to be ordered list!) for (int i = 0; i < vertsOnEdge.size(); i++) { edge.add(currentVert); ArrayList<Integer> adjs = adjacentsMap.get(currentVert); List<Triangle> vertexLightTriangles = lightFaceVerticesToTriangles.get(currentVert); for (int j = 0; j < adjs.size(); j++) { Integer currAdj = adjs.get(j); if (vertsOnEdge.contains(currAdj) && !edge.contains(currAdj)) { int tricount = 0; for (int k = 0; k < vertexLightTriangles.size() && tricount < 2; k++) { Triangle kTri = vertexLightTriangles.get(k); if (kTri.a == currAdj || kTri.b == currAdj || kTri.c == currAdj) { tricount++; } } if (tricount == 1) { currentVert = currAdj; break; } } }