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                         return 1;
219                 }
220         if (opt_file != null) {
221                 strip.base_dir = opt_path;
222                 strip.scan_file( GLib.Path.get_dirname(opt_file),  GLib.Path.get_basename(opt_file));
223                 return 0;
224         }
225
226                 strip.scan_dir(opt_path);
227         
228
229         
230         return 0;
231     }
232 }
233
234 public class Strip : GLib.Object {
235         
236  
237         
238         public string base_dir = "";
239         
240         public Mysql.Database mysql;
241         
242         int processed = 0;
243     
244     uint64 used_space_before = 0;
245     uint64 used_space_after = 0;
246     
247     
248     public Strip(string base_dir)
249     {
250         this.base_dir = base_dir;
251     }
252     
253     public void handle_part(GMime.Object parent, GMime.Object mime_obj)
254     {
255                 if (mime_obj is GMime.Part) {
256                    var  p = (GMime.Part)mime_obj;
257                         var ct = p.get_content_type();
258                         var cd = p.get_content_disposition();
259                         
260                         var sid = p.get_header("X-strip-id");
261                     if (sid != null && sid.length > 0) {
262                         this.update_attachment_db(p);
263                             GLib.debug("Skip attachment replace - it's already been done");
264                         return;
265                         }
266                         
267                         if (cd == null || cd.get_disposition().down() != "attachment") {
268                                 return;
269                         }
270                         if (ct.get_media_type() == "text") {
271                                 return;
272                         }
273                         if (ct.to_string() == "application/pgp-encrypted") {
274                                 return;
275                         }
276                         if (ct.to_string() == "application/pgp-keys") {
277                                 return;
278                         }
279                         if (p.get_filename() == null) {
280                                 return;
281                         }
282                          // print("got part %s\n", ct.to_string());
283                          if (parent is GMime.Multipart) {
284                                 
285                                 this.replace_attachment(((GMime.Multipart)parent), p);
286                                 // remove it !?
287
288                           }
289
290
291                         return;
292                 }
293                 if (mime_obj is GMime.Multipart) {
294                         
295
296                         var  mp = (GMime.Multipart)mime_obj;
297                         //var ct = mp.get_content_type();
298
299                         //print("got multi-part %s\n", ct.to_string());
300                         for (var i = 0; i< mp.get_count(); i++) { 
301                           var mo = mp.get_part(i);
302                           this.handle_part(mime_obj,mo);
303                         }
304                    // ((GMime.Multipart)mime_obj).foreach((sub_obj) => {
305                    //     Strip.handle_part(sub_obj);
306                 //
307                    // });
308
309
310                         return;
311                 }
312
313                 if (mime_obj is GMime.MessagePart) {
314                         var msg = ((GMime.MessagePart)mime_obj).get_message();
315                         msg.foreach((subobj) => {
316                          this.handle_part(msg,subobj);
317                     });
318                 
319                         //print("got message-part\n");
320                         return;
321                 }
322                 
323                 if (mime_obj is GMime.Message) {
324                         var mp = ((GMime.Message) mime_obj).get_mime_part();
325
326                         if (!(mp is GMime.Multipart)) {
327                                 GLib.debug("get mimepart does not return a Multipart?");
328                                 return;
329                         }
330                         
331                         var mpc = ((GMime.Multipart)mp).get_count();
332                         
333                         //GLib.debug("Message has %d parts", mpc); 
334                         for (var i =0 ; i < mpc; i++) {
335                                 //GLib.debug("Getting part %d", i); 
336                                 var submime_obj = ((GMime.Multipart)mp).get_part(i);
337                         this.handle_part(mp,submime_obj);                       
338                     }
339                         print("got message??\n");
340                         return;
341                 }
342                 
343                 print("got something else\n");
344
345
346     }
347     public void update_attachment_db(GMime.Part attachment)
348     {
349         // only called when we have an sid...
350         var sid = attachment.get_header("X-strip-id");
351         if (sid == null || sid.length < 1) {
352                 GLib.debug("Strange - update attachment db called ?");
353                 return;
354         }
355         this.query("""
356                 SELECT attachment_update(
357                                 %d, -- in_id INT(11),
358                                 '%s', -- in_mime_type varchar(255),
359                                 %d, -- in_mime_size int(11),
360                                 '%s', -- in_created DATETIME,
361                                 '%s' -- in_mailfort_sig varchar(64)
362                                 
363                     )""
364         
365                                  
366               """.printf(
367                         int.parse(sid),
368                         "", // this will be ignored..
369                         0, // this will be ingored..
370                                 this.created_date,
371                                 this.mysql_escape(this.active_message_x_mailfort_sig)
372               
373               )
374                 );
375         
376         
377     
378     }
379     
380     
381     public void replace_attachment(GMime.Multipart parent, GMime.Part attachment)
382     {
383         var sid = attachment.get_header("X-strip-id");
384         if (sid != null && sid.length > 0) {
385                 GLib.debug("Skip attachment replace - it's already been done");
386                 return;
387         }
388         
389         var c = attachment.get_content_object();
390         
391         var filename = attachment.get_filename().replace("/", "-");
392         var fn = GLib.Environment.get_tmp_dir() +
393                         "/"+ this.active_name + "."+   filename;
394
395             var outfile = new GMime.StreamFile.for_path(fn, "w");
396             outfile.set_owner(true);
397             var file_size = (int) c.write_to_stream(outfile);
398             var chksum = this.md5_file(fn);
399             outfile.flush();
400             outfile = null;
401         
402         if (file_size == 0) {
403
404                 GLib.debug("ERROR - file size of write to stream returned 0?");
405                 Posix.unlink(fn);               
406                 return;
407         }
408         
409         
410         
411  
412         var mime_type= attachment.get_content_type().to_string();
413         // at this point we have to do our database magic...
414         //filesize / name / date / checksum / mimetype -- into mailfort should be OK.
415         
416         this.query("""
417                 SELECT 
418                 
419                 attachment_init(
420                                 '%s', -- in_msgid VARCHAR(32),
421                                 '%s', -- in_checksum VARCHAR(64),
422                                 '%s', -- in_mime_filename varchar(255)
423                                 %d -- filesize
424                         ) as id ;
425           """.printf(
426                         this.mysql_escape(this.active_message_exim_id),
427                         chksum,
428                         this.mysql_escape( attachment.get_filename() ), // what is thsi is invalid?
429                          file_size)
430                 );
431                 var file_id = "0";
432         var rs = mysql.use_result();
433  
434                 var row = rs.fetch_row();
435                 
436                 var target_fn = "";
437                 
438                 var create_dir = this.created_dir;
439                 
440                 
441                 if (rs != null  && rs.num_rows() > 0) {
442                         file_id =  row[0];
443                         create_dir = row[1];
444                         GLib.debug("msgid %s", row[2]);
445                         Posix.exit(0);
446                         this.used_space_after += file_size;
447                         if (StripApplication.opt_is_extracting) {
448                                 target_fn = StripApplication.opt_target_path + "/" + this.created_dir +"/"+ file_id  + "-" + filename;
449                         } 
450                         
451                         
452                 } else {
453                 
454                         GLib.debug("fn = %s, m5=%s, id= %s", filename, mime_type, this.active_message_id);
455                         this.query("""
456                         INSERT INTO
457                                         Attachment 
458                                 (
459                                          queue_id,
460                                          mime_charset,
461                                          mime_cdisp,
462                                          mime_size,
463                                          
464                                          mime_is_cover,
465                                          mime_is_multi,
466                                          mime_is_mail,
467                                          
468                                          msgid,
469                                          maillog_id,
470                                          delivered,
471                                          
472                                          
473                                          checksum,
474                                          filesize,
475                                          stored_filename,
476                                          
477                                          created,
478                                          mime_filename,
479                                          mime_type,
480                                          
481  
482                                 )
483                                         VALUES
484                                 (
485                                          COALESCE((SELECT id from MailQueue where msgid = '%s' AND message_sig = '%s' AND  msgid != '' AND message_sig != '' LIMIT 1),0),
486                                          '%s',
487                                          '%s',
488                                          %d,
489                                          
490                                          0,
491                                          0,
492                                          0,
493                                          
494                                          '%s',
495                                          COALESCE((SELECT id from email_log where msgid = '%s' AND message_sig = '%s' AND  msgid != '' AND message_sig != '' LIMIT 1),0),
496                                         '%s',
497                                          
498                                          '%s',
499                                          %d,
500                                          '%s',
501                                          
502                                          '%s',
503                                          '%s',
504                                          '%s' 
505                                           
506                                 )
507                                          
508                       """.printf(
509                                 this.mysql_escape(this.active_message_exim_id), this.mysql_escape(this.active_message_x_mailfort_sig),
510                                 "",
511                                 "attachment",
512                                  file_size,
513                                  
514                                 this.mysql_escape(this.active_message_exim_id), // msgid ?
515                                 this.mysql_escape(this.active_message_exim_id), this.mysql_escape(this.active_message_x_mailfort_sig), // maillog_id
516                                 this.created_date, // delivered (from lookup)
517                                  
518                                          chksum,
519                                          file_size,
520                                          "", // filled in after we find out the id..
521                                          
522                                          this.created_date,
523                                          this.mysql_escape(filename),
524                                          this.mysql_escape(mime_type) 
525                                          
526  
527                       
528                       
529                       )
530                         );
531                         this.used_space_after += file_size;
532                         
533                         var file_id_real = this.mysql.insert_id();
534                         GLib.debug("Got file_id = %d\n", (int)file_id_real);                    
535                         if (file_id_real == 0) {
536                                 GLib.Process.exit(1);
537                         }
538                         file_id = "%d".printf((int)file_id_real);
539                         
540                         
541
542                    if (StripApplication.opt_is_extracting) {
543                                 target_fn = StripApplication.opt_target_path + "/" + this.created_dir +"/"+ file_id  + "-" + filename;
544                         } 
545                     
546                     var stored =  "/" + this.created_dir +"/"+ file_id  + "-" + filename;
547                     
548                         this.query("""
549                                 UPDATE
550                                         Attachment
551                                 SET
552                                         stored_filename = '%s'
553                                 WHERE
554                                         id = %s
555                         """.printf(
556                                 this.mysql_escape( stored),
557                                 file_id
558                         ));
559                 
560                 } 
561                 
562         var rep = new GMime.Part.with_type("text","html");
563         // we have to set up a redirect server - to redirect hpasite... to their internal service..
564         rep.set_filename(filename);
565         var txt = "<html><body>"+
566             "<a href=\"" + StripApplication.opt_replace_link + "/" +
567                         file_id + "/" + create_dir + "/"+chksum+"/"+ GLib.Uri.escape_string( filename) +"\">" + 
568             GLib.Uri.escape_string( filename) + // fixme needs html escaping...
569             "</a>" +
570             "</body></html>";
571
572         rep.get_content_type().set_parameter("charset", "utf-8");
573                 rep.set_header("X-strip-id", file_id);
574                 rep.set_header("X-strip-content-name",  filename);                              
575                 rep.set_header("X-strip-path", create_dir + "/" + file_id + "-" + filename);            
576                 rep.set_header("X-strip-content-type", mime_type);              
577         var stream =  new GMime.StreamMem.with_buffer(txt.data);
578         var con = new GMime.DataWrapper.with_stream(stream,GMime.ContentEncoding.DEFAULT);
579
580         rep.set_content_object(con);
581         GLib.debug("Replacing Attachment with HTML");
582         parent.replace(parent.index_of(attachment), rep);
583                 this.has_replaced = true;
584                  
585                 if (StripApplication.opt_is_extracting && target_fn.length > 0) {
586                         var dir = GLib.Path.get_dirname(target_fn);
587                         if (!FileUtils.test (dir, FileTest.IS_DIR)) {
588                                 GLib.DirUtils.create_with_parents(dir, 0755);
589                         }
590                         GLib.debug("Creating file %s", target_fn);
591                         if (!FileUtils.test (target_fn, FileTest.EXISTS)) {
592                                 Posix.link(fn, target_fn);
593                         }
594                 } else { 
595                         GLib.debug("Skipping extraction %s", target_fn);
596                 }
597                 Posix.unlink(fn);
598                 
599
600
601     }
602     
603     public int query(string str)
604     {
605         if (StripApplication.opt_debug_sql) {
606                 GLib.debug("SQL: %s\n", str);
607                 }
608         
609         var rc=  this.mysql.query(str);         
610         if ( rc != 0 ) {
611
612                     GLib.debug("ERROR %u: Query failed: %s\n", this.mysql.errno(), this.mysql.error());
613                 }
614                 return rc;
615         }
616     
617     public string mysql_escape(string str)
618     {
619             unichar[] value_escaped = new unichar[str.length * 2 + 1];
620                 this.mysql.real_escape_string ((string) value_escaped, str, str.length);
621                 return (string) value_escaped;
622     }
623     
624     public string  md5_file(string fn) {
625               Checksum checksum = new Checksum (ChecksumType.MD5);
626
627               FileStream stream = FileStream.open (fn, "rb");
628               uint8 fbuf[100];
629               size_t size;
630
631               while ((size = stream.read (fbuf)) > 0) {
632                       checksum.update (fbuf, size);
633               }
634
635               unowned string digest = checksum.get_string ();
636               return digest;
637     }
638
639         string active_path = "";    
640     string active_name = "";
641     string active_message_id = "";
642     string active_message_x_mailfort_sig = "";
643     string active_message_exim_id = "";
644     bool has_replaced = false;
645     string created_date = ""; // should be YYYY-mm-dd
646     string created_dir = ""; // should be YYY/mm/dd
647     
648     public void scan_file(string path, string name)
649     {
650                 GLib.debug("Scan: %s/%s", path,name); 
651                 
652                 this.has_replaced = false; 
653         this.active_path = path;
654         this.active_name = name;
655         this.active_message_id = "";
656
657         this.created_dir = this.active_path.substring(this.base_dir.length + 1 );
658                 this.created_date = this.created_dir.replace("/", "-");
659         
660         var file_size = (int) File.new_for_path(path +"/" + name)
661                                         .query_info(GLib.FileAttribute.STANDARD_SIZE,GLib.FileQueryInfoFlags.NONE,null)
662                                         .get_size();
663                                                
664         this.used_space_before += file_size;
665         
666         var stream = new GMime.StreamFs.for_path (path +"/" + name,Posix.O_RDONLY, 0);
667         //stream.set_owner(true);
668         var parser = new GMime.Parser.with_stream(stream);
669         var message = parser.construct_message();
670  
671                 if (message == null) {
672                         GLib.debug("Could not parse file? %s/%s", path,name);
673                 this.used_space_after += file_size;                     
674                 return;
675                 }       
676
677
678                 // check : - is message over a year old?                
679                 // get various msg info..
680                 this.active_message_id = message.get_message_id();
681                 this.active_message_x_mailfort_sig = message.get_header("x-mailfort-sig");
682                 var recvd = message.get_header("received");
683                 this.active_message_exim_id = "";
684                 if (recvd != null && recvd.length > 1) {
685                         GLib.debug("RECV: %s", recvd);
686                         var lines = recvd.split("\t");
687                         for (var i = 0; i < lines.length;i++) {
688                                 var bits = lines[i].strip().split(" ");
689                                 if (bits[0] == "id") {
690                                         this.active_message_exim_id = bits[1];
691                                 }
692                         }
693                 }
694                 GLib.debug("Message DATA:\n mid: %s\nmailfort: %s \nexim_id: %s",
695                         this.active_message_id,
696                         this.active_message_x_mailfort_sig,
697                         this.active_message_exim_id
698                 );
699                  
700                         
701                 // DATE?
702                 
703                 var mp = message.get_mime_part();
704
705                 if (!(mp is GMime.Multipart)) {
706                         GLib.debug("get mimepart does not return a Multipart?");
707                 this.used_space_after += file_size;                                             
708                         return;
709                 }
710                 
711                 var mpc = ((GMime.Multipart)mp).get_count();
712                 
713                 //GLib.debug("Message has %d parts", mpc); 
714                 for (var i =0 ; i < mpc; i++) {
715                         //GLib.debug("Getting part %d", i); 
716                         var mime_obj = ((GMime.Multipart)mp).get_part(i);
717             this.handle_part(mp,mime_obj);                      
718         }
719                 
720         parser= null;
721
722       //  stream.set_owner(false);
723             //stream.close();
724         stream = null;//.close();
725         
726         
727                 if (!this.has_replaced) {
728                         this.used_space_after += file_size;
729                         GLib.debug("skpping write file - no replacement occured");
730                         return;
731                 }
732                 string tmpfile = "";
733                 GMime.Stream outstream = new GMime.StreamNull();
734                 if (StripApplication.opt_is_replacing) {
735                 
736                         tmpfile = GLib.Environment.get_tmp_dir() +"/" + name;
737                 outstream = new GMime.StreamFile.for_path (tmpfile,"w");
738                 ((GMime.StreamFile)outstream).set_owner(true);
739         }
740                 if (StripApplication.opt_dump) {
741                         outstream = new GMime.StreamMem();
742         }
743         
744         file_size = (int) message.write_to_stream(outstream);
745         if (StripApplication.opt_is_replacing) {
746                 ((GMime.StreamFile)outstream).set_owner(false);
747         }
748                 if (StripApplication.opt_dump) {
749                         var ua = ((GMime.StreamMem)outstream).get_byte_array().data;
750                         print("%s\n", (string) ua);
751                 }        
752         message = null;
753         outstream.flush();
754         outstream.close();
755         GLib.debug("finished writing output %d", file_size);
756
757         //
758         
759           
760         this.used_space_after += file_size;
761         
762         
763         if (StripApplication.opt_is_replacing) {
764                 Posix.unlink(path +"/" + name);         
765                 GLib.debug("copy tmp file %s to %s" , tmpfile, path +"/" + name);               
766                 Posix.link(tmpfile, path +"/" + name);
767                 Posix.unlink(tmpfile);
768                 }
769         this.processed++;
770         
771         if (StripApplication.opt_limit > -1 && this.processed >= StripApplication.opt_limit) {
772                 GLib.debug("Reached replacement limit");
773                 Posix.exit(1);
774         }
775         
776         
777         
778         
779     }
780     
781     
782     public void scan_dir(string path)
783     {
784         var f = File.new_for_path(path);
785                 FileEnumerator file_enum;
786         var cancellable = new Cancellable ();
787         try {      
788             file_enum = f.enumerate_children(
789                 FileAttribute.STANDARD_DISPLAY_NAME + "," +   FileAttribute.STANDARD_TYPE,
790                         FileQueryInfoFlags.NOFOLLOW_SYMLINKS,  // FileQueryInfoFlags.NONE,
791                         cancellable
792                 );
793         } catch (Error e) {
794                 GLib.debug("Got error scanning dir? %s", e.message);
795             // FIXME - show error..
796             return;
797         }
798         FileInfo next_file;
799          
800         while (cancellable.is_cancelled () == false ) {
801             try {
802                 next_file = file_enum.next_file (cancellable);
803             } catch(Error e) {
804                 GLib.debug("error getting next file? %s", e.message);
805                 break;
806             }
807
808             if (next_file == null) {
809                 break;
810             }
811
812
813             if (next_file.get_file_type() != FileType.DIRECTORY) {
814                 
815                 if (next_file.get_display_name()[0] == ',') {
816                         continue;
817                 }
818                 
819                 this.scan_file(path , next_file.get_display_name());
820                 this.report_state("After scanning %s/%s".printf(path , next_file.get_display_name()));
821                 continue;
822             }
823
824
825             //stdout.printf("Monitor.monitor: got file %s : type :%u\n",
826             //        next_file.get_display_name(), next_file.get_file_type());
827
828
829             if (next_file.get_is_symlink()) {
830                 next_file = null;
831                 continue;
832             }
833             
834             var ds = next_file.get_display_name();
835             if (ds[0] == '.') {
836                 next_file = null;
837                 continue;
838             }
839             if (ds == "attachments") {
840                         continue;
841                 }
842             
843             
844             var sp = path+"/"+next_file.get_display_name();
845             // skip modules.
846             //print("got a file : " + sp);
847          
848             next_file = null;
849             
850             
851             this.scan_dir(sp);
852             
853         }
854     
855     
856     }
857     void report_state(string msg) 
858     {
859         // Saved: 2G  Original 10G : 20%
860         GLib.debug("Saved : %s (%.1f%%) | Original %s | %s", 
861                         GLib.format_size(this.used_space_before - this.used_space_after), 
862                         100f * ((1f * (this.used_space_before - this.used_space_after)) / (this.used_space_before * 1f)), 
863                         GLib.format_size(this.used_space_before),                       
864                         msg
865                 );
866         
867         }
868         
869         
870
871 }