/*************************************************************/
/*  GetAttachments.java   
/*  利用mms.txt裡的帳號和密碼到pop3 server 上取得信件
/*  根據信件的帳號建立資料夾...並由InsertData.java寫進資料庫  
/*************************************************************/
import com.jscape.inet.pop.*;
import com.jscape.inet.mime.*;
import com.jscape.inet.email.*;
import com.jscape.inet.util.*;
import java.util.Enumeration;
import java.util.*;
import java.io.*;

public class GetAttachments extends TimerTask implements Runnable{
    private static String rootaddr="C:/AppServ/www/TheZoo/Messages/";//根目錄的位址
    private static File attachmentsDir;//附件所放的資料夾
	private static String msgadd,attdir,from="",date,filename,dates;
	private int addrindex=0;//紀錄address的char index
    static FileReader fd;
    static BufferedReader reader ;
	private EmailMessage msg;
	private InsertData in_mysql; 
	private int check=0;
	static String path,photo,orimsg,ip,sendaddr;
	//private String tmp_ip;
	//private char[] char_ip;

    // 從Pop mailbox取得信件
public void getMessages(String hostname, String username, String password)throws PopException, MimeException, IOException 
{
        // 連線
        Pop pop = new Pop(hostname,username,password);
        pop.connect();
		
        // 取得信件
        Enumeration messages = pop.getMessages();
        if(!messages.hasMoreElements()) 
		{
           System.out.println("No messages found");
        }     

        // 將信件寫入
        int msgnum = 0;
        while(messages.hasMoreElements()) 
		 {
            ++msgnum;
            msg = (EmailMessage)messages.nextElement();
			addrindex = 0;
	
			//印出寄件人的address
			msgadd = msg.getFrom();
            System.out.println("From:" + msgadd);
			sendaddr=String.valueOf(msgadd);//將寄件人的住址存在sendaddr以便後面寫入資料庫
            
			//將address分解，建立資料夾名稱
		        attdir=attdir.valueOf(msgadd.charAt(addrindex)); 
				addrindex++;
				while(msgadd.charAt(addrindex)!='@')
	             {
					 if(msgadd.charAt(addrindex)=='<')
                       {
                         attdir="";
						 addrindex++;		
					    }
						attdir+=attdir.valueOf(msgadd.charAt(addrindex));    
	                    addrindex++;
				 }			  
				while(addrindex != msgadd.length()-1)
			     {
	                addrindex++;	
					if(msgadd.charAt(addrindex)=='>')
                     {
						 addrindex++;	
						 break;
					  }
			        from+=attdir.valueOf(msgadd.charAt(addrindex));    
			     }
				 System.out.println(attdir);//印出資料夾名稱
				 System.out.println(from);
				
				 //判斷from,選擇是否將內容解碼
				 // PHS的mail格式太過簡陋, inetfactory拆解不出來
				 if(from.compareTo("phs.com.tw") == 0)
			     {
					 MimeMessage mimemsg = msg.getPart(1);
					 Enumeration headers = mimemsg.getHeaders();
					 while(headers.hasMoreElements())
					 {
					   MimeHeader header = (MimeHeader)headers.nextElement();
					   if(header.getName().compareTo("Content-Type") == 0)
					   {
							String h = header.toString();
							mimemsg.addHeader("Content-Disposition", "attachment; filename=\"" + h.substring(h.indexOf("name=\"") + 6, h.length() - 1) + "\"");
					   }	
					 }
					 msg.removePart(1);
					 msg.addPart(mimemsg);
					 msg = new EmailMessage(msg.getMessageBytes());
				 }
                 if(from.compareTo("tccdata.com.tw") == 0)				  
					 ip = MimeBase64.decode(msg.getBody());				  
				 else
					 ip =  msg.getBody();

                 from="";

		   	     attachmentsDir = new File(rootaddr+attdir);
				 this.path=rootaddr+attdir+"/";
				 //System.out.println("Debug_PATH : " + path);
				  if(!attachmentsDir.exists())
				   {
				     attachmentsDir.mkdir();		           
                     getatt();
				     getmsg();
					 in_mysql = new InsertData();
				     in_mysql.run(check, path, photo ,orimsg, ip.trim(), sendaddr);//ip.trim()內容部分只取得ip去掉空白
				   }
				   else
				   {	 
					 getatt();
				     getmsg();
					 in_mysql = new InsertData();
				     in_mysql.run(check, path, photo ,orimsg, ip.trim(), sendaddr);
                   } 				                    
              //pop.deleteMessage(msgnum);//把郵件從pop3 server上刪除
				attdir="";
				msgadd="";              
         }//end of while
        pop.disconnect();
}//end of getMessages()

public void getatt() throws PopException, MimeException, IOException
 {
	    // write attachments to disk
            int attachnum = 0;
			String att_type="",command="",attfilename="";
            Enumeration attachments = msg.getAttachments();
			File attFile;
            while(attachments.hasMoreElements()) {
                ++attachnum;
                Attachment attach = (Attachment)attachments.nextElement();
				dates = getdate();
                filename = dates + "_" +attach.getFilename();
                attfilename=filename.substring(0,filename.length()-4);

				att_type = filename.substring(filename.length()-4,filename.length());//取得圖檔類型.gif或.jpg或.bmp
				//System.out.println("附檔的類型是:"+att_type);

                attFile = new File(attachmentsDir+"/"+filename);
				FileOutputStream attOut;
                  if(!attFile.exists())
					{
                     attOut = new FileOutputStream(attFile);
					 try {
                        attOut.write(attach.getFileData());
                        attOut.close(); 
						if(att_type!=".jpg")
						{
						  command = (String)"C:/Program Files/ImageMagick-5.5.7-Q8/convert \""+attachmentsDir+"\\"+filename+"\" \""+attachmentsDir+"\\"+attfilename+".jpg\"";
						  System.out.println(command);
                          Runtime.getRuntime().exec(command);
                          //attFile.delete();
						}
						photo=attfilename+".jpg";//將圖片檔案名稱存在photo以便後面寫入資料庫				 
                        //System.out.println("Retrieved attachment: " + attFile.getAbsoluteFile());
						attfilename="";
                     }
                     catch(Exception e) {
                        throw new PopException("unable to decode file attachment");
                     }
					break;
				  }
				  else
					 continue;
                //}//end of for
            }//end of while
}//end of getatt()

public void getmsg(){
//將e-mail原文寫入檔案
  for(int i=1;i>=1;i++)
   {
   String msgfilename=filename.substring(0,filename.length()-4);

   try{
	  File msgFile = new File(attachmentsDir,msgfilename+ ".txt");
         if(!msgFile.exists())
		  {
           FileOutputStream fout = new FileOutputStream(msgFile);
		    try{
	      	    fout.write(msg.getMessage().getBytes());
                fout.close();
			    orimsg=msgFile.getName();//將msg檔案名稱存在msg以便後面寫入資料庫
                System.out.println("Retrieved message: " + msgFile.getAbsoluteFile());
		    }
		    catch(Exception e) {
                e.printStackTrace();
            }	
				 break;
		  }//end of if
		  else
			   continue;
	 }
	 catch(IOException ioe){
        System.out.println("File doesn't exist");
     }
  }//end of for
}//end of getmsg()

	 
static String getdate()
{
	    Date today= new Date();
        String output="";
        String year,month,date,hrs,min,sec;
			
        year = String.valueOf(today.getYear()+1900);
		month = NumberCheck(today.getMonth()+1);
		date = NumberCheck(today.getDate());
		hrs = NumberCheck(today.getHours());
		min = NumberCheck(today.getMinutes());
		sec = NumberCheck(today.getSeconds());

        output = year+month+date+hrs+min+sec;
		return output;	
}

static String NumberCheck (int n)
{
  String a = ""; 
	  if( n < 10 )
	  {
	      a = "0" + String.valueOf(n);
          return a;
      }
	  else
 	      return String.valueOf(n);
      
}	


public void run() 
{
        String hostname="";
        String username="";
        String password="";
        GetAttachments example = new GetAttachments();
        try{
             fd = new FileReader("mms.txt");
	         reader = new BufferedReader(fd);
			try{
			  while (reader.ready())
				{      
  					System.out.print("\n-------至Pop3 Server收信-------\n");
		            hostname = reader.readLine();
					System.out.print("Enter Pop3 hostname: "+hostname+"\n");            
					username = reader.readLine();
					System.out.print("Enter Pop3 Username: "+username+"\n");
		            password = reader.readLine();
				    System.out.print("Enter Pop3 Password: \n");
					example.getMessages(hostname,username,password); 
					System.out.print("---------信件儲存訊息-----------\n"+"check:"+check+"\npath:"+this.path+"\nphoto:"+this.photo+"\nmsg:"+this.orimsg+"\nip:"+this.ip+"\nsendaddr:"+this.sendaddr+"\n");
					
					path = "";
					photo = "";
					orimsg = "";
					sendaddr = "";
					ip = "";
				}	
			}
		    catch(Exception e) {
					e.printStackTrace();
		    }	
			reader.close();
		}		  
	    catch(IOException ioe)
		{
			System.out.println("File doesn't exist");
		}
		    
}//end of run


public static void main(String args[]) 
 {
		path = "";
		photo = "";
		orimsg = "";
		sendaddr = "";
		ip = "";
		(new GetAttachments()).run();
 }


}

