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