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;
90 public static string? opt_scan_mailfort_only = "";
93 public static int opt_limit = -1;
95 public static int opt_age_newest = 1;
96 public static int opt_age_oldest = 6;
99 public static bool opt_is_extracting = false;
100 public static bool opt_is_replacing = false;
101 public static bool opt_scan_maildir = false;
102 public static bool opt_scan_mailfort = false;
103 public static bool opt_dump = false;
104 public static bool opt_debug = false;
105 public static bool opt_stamp = false;
107 public static bool opt_debug_sql = false;
108 public static string? opt_replace_link = null;
111 public const GLib.OptionEntry[] options = {
113 { "debug", 0, 0, OptionArg.NONE, ref opt_debug, "show debug messages for components", null },
114 { "debug-sql", 0, 0, OptionArg.NONE, ref opt_debug_sql, "debug the SQL statements", null },
116 { "path", 0, 0, OptionArg.STRING, ref opt_path, "Directory where email to be parsed is", null },
117 { "file", 0, 0, OptionArg.STRING, ref opt_file, "A specific file to be parsed", null },
119 { "target-path", 0, 0, OptionArg.STRING, ref opt_target_path, "Directory where attachments are to be put", null },
121 { "link", 0, 0, OptionArg.STRING, ref opt_replace_link, "url for the replement link: eg. http://www.mysite.com/xxxx/%s", null },
123 { "host", 0, 0, OptionArg.STRING, ref opt_db_host, "Mysql host (default localhost)", null },
124 { "name", 0, 0, OptionArg.STRING, ref opt_db_name, "Mysql database name REQUIRED", null },
125 { "user", 0, 0, OptionArg.STRING, ref opt_db_user, "Mysql database user REQUIRED", null },
126 { "pass", 0, 0, OptionArg.STRING, ref opt_db_pass, "Mysql database password (default empty)", null },
128 { "extract", 0, 0, OptionArg.NONE, ref opt_is_extracting, "Should attachments be extracted (default NO)", null },
129 { "replace", 0, 0, OptionArg.NONE, ref opt_is_replacing, "Should attachments be replaced (default NO)", null },
130 { "dump", 0, 0, OptionArg.NONE, ref opt_dump, "Print the replaced mail contents to stdout", null },
132 { "limit", 0, 0, OptionArg.INT, ref opt_limit, "stop after X number of messages with attachments have been processed", null },
133 { "newest", 0, 0, OptionArg.INT, ref opt_age_newest, "do not replace messages newer that X months (default is 1 months)", null },
134 { "oldest", 0, 0, OptionArg.INT, ref opt_age_oldest, "do not replace messages older than X (default is 6 months)", null },
136 { "scan-maildir", 0, 0, OptionArg.NONE, ref opt_scan_maildir, "scan an maildir tree", null },
137 { "stamp", 0, 0, OptionArg.NONE, ref opt_stamp, "create and honour directory stamps - flag that a folder has been scanned already", null },
138 { "scan-mailfort", 0, 0, OptionArg.NONE, ref opt_scan_mailfort, "scan a mailfort tree", null },
139 { "scan-mailfort-only", 0, 0, OptionArg.STRING, ref opt_scan_mailfort_only, "scan a mailfort Year/month eg. /2010/08", null },
142 public StripApplication( string[] args )
145 application_id: "org.roojs.mailstripper",
146 flags: ApplicationFlags.FLAGS_NONE
150 var opt_context = new GLib.OptionContext ("Mail Stripper");
154 opt_context.set_help_enabled (true);
155 opt_context.add_main_entries (options, null);
156 opt_context.parse ( ref args);
157 //opt_detach = !optx_no_detach;
161 // options that have to be set.. bee or hive... (or stop all)
162 if ((!opt_scan_mailfort && !opt_scan_maildir) || (opt_scan_mailfort && opt_scan_maildir)) {
163 stdout.printf ("You must specify the type of directory tree to scan - either imap or mailfort\n%s",
164 opt_context.get_help(true, null));
165 GLib.Process.exit(Posix.EXIT_FAILURE);
168 if ((opt_db_name == null || opt_db_name.length < 1 || opt_db_user == null || opt_db_user.length < 1)) {
169 stdout.printf ("You must specify the database name / user \n%s",
170 opt_context.get_help(true, null));
171 GLib.Process.exit(Posix.EXIT_FAILURE);
173 if ((opt_path == null || opt_path.length < 1) ) {
174 stdout.printf ("You must specify the scan start path\n%s",
175 opt_context.get_help(true, null));
176 GLib.Process.exit(Posix.EXIT_FAILURE);
178 if (opt_replace_link == null || (opt_replace_link.length < 1)) {
179 stdout.printf ("You must specify the link to use in the replacement \n%s",
180 opt_context.get_help(true, null));
181 GLib.Process.exit(Posix.EXIT_FAILURE);
183 if ((opt_is_replacing || opt_is_extracting ) && (opt_target_path == null || opt_target_path.length < 1)) {
184 stdout.printf ("You must specify a target path to put attachments\n%s",
185 opt_context.get_help(true, null));
186 GLib.Process.exit(Posix.EXIT_FAILURE);
190 } catch (GLib.OptionError e) {
191 stdout.printf ("error: %s\n", e.message);
192 stdout.printf ("Run '%s --help' to see a full list of available command line options.\n%s",
193 args[0], opt_context.get_help(true, null));
194 GLib.Process.exit(Posix.EXIT_FAILURE);
198 public static int main(string[] args)
201 var application = new StripApplication( args);
203 GLib.Log.set_always_fatal(LogLevelFlags.LEVEL_ERROR | LogLevelFlags.LEVEL_CRITICAL);
205 if (opt_debug || opt_debug_sql) {
206 GLib.Log.set_handler(null,
207 GLib.LogLevelFlags.LEVEL_DEBUG | GLib.LogLevelFlags.LEVEL_WARNING | GLib.LogLevelFlags.LEVEL_INFO,
215 if (StripApplication.opt_is_replacing) {
216 StripApplication.opt_is_extracting = true;
219 GLib.debug("scanning folder: %s", opt_path );
221 var strip = new Strip( opt_path );
224 strip.mysql = new Mysql.Database();
225 if (!strip.mysql.real_connect(
228 opt_db_pass == null ? "" : opt_db_pass, //passwd
230 3306, // not changable...?
234 stdout.printf("ERROR %u: Connection failed: %s\n",
235 strip.mysql.errno(), strip.mysql.error()
240 if (opt_file != null) {
241 strip.base_dir = opt_path;
242 strip.scan_file( GLib.Path.get_dirname(opt_file), GLib.Path.get_basename(opt_file));
246 strip.scan_dir(opt_path, opt_scan_mailfort_only);
254 public class Strip : GLib.Object {
258 public string base_dir = "";
260 public Mysql.Database mysql;
264 uint64 used_space_before = 0;
265 uint64 used_space_after = 0;
268 public Strip(string base_dir)
270 this.base_dir = base_dir;
273 public void handle_part(GMime.Object parent, GMime.Object mime_obj)
275 if (mime_obj is GMime.Part) {
276 var p = (GMime.Part)mime_obj;
277 var ct = p.get_content_type();
278 var cd = p.get_content_disposition();
280 var sid = p.get_header("X-strip-id");
281 if (sid != null && sid.length > 0) {
282 this.update_attachment_db(p);
283 GLib.debug("Skip attachment replace - it's already been done");
287 if (cd == null || cd.get_disposition().down() != "attachment") {
290 if (ct.get_media_type() == "text") {
293 if (ct.to_string() == "application/pgp-encrypted") {
296 if (ct.to_string() == "application/pgp-keys") {
299 if (p.get_filename() == null) {
302 // print("got part %s\n", ct.to_string());
303 if (parent is GMime.Multipart) {
305 this.replace_attachment(((GMime.Multipart)parent), p);
313 if (mime_obj is GMime.Multipart) {
316 var mp = (GMime.Multipart)mime_obj;
317 //var ct = mp.get_content_type();
319 //print("got multi-part %s\n", ct.to_string());
320 for (var i = 0; i< mp.get_count(); i++) {
321 var mo = mp.get_part(i);
322 this.handle_part(mime_obj,mo);
324 // ((GMime.Multipart)mime_obj).foreach((sub_obj) => {
325 // Strip.handle_part(sub_obj);
333 if (mime_obj is GMime.MessagePart) {
334 var msg = ((GMime.MessagePart)mime_obj).get_message();
335 msg.foreach((subobj) => {
336 this.handle_part(msg,subobj);
339 //print("got message-part\n");
343 if (mime_obj is GMime.Message) {
344 var mp = ((GMime.Message) mime_obj).get_mime_part();
346 if (!(mp is GMime.Multipart)) {
347 //GLib.debug("get mimepart does not return a Multipart?");
351 var mpc = ((GMime.Multipart)mp).get_count();
353 //GLib.debug("Message has %d parts", mpc);
354 for (var i =0 ; i < mpc; i++) {
355 //GLib.debug("Getting part %d", i);
356 var submime_obj = ((GMime.Multipart)mp).get_part(i);
357 this.handle_part(mp,submime_obj);
359 print("got message??\n");
363 print("got something else\n");
367 public void update_attachment_db(GMime.Part attachment)
369 // only called when we have an sid...
370 var sid = attachment.get_header("X-strip-id");
371 if (sid == null || sid.length < 1) {
372 GLib.debug("Strange - update attachment db called ?");
376 // initialize it with known data..
377 // that should wipe out dupes.
378 var matches = this.query("SELECT count(id) FROM Attachment WHERE id = %d".printf(
382 if (matches == "0") {
383 // our old mailfort code deleted the crap out of old records...
384 // if this occurs we will need to create the record again..
385 this.fix_deleted_attachment_db(int.parse(sid),attachment);
391 // initialize it with known data..
392 // that should wipe out dupes.
393 var filesize = this.query("SELECT filesize FROM Attachment WHERE id = %d".printf(
397 GLib.error("Ignoring record id (missing in database) :%s", sid);
400 if (int.parse(filesize) < 1) {
401 GLib.debug("Could not get filesize from id :%s = %s", sid,filesize);
406 var chksum = this.query("SELECT checksum FROM Attachment WHERE id = %d".printf(
409 var mime_filename = this.query("SELECT mime_filename FROM Attachment WHERE id = %d".printf(
419 this.mysql_escape(this.active_message_exim_id),
420 this.mysql_escape(chksum),
421 this.mysql_escape(mime_filename),
425 SELECT attachment_update(
426 %d, -- in_id INT(11),
427 '%s', -- in_mime_type varchar(255),
428 '%s', -- in_created DATETIME,
429 '%s' -- in_mailfort_sig varchar(64)
433 "", // this will be ignored..
435 this.mysql_escape(this.active_message_x_mailfort_sig)
439 this.mysql.store_result();
446 public void fix_deleted_attachment_db(int id, GMime.Part attachment)
449 var filename = attachment.get_header("X-strip-content-name");
450 var file_path = attachment.get_header("X-strip-path");
451 var fn = StripApplication.opt_target_path + "/" + file_path;
454 if (!FileUtils.test (fn, FileTest.EXISTS)) {
455 GLib.debug("SKIP -- file does not exist");
459 var chksum = this.md5_file(fn);
460 var mime_type = attachment.get_header("X-strip-content-type");
462 var fileinfo = File.new_for_path(fn)
463 .query_info(GLib.FileAttribute.STANDARD_SIZE+","+GLib.FileAttribute.TIME_MODIFIED
464 ,GLib.FileQueryInfoFlags.NONE,null);
465 var file_size = (int) fileinfo.get_size();
468 this.real_query(-1, """
471 INSERT INTO Attachment (
500 '%s', -- stored file anme
516 this.mysql_escape(this.active_message_exim_id),
517 this.mysql_escape(filename),
518 this.mysql_escape(mime_type),
519 this.mysql_escape(file_path),
522 this.mysql_escape(chksum),
525 // this is done to fix the queue_id or maillog_id ??
527 SELECT attachment_update(
528 %d, -- in_id INT(11),
530 '%s', -- in_created DATETIME,
531 '%s' -- in_mailfort_sig varchar(64)
536 this.mysql_escape(this.active_message_x_mailfort_sig)
540 // GLib.error("added attachment?");
544 public void replace_attachment(GMime.Multipart parent, GMime.Part attachment)
546 var sid = attachment.get_header("X-strip-id");
547 if (sid != null && sid.length > 0) {
548 GLib.debug("Skip attachment replace - it's already been done");
552 var c = attachment.get_content_object();
554 var filename = attachment.get_filename().replace("/", "-").replace("\n", "").replace("\t", " ");
555 var fn = GLib.Environment.get_tmp_dir() +
556 "/"+ this.active_name + "."+ GLib.Uri.escape_string(filename,"", false);
558 var outfile = new GMime.StreamFile.for_path(fn, "w");
559 outfile.set_owner(true);
560 var file_size = (int) c.write_to_stream(outfile);
561 var chksum = this.md5_file(fn);
565 if (file_size == 0) {
567 GLib.debug("ERROR - file size of write to stream returned 0?");
575 var mime_type= attachment.get_content_type().to_string();
576 // at this point we have to do our database magic...
577 //filesize / name / date / checksum / mimetype -- into mailfort should be OK.
579 var file_id = this.query("""
583 '%s', -- in_msgid VARCHAR(32),
584 '%s', -- in_checksum VARCHAR(64),
585 '%s', -- in_mime_filename varchar(255)
590 this.mysql_escape(this.active_message_exim_id),
592 this.mysql_escape( GLib.Uri.escape_string(attachment.get_filename(),"", false) ), // what is thsi is invalid?
597 if (file_id.length < 1) {
598 GLib.debug("ERROR - CALL to attachment_init failed");
604 if (int.parse(file_id) < 1) {
605 GLib.debug("ERROR - CALL to attachment_init failed - returned 0?");
612 GLib.debug("fn = %s, m5=%s, id= %s", filename, mime_type, this.active_message_id);
615 SELECT attachment_update(
616 %d, -- in_id INT(11),
617 '%s', -- in_mime_type varchar(255),
618 '%s', -- in_created DATETIME,
619 '%s' -- in_mailfort_sig varchar(64)
624 this.mysql_escape(mime_type),
626 this.mysql_escape(this.active_message_x_mailfort_sig)
628 this.mysql.store_result();
631 this.used_space_after += file_size;
635 if (StripApplication.opt_is_extracting) {
636 target_fn = StripApplication.opt_target_path + "/" + this.created_dir +"/"+ file_id + "-" + GLib.Uri.escape_string(filename,"", false);
639 var stored = "/" + this.created_dir +"/"+ file_id + "-" + GLib.Uri.escape_string(filename,"", false);
642 SELECT attachment_update_store(
643 %d, -- in_id INT(11),
644 '%s' -- in_store_filename varchar(255),
650 this.mysql_escape( stored)
653 var rep = new GMime.Part.with_type("text","html");
654 // we have to set up a redirect server - to redirect hpasite... to their internal service..
655 rep.set_filename(filename);
656 string txt = "<html><body>"+
657 "<a href=\"" + StripApplication.opt_replace_link + "/" +
658 file_id + "/" + this.created_dir + "/"+chksum+"/"+ GLib.Uri.escape_string( filename, "", false) +"\">" +
659 GLib.Uri.escape_string( filename, "", false) + // fixme needs html escaping...
663 rep.get_content_type().set_parameter("charset", "utf-8");
664 rep.set_header("X-strip-id", file_id);
665 rep.set_header("X-strip-content-name", filename);
666 rep.set_header("X-strip-path", this.created_dir + "/" + file_id + "-" + GLib.Uri.escape_string(filename,"", false));
667 rep.set_header("X-strip-content-type", mime_type);
668 var stream = new GMime.StreamMem.with_buffer(txt.data);
669 var con = new GMime.DataWrapper.with_stream(stream,GMime.ContentEncoding.DEFAULT);
671 rep.set_content_object(con);
672 GLib.debug("Replacing Attachment with HTML");
673 parent.replace(parent.index_of(attachment), rep);
674 this.has_replaced = true;
676 if (StripApplication.opt_is_extracting && target_fn.length > 0) {
677 var dir = GLib.Path.get_dirname(target_fn);
678 if (!FileUtils.test (dir, FileTest.IS_DIR)) {
679 GLib.DirUtils.create_with_parents(dir, 0755);
681 GLib.debug("Creating file %s", target_fn);
682 if (!FileUtils.test (target_fn, FileTest.EXISTS)) {
683 var from = File.new_for_path (fn);
684 var to = File.new_for_path (target_fn);
685 from.copy(to, 0, null);
689 GLib.debug("Skipping extraction %s", target_fn);
696 public string query(string str)
698 return this.real_query(1, str);
700 public string execute(string str)
702 return this.real_query(0, str);
710 public string real_query(int need_return, string str)
712 GLib.debug("Before Query : %u : %s\n", this.mysql.errno(), this.mysql.error());
715 if (StripApplication.opt_debug_sql) {
716 GLib.debug("SQL: %s\n", str);
721 var rc= this.mysql.query(str);
724 GLib.debug("ERROR %u: Query failed: %s\n", this.mysql.errno(), this.mysql.error());
727 var rs = mysql.use_result();
728 if (need_return == -1) {
733 //GLib.debug("got %d rows", (int) rs.num_rows());
738 while( (row = rs.fetch_row()) != null) {
743 if (need_return == 0) {
744 if (StripApplication.opt_debug_sql) {
745 GLib.debug("got %s", got_row ? "=Nothing=" : ret);
747 return got_row ? "" : ret;
751 GLib.debug("ERROR : no rows returned");
755 if (StripApplication.opt_debug_sql) {
756 GLib.debug("got %s", ret);
763 public string mysql_escape(string str)
765 unichar[] value_escaped = new unichar[str.length * 2 + 1];
766 this.mysql.real_escape_string ((string) value_escaped, str, str.length);
767 return (string) value_escaped;
770 public string md5_file(string fn) {
771 Checksum checksum = new Checksum (ChecksumType.MD5);
773 FileStream stream = FileStream.open (fn, "rb");
777 while ((size = stream.read (fbuf)) > 0) {
778 checksum.update (fbuf, size);
781 unowned string digest = checksum.get_string ();
785 string active_path = "";
786 string active_name = "";
787 string active_message_id = "";
788 string active_message_x_mailfort_sig = "";
789 string active_message_exim_id = "";
790 bool has_replaced = false;
791 string created_date = ""; // should be YYYY-mm-dd
792 string created_dir = ""; // should be YYY/mm/dd
794 public void scan_file(string path, string name)
796 GLib.debug("Scan: %s/%s", path,name);
798 this.has_replaced = false;
799 this.active_path = path;
800 this.active_name = name;
801 this.active_message_id = "";
803 var mailtime = new DateTime.now_local();
804 if (StripApplication.opt_scan_mailfort) {
805 this.created_dir = this.active_path.substring(this.base_dir.length + 1 );
806 this.created_date = this.created_dir.replace("/", "-");
807 var bits = this.created_date.split("-");
808 mailtime = new DateTime.local(int.parse(bits[0]),int.parse(bits[1]),int.parse(bits[2]),0,0,0);
810 var oldest = new DateTime.now_local();
811 oldest = oldest.add_months(-1 * StripApplication.opt_age_oldest);
812 var tspan = mailtime.difference(oldest) / GLib.TimeSpan.DAY;
815 GLib.debug("skip file is %d days older than %d months", (int)tspan, StripApplication.opt_age_oldest);
819 var newest = new DateTime.now_local();
820 newest = newest.add_months(-1 * StripApplication.opt_age_newest);
821 tspan = mailtime.difference(newest) / GLib.TimeSpan.DAY;
823 GLib.debug("skip file is %d days newer than %d months", (int)tspan, StripApplication.opt_age_newest);
830 var fileinfo = File.new_for_path(path +"/" + name)
831 .query_info(GLib.FileAttribute.STANDARD_SIZE+","+GLib.FileAttribute.TIME_MODIFIED
832 ,GLib.FileQueryInfoFlags.NONE,null);
833 var file_size = (int) fileinfo.get_size();
834 var mod_time = fileinfo.get_modification_time();
838 if (!StripApplication.opt_scan_mailfort) {
840 // it's a mail directory...
841 // use the last modification time? as the default...
842 mailtime = new DateTime.from_timeval_utc(mod_time);
843 this.created_dir = mailtime.format("%Y/%m/%d");
844 this.created_date = mailtime.format("%Y-%m-%d %H:%M:%S");
847 // check on age of file...
853 this.used_space_before += file_size;
855 var stream = new GMime.StreamFs.for_path (path +"/" + name,Posix.O_RDONLY, 0);
856 //stream.set_owner(true);
857 var parser = new GMime.Parser.with_stream(stream);
858 var message = parser.construct_message();
860 if (message == null) {
861 GLib.debug("Could not parse file? %s/%s", path,name);
862 this.used_space_after += file_size;
867 // check : - is message over a year old?
868 // get various msg info..
869 this.active_message_id = message.get_message_id();
870 this.active_message_x_mailfort_sig = message.get_header("x-mailfort-sig");
871 var recvd = message.get_header("received");
872 this.active_message_exim_id = "";
873 if (recvd != null && recvd.length > 1) {
874 GLib.debug("RECV: %s", recvd);
875 var lines = recvd.split("\t");
876 for (var i = 0; i < lines.length;i++) {
877 var bits = lines[i].strip().split(" ");
878 if (bits[0] == "id") {
879 this.active_message_exim_id = bits[1].replace(";","");
883 if (lines[i].contains(";")) {
884 var dbits = lines[i].strip().split(";");
885 GLib.debug("Reading time from : %s", dbits[1]);
886 var timez = GMime.utils_header_decode_date(dbits[1], null);
888 mailtime = new DateTime.from_unix_utc(timez);
889 this.created_date = mailtime.format("%Y-%m-%d %H:%M:%S");
890 GLib.debug("Time is %s",this.created_date);
891 // if it's not mailfort we can use that date to determine where to store it...
892 if (!StripApplication.opt_scan_mailfort) {
893 this.created_dir = mailtime.format("%Y/%m/%d");
896 GLib.debug("Could not read time from headers?");
903 var oldest = new DateTime.now_local();
904 oldest = oldest.add_months(-1 * StripApplication.opt_age_oldest);
905 var rtspan = mailtime.difference(oldest) / GLib.TimeSpan.DAY;
906 GLib.debug("Checking oldest %d days difference", (int)rtspan );
908 GLib.debug("skip(2) file is %d days older than %d months", (int)rtspan, StripApplication.opt_age_oldest);
911 var newest = new DateTime.now_local();
912 newest = newest.add_months(-1 * StripApplication.opt_age_newest);
913 rtspan = mailtime.difference(newest) / GLib.TimeSpan.DAY;
915 GLib.debug("skip(2) file is %d days newer than %d months : %s", (int)rtspan, StripApplication.opt_age_newest,
916 mailtime.format("%Y-%m-%d %H:%M:%S"));
923 GLib.debug("Message DATA:\n mid: %s\nmailfort: %s \nexim_id: %s",
924 this.active_message_id,
925 this.active_message_x_mailfort_sig,
926 this.active_message_exim_id
932 var mp = message.get_mime_part();
934 if (!(mp is GMime.Multipart)) {
935 //GLib.debug("get mimepart does not return a Multipart?");
936 this.used_space_after += file_size;
940 var mpc = ((GMime.Multipart)mp).get_count();
942 //GLib.debug("Message has %d parts", mpc);
943 for (var i =0 ; i < mpc; i++) {
944 //GLib.debug("Getting part %d", i);
945 var mime_obj = ((GMime.Multipart)mp).get_part(i);
946 this.handle_part(mp,mime_obj);
951 // stream.set_owner(false);
953 stream = null;//.close();
956 if (!this.has_replaced) {
957 this.used_space_after += file_size;
958 GLib.debug("skpping write file - no replacement occured");
962 GMime.Stream outstream = new GMime.StreamNull();
963 if (StripApplication.opt_is_replacing) {
965 tmpfile = GLib.Environment.get_tmp_dir() +"/" + name;
966 outstream = new GMime.StreamFile.for_path (tmpfile,"w");
967 ((GMime.StreamFile)outstream).set_owner(true);
969 if (StripApplication.opt_dump) {
970 outstream = new GMime.StreamMem();
973 file_size = (int) message.write_to_stream(outstream);
974 if (StripApplication.opt_is_replacing) {
975 ((GMime.StreamFile)outstream).set_owner(false);
977 if (StripApplication.opt_dump) {
978 var ua = ((GMime.StreamMem)outstream).get_byte_array().data;
979 print("%s\n", (string) ua);
984 GLib.debug("finished writing output %d", file_size);
990 this.used_space_after += file_size;
993 if (StripApplication.opt_is_replacing) {
994 Posix.unlink(path +"/" + name);
995 GLib.debug("copy tmp file %s to %s" , tmpfile, path +"/" + name);
997 // link will not work, as we are doing it accross file systems
998 var from = File.new_for_path (tmpfile);
999 var nf = File.new_for_path (path +"/" + name);
1000 from.copy(nf, 0, null);
1003 var newfileinfo = nf.query_info(GLib.FileAttribute.TIME_MODIFIED,GLib.FileQueryInfoFlags.NONE,null);
1004 newfileinfo.set_modification_time(mod_time);
1005 nf.set_attributes_from_info(newfileinfo,FileQueryInfoFlags.NONE);
1006 Posix.unlink(tmpfile);
1010 if (StripApplication.opt_limit > -1 && this.processed >= StripApplication.opt_limit) {
1011 GLib.debug("Reached replacement limit");
1021 public void scan_dir(string basepath, string subpath)
1025 // determine if path is to old to scan..
1026 if (subpath.length > 0 && StripApplication.opt_scan_mailfort) {
1027 var year = int.parse(subpath.substring(1,4)); // "/2000"
1028 var month = subpath.length > 5 ? int.parse(subpath.substring(6,2)) : 999; // "/2000/12"
1029 var day = subpath.length > 8 ? int.parse(subpath.substring(9,2)) : 999; // "/2000/12/01"
1031 var oldest = new DateTime.now_local();
1032 oldest = oldest.add_months(-1 * StripApplication.opt_age_oldest);
1034 //GLib.debug("Checking directory %s is older than min: %d/%d/%d", subpath, oldest.get_year() , oldest.get_month(), oldest.get_day_of_month() );
1036 if (year < oldest.get_year()) {
1037 GLib.debug("Skip directory %s is older than min year: %d", subpath, oldest.get_year());
1040 if (year == oldest.get_year() && month < oldest.get_month()) {
1041 GLib.debug("Skip directory %s is older than min month: %d/%d", subpath, oldest.get_year() , oldest.get_month() );
1044 if (year == oldest.get_year() && month == oldest.get_month() && day < oldest.get_day_of_month()) {
1045 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() );
1049 var newest = new DateTime.now_local();
1050 newest = newest.add_months(-1 * StripApplication.opt_age_newest);
1052 //GLib.debug("Checking directory %s is newer than max: %d/%d/%d", subpath, newest.get_year() , newest.get_month(), newest.get_day_of_month() );
1054 if (year > newest.get_year()) {
1055 GLib.debug("Skip directory %s is newer than max year: %d", subpath, newest.get_year());
1058 if (year == newest.get_year() && month != 999 && month > newest.get_month()) {
1059 GLib.debug("Skip directory %s is newer than max month: %d/%d", subpath, newest.get_year() , newest.get_month() );
1062 if (year == newest.get_year() && month == newest.get_month() && day != 999 && day > newest.get_day_of_month()) {
1063 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() );
1071 if (GLib.FileUtils.test( basepath + subpath + ".strip-done-stamp", GLib.FileTest.EXISTS )) {
1076 var f = File.new_for_path(basepath + subpath);
1077 FileEnumerator file_enum;
1078 var cancellable = new Cancellable ();
1080 file_enum = f.enumerate_children(
1081 FileAttribute.STANDARD_DISPLAY_NAME + "," + FileAttribute.STANDARD_TYPE,
1082 FileQueryInfoFlags.NOFOLLOW_SYMLINKS, // FileQueryInfoFlags.NONE,
1086 GLib.debug("Got error scanning dir? %s", e.message);
1087 // FIXME - show error..
1092 while (cancellable.is_cancelled () == false ) {
1094 next_file = file_enum.next_file (cancellable);
1096 GLib.debug("error getting next file? %s", e.message);
1100 if (next_file == null) {
1105 if (next_file.get_is_symlink()) {
1110 var ds = next_file.get_display_name();
1111 if (next_file.get_file_type() != FileType.DIRECTORY) {
1118 // other files to ignore?
1119 if (Regex.match_simple (".tgz$", ds)) {
1122 this.scan_file(basepath + subpath , ds);
1123 if(this.has_replaced) {
1124 this.report_state("After scanning %s/%s".printf(basepath + subpath , ds));
1130 //stdout.printf("Monitor.monitor: got file %s : type :%u\n",
1131 // next_file.get_display_name(), next_file.get_file_type());
1136 // not really needed?? - we are storing attachments in a seperate location now...
1141 if (ds == "attachments") {
1146 var sp = subpath+"/"+next_file.get_display_name();
1148 //print("got a file : " + sp);
1153 this.scan_dir(basepath,sp);
1157 // completed this folder
1160 GLib.FileUtils.set_contents (basepath + subpath + ".strip-done-stamp", "Stripper done");
1166 void report_state(string msg)
1168 // Saved: 2G Original 10G : 20%
1169 GLib.debug("Saved : %s (%.1f%%) | Original %s | %s",
1170 GLib.format_size(this.used_space_before - this.used_space_after),
1171 100f * ((1f * (this.used_space_before - this.used_space_after)) / (this.used_space_before * 1f)),
1172 GLib.format_size(this.used_space_before),