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?
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?
24 check if file exists in our DB.. - replace the link...
25 otherwise generate a file. + add to DB...
30 -> URL -> redirect to correct server
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..
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.
44 - {id} attachment_init(
49 // creates or returns id (can look for existing messages?
50 // can do a merge?? - copy 'old' record data into 'new'.... "prefer checksummed"
57 {created} // message date..
62 attachment_update_store(
70 // valac --pkg gmime --vapi
73 // http://www.fromdual.com/mysql-vala-program-example << check mysql if this does not work.
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 \
81 public class StripApplication : GLib.Application {
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;
91 public static int opt_limit = -1;
93 public static int opt_age_newest = 1;
94 public static int opt_age_oldest = 6;
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;
104 public static bool opt_debug_sql = false;
105 public static string? opt_replace_link = null;
108 public const GLib.OptionEntry[] options = {
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 },
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 },
116 { "target-path", 0, 0, OptionArg.STRING, ref opt_target_path, "Directory where attachments are to be put", null },
118 { "link", 0, 0, OptionArg.STRING, ref opt_replace_link, "url for the replement link: eg. http://www.mysite.com/xxxx/%s", null },
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 },
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 },
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 },
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 },
137 public StripApplication( string[] args )
140 application_id: "org.roojs.mailstripper",
141 flags: ApplicationFlags.FLAGS_NONE
145 var opt_context = new GLib.OptionContext ("Mail Stripper");
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;
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);
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);
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);
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);
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);
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);
193 public static int main(string[] args)
196 var application = new StripApplication( args);
198 GLib.Log.set_always_fatal(LogLevelFlags.LEVEL_ERROR | LogLevelFlags.LEVEL_CRITICAL);
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,
210 if (StripApplication.opt_is_replacing) {
211 StripApplication.opt_is_extracting = true;
214 GLib.debug("scanning folder: %s", opt_path );
216 var strip = new Strip( opt_path );
219 strip.mysql = new Mysql.Database();
220 if (!strip.mysql.real_connect(
223 opt_db_pass == null ? "" : opt_db_pass, //passwd
225 3306, // not changable...?
229 stdout.printf("ERROR %u: Connection failed: %s\n",
230 strip.mysql.errno(), strip.mysql.error()
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));
241 strip.scan_dir(opt_path, "");
249 public class Strip : GLib.Object {
253 public string base_dir = "";
255 public Mysql.Database mysql;
259 uint64 used_space_before = 0;
260 uint64 used_space_after = 0;
263 public Strip(string base_dir)
265 this.base_dir = base_dir;
268 public void handle_part(GMime.Object parent, GMime.Object mime_obj)
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();
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");
282 if (cd == null || cd.get_disposition().down() != "attachment") {
285 if (ct.get_media_type() == "text") {
288 if (ct.to_string() == "application/pgp-encrypted") {
291 if (ct.to_string() == "application/pgp-keys") {
294 if (p.get_filename() == null) {
297 // print("got part %s\n", ct.to_string());
298 if (parent is GMime.Multipart) {
300 this.replace_attachment(((GMime.Multipart)parent), p);
308 if (mime_obj is GMime.Multipart) {
311 var mp = (GMime.Multipart)mime_obj;
312 //var ct = mp.get_content_type();
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);
319 // ((GMime.Multipart)mime_obj).foreach((sub_obj) => {
320 // Strip.handle_part(sub_obj);
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);
334 //print("got message-part\n");
338 if (mime_obj is GMime.Message) {
339 var mp = ((GMime.Message) mime_obj).get_mime_part();
341 if (!(mp is GMime.Multipart)) {
342 //GLib.debug("get mimepart does not return a Multipart?");
346 var mpc = ((GMime.Multipart)mp).get_count();
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);
354 print("got message??\n");
358 print("got something else\n");
362 public void update_attachment_db(GMime.Part attachment)
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 ?");
371 // initialize it with known data..
372 // that should wipe out dupes.
373 var matches = this.execute("SELECT count(id) as nid FROM Attachment WHERE id = %d".printf(
378 // our old mailfort code deleted the crap out of old records...
379 // if this occurs we will need to create the record again..
380 this.fix_deleted_attachment_db(int.parse(sid),attachment);
386 // initialize it with known data..
387 // that should wipe out dupes.
388 var filesize = this.execute("SELECT filesize FROM Attachment WHERE id = %d".printf(
392 GLib.error("Ignoring record id (missing in database) :%s", sid);
395 if (int.parse(filesize) < 1) {
396 GLib.debug("Could not get filesize from id :%s = %s", sid,filesize);
401 var chksum = this.query("SELECT checksum FROM Attachment WHERE id = %d".printf(
404 var mime_filename = this.query("SELECT mime_filename FROM Attachment WHERE id = %d".printf(
414 this.mysql_escape(this.active_message_exim_id),
415 this.mysql_escape(chksum),
416 this.mysql_escape(mime_filename),
420 SELECT attachment_update(
421 %d, -- in_id INT(11),
422 '%s', -- in_mime_type varchar(255),
423 '%s', -- in_created DATETIME,
424 '%s' -- in_mailfort_sig varchar(64)
428 "", // this will be ignored..
430 this.mysql_escape(this.active_message_x_mailfort_sig)
434 this.mysql.store_result();
441 public void fix_deleted_attachment_db(int id, GMime.Part attachment)
444 var filename = attachment.get_header("X-strip-content-name");
445 var file_path = attachment.get_header("X-strip-path");
446 var fn = StripApplication.opt_target_path + "/" + file_path;
447 var chksum = this.md5_file(fn);
448 var content_type = attachment.get_header("X-strip-content-type");
450 GLib.error("GOT FN: %s | PATH: %s | CT: %s", filename, file_path, content_type);
454 INSERT INTO Attachments
455 (id, exim_msg?, chksum, filesize)
458 %d, '%s', '%s', '%s', %d
463 this.mysql_escape(this.active_message_exim_id),
464 this.mysql_escape(chksum),
465 this.mysql_escape(mime_filename),
472 public void replace_attachment(GMime.Multipart parent, GMime.Part attachment)
474 var sid = attachment.get_header("X-strip-id");
475 if (sid != null && sid.length > 0) {
476 GLib.debug("Skip attachment replace - it's already been done");
480 var c = attachment.get_content_object();
482 var filename = attachment.get_filename().replace("/", "-").replace("\n", "").replace("\t", " ");
483 var fn = GLib.Environment.get_tmp_dir() +
484 "/"+ this.active_name + "."+ filename;
486 var outfile = new GMime.StreamFile.for_path(fn, "w");
487 outfile.set_owner(true);
488 var file_size = (int) c.write_to_stream(outfile);
489 var chksum = this.md5_file(fn);
493 if (file_size == 0) {
495 GLib.debug("ERROR - file size of write to stream returned 0?");
503 var mime_type= attachment.get_content_type().to_string();
504 // at this point we have to do our database magic...
505 //filesize / name / date / checksum / mimetype -- into mailfort should be OK.
507 var file_id = this.query("""
511 '%s', -- in_msgid VARCHAR(32),
512 '%s', -- in_checksum VARCHAR(64),
513 '%s', -- in_mime_filename varchar(255)
518 this.mysql_escape(this.active_message_exim_id),
520 this.mysql_escape( attachment.get_filename() ), // what is thsi is invalid?
525 if (file_id.length < 1) {
526 GLib.debug("ERROR - CALL to attachment_init failed");
532 if (int.parse(file_id) < 1) {
533 GLib.debug("ERROR - CALL to attachment_init failed - returned 0?");
540 GLib.debug("fn = %s, m5=%s, id= %s", filename, mime_type, this.active_message_id);
543 SELECT attachment_update(
544 %d, -- in_id INT(11),
545 '%s', -- in_mime_type varchar(255),
546 '%s', -- in_created DATETIME,
547 '%s' -- in_mailfort_sig varchar(64)
552 this.mysql_escape(mime_type),
554 this.mysql_escape(this.active_message_x_mailfort_sig)
556 this.mysql.store_result();
559 this.used_space_after += file_size;
563 if (StripApplication.opt_is_extracting) {
564 target_fn = StripApplication.opt_target_path + "/" + this.created_dir +"/"+ file_id + "-" + filename;
567 var stored = "/" + this.created_dir +"/"+ file_id + "-" + filename;
570 SELECT attachment_update_store(
571 %d, -- in_id INT(11),
572 '%s' -- in_store_filename varchar(255),
578 this.mysql_escape( stored)
581 var rep = new GMime.Part.with_type("text","html");
582 // we have to set up a redirect server - to redirect hpasite... to their internal service..
583 rep.set_filename(filename);
584 string txt = "<html><body>"+
585 "<a href=\"" + StripApplication.opt_replace_link + "/" +
586 file_id + "/" + this.created_dir + "/"+chksum+"/"+ GLib.Uri.escape_string( filename) +"\">" +
587 GLib.Uri.escape_string( filename) + // fixme needs html escaping...
591 rep.get_content_type().set_parameter("charset", "utf-8");
592 rep.set_header("X-strip-id", file_id);
593 rep.set_header("X-strip-content-name", filename);
594 rep.set_header("X-strip-path", this.created_dir + "/" + file_id + "-" + filename);
595 rep.set_header("X-strip-content-type", mime_type);
596 var stream = new GMime.StreamMem.with_buffer(txt.data);
597 var con = new GMime.DataWrapper.with_stream(stream,GMime.ContentEncoding.DEFAULT);
599 rep.set_content_object(con);
600 GLib.debug("Replacing Attachment with HTML");
601 parent.replace(parent.index_of(attachment), rep);
602 this.has_replaced = true;
604 if (StripApplication.opt_is_extracting && target_fn.length > 0) {
605 var dir = GLib.Path.get_dirname(target_fn);
606 if (!FileUtils.test (dir, FileTest.IS_DIR)) {
607 GLib.DirUtils.create_with_parents(dir, 0755);
609 GLib.debug("Creating file %s", target_fn);
610 if (!FileUtils.test (target_fn, FileTest.EXISTS)) {
611 var from = File.new_for_path (fn);
612 var to = File.new_for_path (target_fn);
613 from.copy(to, 0, null);
617 GLib.debug("Skipping extraction %s", target_fn);
624 public string query(string str)
626 return this.real_query(true, str);
628 public string execute(string str)
630 return this.real_query(false, str);
632 public string real_query(bool need_return, string str)
634 GLib.debug("Before Query : %u : %s\n", this.mysql.errno(), this.mysql.error());
637 if (StripApplication.opt_debug_sql) {
638 GLib.debug("SQL: %s\n", str);
643 var rc= this.mysql.query(str);
646 GLib.debug("ERROR %u: Query failed: %s\n", this.mysql.errno(), this.mysql.error());
651 var rs = mysql.use_result();
653 //GLib.debug("got %d rows", (int) rs.num_rows());
658 while( (row = rs.fetch_row()) != null) {
664 if (StripApplication.opt_debug_sql) {
665 GLib.debug("got %s", got_row ? "=Nothing=" : ret);
667 return got_row ? "" : ret;
671 GLib.debug("ERROR : no rows returned");
675 if (StripApplication.opt_debug_sql) {
676 GLib.debug("got %s", ret);
683 public string mysql_escape(string str)
685 unichar[] value_escaped = new unichar[str.length * 2 + 1];
686 this.mysql.real_escape_string ((string) value_escaped, str, str.length);
687 return (string) value_escaped;
690 public string md5_file(string fn) {
691 Checksum checksum = new Checksum (ChecksumType.MD5);
693 FileStream stream = FileStream.open (fn, "rb");
697 while ((size = stream.read (fbuf)) > 0) {
698 checksum.update (fbuf, size);
701 unowned string digest = checksum.get_string ();
705 string active_path = "";
706 string active_name = "";
707 string active_message_id = "";
708 string active_message_x_mailfort_sig = "";
709 string active_message_exim_id = "";
710 bool has_replaced = false;
711 string created_date = ""; // should be YYYY-mm-dd
712 string created_dir = ""; // should be YYY/mm/dd
714 public void scan_file(string path, string name)
716 GLib.debug("Scan: %s/%s", path,name);
718 this.has_replaced = false;
719 this.active_path = path;
720 this.active_name = name;
721 this.active_message_id = "";
723 var mailtime = new DateTime.now_local();
724 if (StripApplication.opt_scan_mailfort) {
725 this.created_dir = this.active_path.substring(this.base_dir.length + 1 );
726 this.created_date = this.created_dir.replace("/", "-");
727 var bits = this.created_date.split("-");
728 mailtime = new DateTime.local(int.parse(bits[0]),int.parse(bits[1]),int.parse(bits[2]),0,0,0);
730 var oldest = new DateTime.now_local();
731 oldest = oldest.add_months(-1 * StripApplication.opt_age_oldest);
732 var tspan = mailtime.difference(oldest) / GLib.TimeSpan.DAY;
735 GLib.debug("skip file is %d days older than %d months", (int)tspan, StripApplication.opt_age_oldest);
739 var newest = new DateTime.now_local();
740 newest = newest.add_months(-1 * StripApplication.opt_age_newest);
741 tspan = mailtime.difference(newest) / GLib.TimeSpan.DAY;
743 GLib.debug("skip file is %d days newer than %d months", (int)tspan, StripApplication.opt_age_newest);
750 var fileinfo = File.new_for_path(path +"/" + name)
751 .query_info(GLib.FileAttribute.STANDARD_SIZE+","+GLib.FileAttribute.TIME_MODIFIED
752 ,GLib.FileQueryInfoFlags.NONE,null);
753 var file_size = (int) fileinfo.get_size();
754 var mod_time = fileinfo.get_modification_time();
758 if (!StripApplication.opt_scan_mailfort) {
760 // it's a mail directory...
761 // use the last modification time? as the default...
762 mailtime = new DateTime.from_timeval_utc(mod_time);
763 this.created_dir = mailtime.format("%Y/%m/%d");
764 this.created_date = mailtime.format("%Y-%m-%d %H:%M:%S");
767 // check on age of file...
773 this.used_space_before += file_size;
775 var stream = new GMime.StreamFs.for_path (path +"/" + name,Posix.O_RDONLY, 0);
776 //stream.set_owner(true);
777 var parser = new GMime.Parser.with_stream(stream);
778 var message = parser.construct_message();
780 if (message == null) {
781 GLib.debug("Could not parse file? %s/%s", path,name);
782 this.used_space_after += file_size;
787 // check : - is message over a year old?
788 // get various msg info..
789 this.active_message_id = message.get_message_id();
790 this.active_message_x_mailfort_sig = message.get_header("x-mailfort-sig");
791 var recvd = message.get_header("received");
792 this.active_message_exim_id = "";
793 if (recvd != null && recvd.length > 1) {
794 GLib.debug("RECV: %s", recvd);
795 var lines = recvd.split("\t");
796 for (var i = 0; i < lines.length;i++) {
797 var bits = lines[i].strip().split(" ");
798 if (bits[0] == "id") {
799 this.active_message_exim_id = bits[1].replace(";","");
803 if (lines[i].contains(";")) {
804 var dbits = lines[i].strip().split(";");
805 GLib.debug("Reading time from : %s", dbits[1]);
806 var timez = GMime.utils_header_decode_date(dbits[1], null);
808 mailtime = new DateTime.from_unix_utc(timez);
809 this.created_date = mailtime.format("%Y-%m-%d %H:%M:%S");
810 GLib.debug("Time is %s",this.created_date);
811 // if it's not mailfort we can use that date to determine where to store it...
812 if (!StripApplication.opt_scan_mailfort) {
813 this.created_dir = mailtime.format("%Y/%m/%d");
816 GLib.debug("Could not read time from headers?");
823 var oldest = new DateTime.now_local();
824 oldest = oldest.add_months(-1 * StripApplication.opt_age_oldest);
825 var rtspan = mailtime.difference(oldest) / GLib.TimeSpan.DAY;
826 GLib.debug("Checking oldest %d days difference", (int)rtspan );
828 GLib.debug("skip(2) file is %d days older than %d months", (int)rtspan, StripApplication.opt_age_oldest);
831 var newest = new DateTime.now_local();
832 newest = newest.add_months(-1 * StripApplication.opt_age_newest);
833 rtspan = mailtime.difference(newest) / GLib.TimeSpan.DAY;
835 GLib.debug("skip(2) file is %d days newer than %d months : %s", (int)rtspan, StripApplication.opt_age_newest,
836 mailtime.format("%Y-%m-%d %H:%M:%S"));
843 GLib.debug("Message DATA:\n mid: %s\nmailfort: %s \nexim_id: %s",
844 this.active_message_id,
845 this.active_message_x_mailfort_sig,
846 this.active_message_exim_id
852 var mp = message.get_mime_part();
854 if (!(mp is GMime.Multipart)) {
855 //GLib.debug("get mimepart does not return a Multipart?");
856 this.used_space_after += file_size;
860 var mpc = ((GMime.Multipart)mp).get_count();
862 //GLib.debug("Message has %d parts", mpc);
863 for (var i =0 ; i < mpc; i++) {
864 //GLib.debug("Getting part %d", i);
865 var mime_obj = ((GMime.Multipart)mp).get_part(i);
866 this.handle_part(mp,mime_obj);
871 // stream.set_owner(false);
873 stream = null;//.close();
876 if (!this.has_replaced) {
877 this.used_space_after += file_size;
878 GLib.debug("skpping write file - no replacement occured");
882 GMime.Stream outstream = new GMime.StreamNull();
883 if (StripApplication.opt_is_replacing) {
885 tmpfile = GLib.Environment.get_tmp_dir() +"/" + name;
886 outstream = new GMime.StreamFile.for_path (tmpfile,"w");
887 ((GMime.StreamFile)outstream).set_owner(true);
889 if (StripApplication.opt_dump) {
890 outstream = new GMime.StreamMem();
893 file_size = (int) message.write_to_stream(outstream);
894 if (StripApplication.opt_is_replacing) {
895 ((GMime.StreamFile)outstream).set_owner(false);
897 if (StripApplication.opt_dump) {
898 var ua = ((GMime.StreamMem)outstream).get_byte_array().data;
899 print("%s\n", (string) ua);
904 GLib.debug("finished writing output %d", file_size);
910 this.used_space_after += file_size;
913 if (StripApplication.opt_is_replacing) {
914 Posix.unlink(path +"/" + name);
915 GLib.debug("copy tmp file %s to %s" , tmpfile, path +"/" + name);
917 // link will not work, as we are doing it accross file systems
918 var from = File.new_for_path (tmpfile);
919 var nf = File.new_for_path (path +"/" + name);
920 from.copy(nf, 0, null);
923 var newfileinfo = nf.query_info(GLib.FileAttribute.TIME_MODIFIED,GLib.FileQueryInfoFlags.NONE,null);
924 newfileinfo.set_modification_time(mod_time);
925 nf.set_attributes_from_info(newfileinfo,FileQueryInfoFlags.NONE);
926 Posix.unlink(tmpfile);
930 if (StripApplication.opt_limit > -1 && this.processed >= StripApplication.opt_limit) {
931 GLib.debug("Reached replacement limit");
941 public void scan_dir(string basepath, string subpath)
945 // determine if path is to old to scan..
946 if (subpath.length > 0 && StripApplication.opt_scan_mailfort) {
947 var year = int.parse(subpath.substring(1,4)); // "/2000"
948 var month = subpath.length > 5 ? int.parse(subpath.substring(6,2)) : 999; // "/2000/12"
949 var day = subpath.length > 8 ? int.parse(subpath.substring(9,2)) : 999; // "/2000/12/01"
951 var oldest = new DateTime.now_local();
952 oldest = oldest.add_months(-1 * StripApplication.opt_age_oldest);
954 //GLib.debug("Checking directory %s is older than min: %d/%d/%d", subpath, oldest.get_year() , oldest.get_month(), oldest.get_day_of_month() );
956 if (year < oldest.get_year()) {
957 GLib.debug("Skip directory %s is older than min year: %d", subpath, oldest.get_year());
960 if (year == oldest.get_year() && month < oldest.get_month()) {
961 GLib.debug("Skip directory %s is older than min month: %d/%d", subpath, oldest.get_year() , oldest.get_month() );
964 if (year == oldest.get_year() && month == oldest.get_month() && day < oldest.get_day_of_month()) {
965 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() );
969 var newest = new DateTime.now_local();
970 newest = newest.add_months(-1 * StripApplication.opt_age_newest);
972 //GLib.debug("Checking directory %s is newer than max: %d/%d/%d", subpath, newest.get_year() , newest.get_month(), newest.get_day_of_month() );
974 if (year > newest.get_year()) {
975 GLib.debug("Skip directory %s is newer than max year: %d", subpath, newest.get_year());
978 if (year == newest.get_year() && month != 999 && month > newest.get_month()) {
979 GLib.debug("Skip directory %s is newer than max month: %d/%d", subpath, newest.get_year() , newest.get_month() );
982 if (year == newest.get_year() && month == newest.get_month() && day != 999 && day > newest.get_day_of_month()) {
983 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() );
992 var f = File.new_for_path(basepath + subpath);
993 FileEnumerator file_enum;
994 var cancellable = new Cancellable ();
996 file_enum = f.enumerate_children(
997 FileAttribute.STANDARD_DISPLAY_NAME + "," + FileAttribute.STANDARD_TYPE,
998 FileQueryInfoFlags.NOFOLLOW_SYMLINKS, // FileQueryInfoFlags.NONE,
1002 GLib.debug("Got error scanning dir? %s", e.message);
1003 // FIXME - show error..
1008 while (cancellable.is_cancelled () == false ) {
1010 next_file = file_enum.next_file (cancellable);
1012 GLib.debug("error getting next file? %s", e.message);
1016 if (next_file == null) {
1021 if (next_file.get_is_symlink()) {
1026 var ds = next_file.get_display_name();
1027 if (next_file.get_file_type() != FileType.DIRECTORY) {
1034 // other files to ignore?
1035 if (Regex.match_simple (".tgz$", ds)) {
1038 this.scan_file(basepath + subpath , ds);
1039 if(this.has_replaced) {
1040 this.report_state("After scanning %s/%s".printf(basepath + subpath , ds));
1046 //stdout.printf("Monitor.monitor: got file %s : type :%u\n",
1047 // next_file.get_display_name(), next_file.get_file_type());
1052 // not really needed?? - we are storing attachments in a seperate location now...
1057 if (ds == "attachments") {
1062 var sp = subpath+"/"+next_file.get_display_name();
1064 //print("got a file : " + sp);
1069 this.scan_dir(basepath,sp);
1075 void report_state(string msg)
1077 // Saved: 2G Original 10G : 20%
1078 GLib.debug("Saved : %s (%.1f%%) | Original %s | %s",
1079 GLib.format_size(this.used_space_before - this.used_space_after),
1080 100f * ((1f * (this.used_space_before - this.used_space_after)) / (this.used_space_before * 1f)),
1081 GLib.format_size(this.used_space_before),