src/strip.vala
[app.mailtrimmer] / src / strip.vala
1 /**
2
3   needs to scan 2 things
4   a) our mailfort email database
5        point it at the top directory, containing YEAR/MONTH/DAY.... directories.
6        scan each file (over a year old...)
7        extract out the attachment, and replace with HTML
8        DATABASE? - mysql or sqlite? - 
9            filesize / name / date / checksum / mimetype -- into mailfort should be OK.
10   b) the imap user emails
11            loop through user's directories
12            check age of email .. over 1 years..
13            ?? how to prevent 'repeat' scanning of emails?
14               ??? hidden '.' files containing last scan date?
15
16            check if file exists in our DB.. - replace the link...
17            otherwise generate a file. + add to DB...
18            
19    c) retreival system
20      -> URL -> get file
21    d) redirect system.
22      -> URL -> redirect to correct server
23
24
25 More notes on our Mailfort DB sync:
26 * some of these attachments are already in the database...
27  - so we need to update the DB..
28  - probably worth putting the code in a stored procedure..
29  
30  -- key scenarios
31    * first scan (and extract)
32    * rescan (as I messed up the first time - fix the DB...)
33    * email scan - attachments might not have related messages.
34  
35  
36  - {id} attachment_init(
37                 {exim_msg_id}
38                 {chksum}
39                 {filename),
40         )
41         // creates or returns id (can look for existing messages?
42         // can do a merge?? - copy 'old' record data into 'new'....  "prefer checksummed"
43         
44         attachment_update(
45                 {id}
46                 {exim_msg_id}
47                 {mailfort_msg_sig}
48                 {file_size}
49                 {created} // message date..
50                 {chksum}
51                 {filename),
52         {mime_type}
53         )
54         attachment_update_store(
55                         {id}
56                         {stored_filename}
57         )
58
59
60 */ 
61
62 // valac --pkg gmime --vapi
63 /*
64
65 // http://www.fromdual.com/mysql-vala-program-example << check mysql if this does not work.
66
67  valac  -g --vapidir=. --thread  strip.vala   --vapidir=../vapi \
68      --pkg glib-2.0 --pkg mysql --pkg gio-2.0 --pkg posix --pkg gmime-2.6 \
69       --Xcc=-lmysqlclient  -v \
70        -o /tmp/strip
71 */ 
72  
73 public class StripApplication : GLib.Application {
74
75         public static string? opt_path = null;
76         public static string? opt_file = null;  
77         public static string? opt_target_path = null;
78         public static string? opt_db_host = "127.0.0.1";
79         public static string? opt_db_name = null;       
80         public static string? opt_db_user = null;               
81         public static string? opt_db_pass = null;               
82
83         public static int    opt_limit = -1;
84
85         public static bool      opt_is_extracting = false;
86         public static bool      opt_is_replacing = false;
87         public static bool      opt_scan_imap  = false; 
88         public static bool      opt_scan_mailfort  = false;     
89         public static bool              opt_dump = false;       
90         public static bool              opt_debug = false; 
91         
92         public static bool opt_debug_sql = false;       
93         public static string? opt_replace_link = null;
94         
95         
96         public const GLib.OptionEntry[] options = {
97                 
98                 { "debug", 0, 0, OptionArg.NONE, ref opt_debug, "show debug messages for components", null },
99                 { "debug-sql", 0, 0, OptionArg.NONE, ref opt_debug_sql, "debug the SQL statements", null },         
100
101                 { "path", 0, 0, OptionArg.STRING, ref opt_path, "Directory where email to be parsed is", null },        
102                 { "file", 0, 0, OptionArg.STRING, ref opt_file, "A specific file to be parsed", null }, 
103
104                 { "target-path", 0, 0, OptionArg.STRING, ref opt_target_path, "Directory where attachments are to be put", null },
105
106                 { "link", 0, 0, OptionArg.STRING, ref opt_replace_link, "url for the replement link: eg. http://www.mysite.com/xxxx/%s", null },         
107                         
108                 { "host", 0, 0, OptionArg.STRING, ref opt_db_host, "Mysql host (default localhost)", null },    
109                 { "name", 0, 0, OptionArg.STRING, ref opt_db_name, "Mysql database name REQUIRED", null },      
110                 { "user", 0, 0, OptionArg.STRING, ref opt_db_user, "Mysql database user REQUIRED", null },      
111                 { "pass", 0, 0, OptionArg.STRING, ref opt_db_pass, "Mysql database password (default empty)", null },            
112
113                 { "extract", 0, 0, OptionArg.NONE, ref opt_is_extracting, "Should attachments be extracted (default NO)", null },
114                 { "replace", 0, 0, OptionArg.NONE, ref opt_is_replacing, "Should attachments be replaced (default NO)", null },
115                 { "dump", 0, 0, OptionArg.NONE, ref opt_dump, "Print the replaced mail contents to stdout", null },         
116
117                 { "limit", 0, 0, OptionArg.INT, ref opt_limit, "stop after X number of messages with attachments have been processed", null },         
118
119                 { "scan-imap", 0, 0, OptionArg.NONE, ref opt_scan_imap, "scan an imap tree", null },
120                 { "scan-mailfort", 0, 0, OptionArg.NONE, ref opt_scan_mailfort, "scan a mailfort tree", null },  
121                 { null }       
122         };         
123     public StripApplication( string[] args ) 
124     {
125                  Object(
126             application_id: "org.roojs.mailstripper",
127             flags: ApplicationFlags.FLAGS_NONE
128          );
129  
130                         
131          var opt_context =  new GLib.OptionContext ("Mail Stripper");
132                         
133          try {
134                                 
135             opt_context.set_help_enabled (true);
136             opt_context.add_main_entries (options, null);
137             opt_context.parse ( ref  args);
138             //opt_detach = !optx_no_detach;
139                             
140  
141                             
142              // options that have to be set.. bee or hive... (or stop all)
143             if ((!opt_scan_mailfort && !opt_scan_imap) || (opt_scan_mailfort && opt_scan_imap))  {
144                stdout.printf ("You must specify the type of directory tree to scan - either imap or mailfort\n%s",
145                    opt_context.get_help(true, null));
146                GLib.Process.exit(Posix.EXIT_FAILURE);
147             }
148                         
149                          if ((opt_db_name == null || opt_db_name.length < 1 || opt_db_user == null || opt_db_user.length < 1))  {
150                stdout.printf ("You must specify the database name / user \n%s",
151                    opt_context.get_help(true, null));
152                GLib.Process.exit(Posix.EXIT_FAILURE);
153             }
154                          if ((opt_path == null || opt_path.length < 1)   )  {
155                stdout.printf ("You must specify the scan start path\n%s",
156                    opt_context.get_help(true, null));
157                GLib.Process.exit(Posix.EXIT_FAILURE);
158             }
159                         if (opt_replace_link == null || (opt_replace_link.length < 1))  {
160                stdout.printf ("You must specify the link to use in the replacement \n%s",
161                    opt_context.get_help(true, null));
162                GLib.Process.exit(Posix.EXIT_FAILURE);
163             }
164             if ((opt_is_replacing || opt_is_extracting ) && (opt_target_path == null || opt_target_path.length < 1)) {
165                       stdout.printf ("You must specify a target path to put attachments\n%s",
166                    opt_context.get_help(true, null));
167                GLib.Process.exit(Posix.EXIT_FAILURE);
168             }
169             
170             
171          } catch (GLib.OptionError e) {
172             stdout.printf ("error: %s\n", e.message);
173             stdout.printf ("Run '%s --help' to see a full list of available command line options.\n%s", 
174                       args[0], opt_context.get_help(true, null));
175             GLib.Process.exit(Posix.EXIT_FAILURE);
176          }
177         }
178          
179     public static int main(string[] args) 
180     {
181                 
182                 var application = new StripApplication(  args);
183                 
184                 GLib.Log.set_always_fatal(LogLevelFlags.LEVEL_ERROR | LogLevelFlags.LEVEL_CRITICAL); 
185            
186            if (opt_debug || opt_debug_sql) {
187                         GLib.Log.set_handler(null, 
188                         GLib.LogLevelFlags.LEVEL_DEBUG | GLib.LogLevelFlags.LEVEL_WARNING | GLib.LogLevelFlags.LEVEL_INFO, 
189                         (dom, lvl, msg) => {
190                                         print("%s\n", msg);
191                                 }
192                         );
193                 }
194         
195         GMime.init(0);
196                 if (StripApplication.opt_is_replacing) {
197                         StripApplication.opt_is_extracting = true;
198                 }
199   
200                 GLib.debug("scanning folder: %s", opt_path );
201                 
202                 var strip = new Strip( opt_path );
203  
204                 
205                 strip.mysql  = new Mysql.Database();
206                 if (!strip.mysql.real_connect(
207                                 opt_db_host,
208                                 opt_db_user ,
209                                 opt_db_pass == null ? "" : opt_db_pass, //passwd
210                                 opt_db_name, //DB
211                                 3306, // not changable...?
212                                 null
213                         )
214                 ) {
215                         stdout.printf("ERROR %u: Connection failed: %s\n", 
216                                 strip.mysql.errno(), strip.mysql.error()
217                         );
218
219                         return 1;
220                 }
221         if (opt_file != null) {
222                 strip.base_dir = opt_path;
223                 strip.scan_file( GLib.Path.get_dirname(opt_file),  GLib.Path.get_basename(opt_file));
224                 return 0;
225         }
226
227                 strip.scan_dir(opt_path);
228         
229
230         
231         return 0;
232     }
233 }
234
235 public class Strip : GLib.Object {
236         
237  
238         
239         public string base_dir = "";
240         
241         public Mysql.Database mysql;
242         
243         int processed = 0;
244     
245     uint64 used_space_before = 0;
246     uint64 used_space_after = 0;
247     
248     
249     public Strip(string base_dir)
250     {
251         this.base_dir = base_dir;
252     }
253     
254     public void handle_part(GMime.Object parent, GMime.Object mime_obj)
255     {
256                 if (mime_obj is GMime.Part) {
257                    var  p = (GMime.Part)mime_obj;
258                         var ct = p.get_content_type();
259                         var cd = p.get_content_disposition();
260                         
261                         var sid = p.get_header("X-strip-id");
262                     if (sid != null && sid.length > 0) {
263                         this.update_attachment_db(p);
264                             GLib.debug("Skip attachment replace - it's already been done");
265                         return;
266                         }
267                         
268                         if (cd == null || cd.get_disposition().down() != "attachment") {
269                                 return;
270                         }
271                         if (ct.get_media_type() == "text") {
272                                 return;
273                         }
274                         if (ct.to_string() == "application/pgp-encrypted") {
275                                 return;
276                         }
277                         if (ct.to_string() == "application/pgp-keys") {
278                                 return;
279                         }
280                         if (p.get_filename() == null) {
281                                 return;
282                         }
283                          // print("got part %s\n", ct.to_string());
284                          if (parent is GMime.Multipart) {
285                                 
286                                 this.replace_attachment(((GMime.Multipart)parent), p);
287                                 // remove it !?
288
289                           }
290
291
292                         return;
293                 }
294                 if (mime_obj is GMime.Multipart) {
295                         
296
297                         var  mp = (GMime.Multipart)mime_obj;
298                         //var ct = mp.get_content_type();
299
300                         //print("got multi-part %s\n", ct.to_string());
301                         for (var i = 0; i< mp.get_count(); i++) { 
302                           var mo = mp.get_part(i);
303                           this.handle_part(mime_obj,mo);
304                         }
305                    // ((GMime.Multipart)mime_obj).foreach((sub_obj) => {
306                    //     Strip.handle_part(sub_obj);
307                 //
308                    // });
309
310
311                         return;
312                 }
313
314                 if (mime_obj is GMime.MessagePart) {
315                         var msg = ((GMime.MessagePart)mime_obj).get_message();
316                         msg.foreach((subobj) => {
317                          this.handle_part(msg,subobj);
318                     });
319                 
320                         //print("got message-part\n");
321                         return;
322                 }
323                 
324                 if (mime_obj is GMime.Message) {
325                         var mp = ((GMime.Message) mime_obj).get_mime_part();
326
327                         if (!(mp is GMime.Multipart)) {
328                                 //GLib.debug("get mimepart does not return a Multipart?");
329                                 return;
330                         }
331                         
332                         var mpc = ((GMime.Multipart)mp).get_count();
333                         
334                         //GLib.debug("Message has %d parts", mpc); 
335                         for (var i =0 ; i < mpc; i++) {
336                                 //GLib.debug("Getting part %d", i); 
337                                 var submime_obj = ((GMime.Multipart)mp).get_part(i);
338                         this.handle_part(mp,submime_obj);                       
339                     }
340                         print("got message??\n");
341                         return;
342                 }
343                 
344                 print("got something else\n");
345
346
347     }
348     public void update_attachment_db(GMime.Part attachment)
349     {
350         // only called when we have an sid...
351         var sid = attachment.get_header("X-strip-id");
352         if (sid == null || sid.length < 1) {
353                 GLib.debug("Strange - update attachment db called ?");
354                 return;
355         }
356         
357         // initialize it with known data..
358         // that should wipe out dupes.
359         var filesize = this.query("SELECT filesize FROM Attachment WHERE id = %d".printf(
360                         int.parse(sid)));       
361                 if (int.parse(filesize) < 1) {
362                 GLib.debug("Could not get filesize from id :%s = %s", sid,filesize);
363                 Posix.exit(0);
364                 return;
365         }
366         
367         var chksum = this.query("SELECT  checksum FROM Attachment WHERE id = %d".printf(
368                         int.parse(sid)
369                 ));
370         var mime_filename = this.query("SELECT  mime_filename FROM Attachment WHERE id = %d".printf(
371                         int.parse(sid)));       
372                 
373         this.query("""
374              SELECT 
375                  attachment_init(
376                      '%s', '%s', '%s', %d
377                  ) as id 
378                  
379           """.printf(
380                           this.mysql_escape(this.active_message_exim_id),
381                           this.mysql_escape(chksum),
382                           this.mysql_escape(mime_filename),                       
383                           int.parse(filesize)
384                 ));
385         this.query("""
386                  SELECT attachment_update(
387                       %d, -- in_id INT(11),
388                       '%s', -- in_mime_type varchar(255),
389                       '%s', -- in_created DATETIME,
390                       '%s' -- in_mailfort_sig varchar(64)
391                  )
392               """.printf(
393                         int.parse(sid),
394                         "", // this will be ignored..
395                                 this.created_date,
396                                 this.mysql_escape(this.active_message_x_mailfort_sig)
397               
398               )
399                 );
400                 this.mysql.store_result();
401                 
402
403     
404     }
405     
406     
407     public void replace_attachment(GMime.Multipart parent, GMime.Part attachment)
408     {
409         var sid = attachment.get_header("X-strip-id");
410         if (sid != null && sid.length > 0) {
411                 GLib.debug("Skip attachment replace - it's already been done");
412                 return;
413         }
414         
415         var c = attachment.get_content_object();
416         
417         var filename = attachment.get_filename().replace("/", "-");
418         var fn = GLib.Environment.get_tmp_dir() +
419                         "/"+ this.active_name + "."+   filename;
420
421             var outfile = new GMime.StreamFile.for_path(fn, "w");
422             outfile.set_owner(true);
423             var file_size = (int) c.write_to_stream(outfile);
424             var chksum = this.md5_file(fn);
425             outfile.flush();
426             outfile = null;
427         
428         if (file_size == 0) {
429
430                 GLib.debug("ERROR - file size of write to stream returned 0?");
431                 Posix.unlink(fn);               
432                 return;
433         }
434         
435         
436         
437  
438         var mime_type= attachment.get_content_type().to_string();
439         // at this point we have to do our database magic...
440         //filesize / name / date / checksum / mimetype -- into mailfort should be OK.
441         
442         var file_id = this.query("""
443                 SELECT 
444                 
445                 attachment_init(
446                                 '%s', -- in_msgid VARCHAR(32),
447                                 '%s', -- in_checksum VARCHAR(64),
448                                 '%s', -- in_mime_filename varchar(255)
449                                 %d -- filesize
450                         ) as id 
451                         
452           """.printf(
453                         this.mysql_escape(this.active_message_exim_id),
454                         chksum,
455                         this.mysql_escape( attachment.get_filename() ), // what is thsi is invalid?
456                          file_size)
457                 );
458                  
459                 
460                 if (file_id.length < 1) {
461                         GLib.debug("ERROR - CALL to attachment_init failed");
462                 Posix.unlink(fn);               
463                 return;
464                 
465                 }
466  
467                 if (int.parse(file_id) < 1) {
468                         GLib.debug("ERROR - CALL to attachment_init failed - returned 0?");
469                 Posix.unlink(fn);               
470                 return;
471                 
472                 }
473  
474         
475                 GLib.debug("fn = %s, m5=%s, id= %s", filename, mime_type, this.active_message_id);
476                 this.query("""
477                 
478                         SELECT attachment_update(
479                                 %d, -- in_id INT(11),
480                                 '%s', -- in_mime_type varchar(255),
481                                 '%s', -- in_created DATETIME,
482                                 '%s' -- in_mailfort_sig varchar(64)
483                                 
484                                 ) as result
485       """.printf(
486                 int.parse(file_id),
487                         this.mysql_escape(mime_type),
488                         this.created_date,
489                         this.mysql_escape(this.active_message_x_mailfort_sig)
490                 ));
491                  this.mysql.store_result();
492                                  
493  
494                 this.used_space_after += file_size;
495                         
496                 var target_fn = "";
497
498             if (StripApplication.opt_is_extracting) {
499                         target_fn = StripApplication.opt_target_path + "/" + this.created_dir +"/"+ file_id  + "-" + filename;
500                 } 
501                     
502             var stored =  "/" + this.created_dir +"/"+ file_id  + "-" + filename;
503                  this.query("""
504                 
505                         SELECT attachment_update_store(
506                                 %d, -- in_id INT(11),
507                                 '%s'  -- in_store_filename varchar(255),
508                          
509                                 
510                                 ) as result
511       """.printf(
512                 int.parse(file_id),
513                          this.mysql_escape( stored)
514                 ));   
515                          
516         var rep = new GMime.Part.with_type("text","html");
517         // we have to set up a redirect server - to redirect hpasite... to their internal service..
518         rep.set_filename(filename);
519         string txt = "<html><body>"+
520             "<a href=\"" + StripApplication.opt_replace_link + "/" +
521                         file_id + "/" + this.created_dir + "/"+chksum+"/"+ GLib.Uri.escape_string( filename) +"\">" + 
522             GLib.Uri.escape_string( filename) + // fixme needs html escaping...
523             "</a>" +
524             "</body></html>";
525
526         rep.get_content_type().set_parameter("charset", "utf-8");
527                 rep.set_header("X-strip-id", file_id);
528                 rep.set_header("X-strip-content-name",  filename);                              
529                 rep.set_header("X-strip-path", this.created_dir + "/" + file_id + "-" + filename);              
530                 rep.set_header("X-strip-content-type", mime_type);              
531         var stream =  new GMime.StreamMem.with_buffer(txt.data);
532         var con = new GMime.DataWrapper.with_stream(stream,GMime.ContentEncoding.DEFAULT);
533
534         rep.set_content_object(con);
535         GLib.debug("Replacing Attachment with HTML");
536         parent.replace(parent.index_of(attachment), rep);
537                 this.has_replaced = true;
538                  
539                 if (StripApplication.opt_is_extracting && target_fn.length > 0) {
540                         var dir = GLib.Path.get_dirname(target_fn);
541                         if (!FileUtils.test (dir, FileTest.IS_DIR)) {
542                                 GLib.DirUtils.create_with_parents(dir, 0755);
543                         }
544                         GLib.debug("Creating file %s", target_fn);
545                         if (!FileUtils.test (target_fn, FileTest.EXISTS)) {
546                                 Posix.link(fn, target_fn);
547                         }
548                 } else { 
549                         GLib.debug("Skipping extraction %s", target_fn);
550                 }
551                 Posix.unlink(fn);
552                 
553
554
555     }
556     public string query(string str)
557     {
558             return this.real_query(true, str);
559     }
560     public string execute(string str)
561     {
562             return this.real_query(false, str);
563     }
564     public string real_query(bool need_return, string str)
565     {
566                 GLib.debug("Before Query : %u  : %s\n", this.mysql.errno(), this.mysql.error());
567
568
569         if (StripApplication.opt_debug_sql) {
570                 GLib.debug("SQL: %s\n", str);
571                 }
572                 
573                 
574         
575         var rc=  this.mysql.query(str);         
576         if ( rc != 0 ) {
577
578                     GLib.debug("ERROR %u: Query failed: %s\n", this.mysql.errno(), this.mysql.error());
579                                 Posix.exit(1);
580                 }
581                 
582
583         var rs = mysql.use_result();
584         
585         var got_row = false;
586                 string[] row;
587                 string ret = "";
588                 while( (row = rs.fetch_row()) != null) { 
589                         got_row = true;
590                         ret = row[0];
591                 
592                 }
593                 if (!need_return) {
594                         return "";
595                 }
596                 if (!got_row) {
597                          GLib.debug("ERROR : no rows returned");
598                         Posix.exit(1);
599                         return "";
600                 }
601                 GLib.debug("got %s", ret);
602                 return ret;
603                 
604                  
605         }
606     
607     public string mysql_escape(string str)
608     {
609             unichar[] value_escaped = new unichar[str.length * 2 + 1];
610                 this.mysql.real_escape_string ((string) value_escaped, str, str.length);
611                 return (string) value_escaped;
612     }
613     
614     public string  md5_file(string fn) {
615               Checksum checksum = new Checksum (ChecksumType.MD5);
616
617               FileStream stream = FileStream.open (fn, "rb");
618               uint8 fbuf[100];
619               size_t size;
620
621               while ((size = stream.read (fbuf)) > 0) {
622                       checksum.update (fbuf, size);
623               }
624
625               unowned string digest = checksum.get_string ();
626               return digest;
627     }
628
629         string active_path = "";    
630     string active_name = "";
631     string active_message_id = "";
632     string active_message_x_mailfort_sig = "";
633     string active_message_exim_id = "";
634     bool has_replaced = false;
635     string created_date = ""; // should be YYYY-mm-dd
636     string created_dir = ""; // should be YYY/mm/dd
637     
638     public void scan_file(string path, string name)
639     {
640                 GLib.debug("Scan: %s/%s", path,name); 
641                 
642                 this.has_replaced = false; 
643         this.active_path = path;
644         this.active_name = name;
645         this.active_message_id = "";
646
647         this.created_dir = this.active_path.substring(this.base_dir.length + 1 );
648                 this.created_date = this.created_dir.replace("/", "-");
649         
650                 var fileinfo = File.new_for_path(path +"/" + name)
651                                         .query_info(GLib.FileAttribute.STANDARD_SIZE+","+GLib.FileAttribute.TIME_MODIFIED
652                                                 ,GLib.FileQueryInfoFlags.NONE,null);
653         var file_size = (int) fileinfo.get_size();
654                 var mod_time = fileinfo.get_modification_time();                                       
655                 
656         this.used_space_before += file_size;
657         
658         var stream = new GMime.StreamFs.for_path (path +"/" + name,Posix.O_RDONLY, 0);
659         //stream.set_owner(true);
660         var parser = new GMime.Parser.with_stream(stream);
661         var message = parser.construct_message();
662  
663                 if (message == null) {
664                         GLib.debug("Could not parse file? %s/%s", path,name);
665                 this.used_space_after += file_size;                     
666                 return;
667                 }       
668
669
670                 // check : - is message over a year old?                
671                 // get various msg info..
672                 this.active_message_id = message.get_message_id();
673                 this.active_message_x_mailfort_sig = message.get_header("x-mailfort-sig");
674                 var recvd = message.get_header("received");
675                 this.active_message_exim_id = "";
676                 if (recvd != null && recvd.length > 1) {
677                         // GLib.debug("RECV: %s", recvd);
678                         var lines = recvd.split("\t");
679                         for (var i = 0; i < lines.length;i++) {
680                                 var bits = lines[i].strip().split(" ");
681                                 if (bits[0] == "id") {
682                                         this.active_message_exim_id = bits[1].replace(";","");
683                                         var dbits = lines[i].strip().split(";");
684                                         int tz;
685                                         var timez = GMime.utils_header_decode_date(dbits[1], null);
686                                         if (timez != 0) {
687                                                 var dts = DateTime.from_unix_utc(timez);
688                                                 this.created_date = dts.format("%Y-%m-%d %H:%M:%s");
689                                         }
690                                 }
691
692                         }
693                 }
694                 /*
695                 GLib.debug("Message DATA:\n mid: %s\nmailfort: %s \nexim_id: %s",
696                         this.active_message_id,
697                         this.active_message_x_mailfort_sig,
698                         this.active_message_exim_id
699                 );
700                  */
701                         
702                 // DATE?
703                 
704                 var mp = message.get_mime_part();
705
706                 if (!(mp is GMime.Multipart)) {
707                         //GLib.debug("get mimepart does not return a Multipart?");
708                 this.used_space_after += file_size;                                             
709                         return;
710                 }
711                 
712                 var mpc = ((GMime.Multipart)mp).get_count();
713                 
714                 //GLib.debug("Message has %d parts", mpc); 
715                 for (var i =0 ; i < mpc; i++) {
716                         //GLib.debug("Getting part %d", i); 
717                         var mime_obj = ((GMime.Multipart)mp).get_part(i);
718             this.handle_part(mp,mime_obj);                      
719         }
720                 
721         parser= null;
722
723       //  stream.set_owner(false);
724             //stream.close();
725         stream = null;//.close();
726         
727         
728                 if (!this.has_replaced) {
729                         this.used_space_after += file_size;
730                         GLib.debug("skpping write file - no replacement occured");
731                         return;
732                 }
733                 string tmpfile = "";
734                 GMime.Stream outstream = new GMime.StreamNull();
735                 if (StripApplication.opt_is_replacing) {
736                 
737                         tmpfile = GLib.Environment.get_tmp_dir() +"/" + name;
738                 outstream = new GMime.StreamFile.for_path (tmpfile,"w");
739                 ((GMime.StreamFile)outstream).set_owner(true);
740         }
741                 if (StripApplication.opt_dump) {
742                         outstream = new GMime.StreamMem();
743         }
744         
745         file_size = (int) message.write_to_stream(outstream);
746         if (StripApplication.opt_is_replacing) {
747                 ((GMime.StreamFile)outstream).set_owner(false);
748         }
749                 if (StripApplication.opt_dump) {
750                         var ua = ((GMime.StreamMem)outstream).get_byte_array().data;
751                         print("%s\n", (string) ua);
752                 }        
753         message = null;
754         outstream.flush();
755         outstream.close();
756         GLib.debug("finished writing output %d", file_size);
757
758         //
759         
760           
761         this.used_space_after += file_size;
762         
763         
764         if (StripApplication.opt_is_replacing) {
765                 Posix.unlink(path +"/" + name);         
766                 GLib.debug("copy tmp file %s to %s" , tmpfile, path +"/" + name);               
767                 Posix.link(tmpfile, path +"/" + name);
768                 Posix.unlink(tmpfile);
769                 var nf = File.new_for_path(path +"/" + name);
770                 var newfileinfo = nf.query_info(GLib.FileAttribute.TIME_MODIFIED,GLib.FileQueryInfoFlags.NONE,null);
771                 newfileinfo.set_modification_time(mod_time);
772                 nf.set_attributes_from_info(newfileinfo,FileQueryInfoFlags.NONE);
773                 }
774         this.processed++;
775         
776         if (StripApplication.opt_limit > -1 && this.processed >= StripApplication.opt_limit) {
777                 GLib.debug("Reached replacement limit");
778                 Posix.exit(1);
779         }
780         
781         
782         
783         
784     }
785     
786     
787     public void scan_dir(string path)
788     {
789         var f = File.new_for_path(path);
790                 FileEnumerator file_enum;
791         var cancellable = new Cancellable ();
792         try {      
793             file_enum = f.enumerate_children(
794                 FileAttribute.STANDARD_DISPLAY_NAME + "," +   FileAttribute.STANDARD_TYPE,
795                         FileQueryInfoFlags.NOFOLLOW_SYMLINKS,  // FileQueryInfoFlags.NONE,
796                         cancellable
797                 );
798         } catch (Error e) {
799                 GLib.debug("Got error scanning dir? %s", e.message);
800             // FIXME - show error..
801             return;
802         }
803         FileInfo next_file;
804          
805         while (cancellable.is_cancelled () == false ) {
806             try {
807                 next_file = file_enum.next_file (cancellable);
808             } catch(Error e) {
809                 GLib.debug("error getting next file? %s", e.message);
810                 break;
811             }
812
813             if (next_file == null) {
814                 break;
815             }
816
817
818             if (next_file.get_file_type() != FileType.DIRECTORY) {
819                 
820                 if (next_file.get_display_name()[0] == ',') {
821                         continue;
822                 }
823                 
824                 this.scan_file(path , next_file.get_display_name());
825                                 if(this.has_replaced) {
826                          this.report_state("After scanning %s/%s".printf(path , next_file.get_display_name()));
827                         }
828                 continue;
829             }
830
831
832             //stdout.printf("Monitor.monitor: got file %s : type :%u\n",
833             //        next_file.get_display_name(), next_file.get_file_type());
834
835
836             if (next_file.get_is_symlink()) {
837                 next_file = null;
838                 continue;
839             }
840             
841             var ds = next_file.get_display_name();
842             if (ds[0] == '.') {
843                 next_file = null;
844                 continue;
845             }
846             if (ds == "attachments") {
847                         continue;
848                 }
849             
850             
851             var sp = path+"/"+next_file.get_display_name();
852             // skip modules.
853             //print("got a file : " + sp);
854          
855             next_file = null;
856             
857             
858             this.scan_dir(sp);
859             
860         }
861     
862     
863     }
864     void report_state(string msg) 
865     {
866         // Saved: 2G  Original 10G : 20%
867         GLib.debug("Saved : %s (%.1f%%) | Original %s | %s", 
868                         GLib.format_size(this.used_space_before - this.used_space_after), 
869                         100f * ((1f * (this.used_space_before - this.used_space_after)) / (this.used_space_before * 1f)), 
870                         GLib.format_size(this.used_space_before),                       
871                         msg
872                 );
873         
874         }
875         
876         
877
878 }