⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 webmailsession.java

📁 java 开发的一个电子邮局,挺实用的
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
	Queue q=new Queue();
	q.queue(folder);
	// Only IMAP supports subscription...
	try {
	    while(!q.isEmpty()) {
		folder=(Folder)q.next();
		
		folder.setSubscribed(subscribed);
		Folder[] list=folder.list();
		for(int i=0;i<list.length;i++) {
		    q.queue(list[i]);
		}
	    }
	} catch(MessagingException ex) {}
    }

   
    /**
       Disconnect from all Mailhosts
    */
    public void disconnectAll() {
	Enumeration e=user.mailHosts();
	while(e.hasMoreElements()) {
	    String name=(String)e.nextElement();
	    disconnect(name);
	}
	e=stores.keys();
	while(e.hasMoreElements()) {
	    String name=(String)e.nextElement();
	    Store st=(Store)stores.get(name);
	    try {
		st.close();
		parent.getStorage().log(Storage.LOG_INFO,"Mail: Connection to "+st.toString()+" closed.");
	    } catch(MessagingException ex) {
		parent.getStorage().log(Storage.LOG_WARN,"Mail: Failed to close connection to "+st.toString()+". Reason: "+ex.getMessage());
	    }		
	    stores.remove(name);
	}
	folders=null;
    }
	
	
    public Folder getRootFolder(String name) throws MessagingException {
	if(connections != null && connections.containsKey(name)) {
	    return (Folder)connections.get(name);
	} else {
	    return connect(name);
	}
    }
	
    protected Store connectStore(String host,String protocol,String login, String password) throws MessagingException {
	/* Check whether the domain of this user allows to connect to the host */	
	WebMailVirtualDomain vdom=parent.getStorage().getVirtualDomain(user.getDomain());
	if(!vdom.isAllowedHost(host)) {
	    throw new MessagingException("You are not allowed to connect to this host");
	}

	/* Check if this host is already connected. Use connection if true, create a new one if false. */
	Store st=(Store)stores.get(host+"-"+protocol);
	if(st==null) {
	    st=mailsession.getStore(protocol);
	    stores.put(host+"-"+protocol,st);
	}

	/* Maybe this is a new store or this store has been disconnected. Reconnect if this is the case. */
	if(!st.isConnected()) {
	    try {
		st.connect(host,login,password);
		parent.getStorage().log(Storage.LOG_INFO,"Mail: Connection to "+st.toString()+".");
	    } catch(AuthenticationFailedException ex) {
		/* If login fails, try the login_password */
		if(!login_password.equals(password) &&
		   parent.getStorage().getConfig("FOLDER TRY LOGIN PASSWORD").toUpperCase().equals("YES")) {
		    st.connect(host,login,login_password);
		    parent.getStorage().log(Storage.LOG_INFO,"Mail: Connection to "+st.toString()+", second attempt with login password succeeded.");
		} else {
		    throw ex;
		}
	    }
	}
	return st;
    }    
	
    /**
       Connect to mailhost "name"
    */
    public Folder connect(String name) throws MessagingException {
	MailHostData m=user.getMailHost(name);
	URLName url=new URLName(m.getHostURL());

	Store st=connectStore(url.getHost(),url.getProtocol(),m.getLogin(),m.getPassword());

	//System.err.println("Default folder: "+st.getDefaultFolder().toString());
		
	Folder f=st.getDefaultFolder();
	connections.put(name,f);
	parent.getStorage().log(Storage.LOG_INFO,"Mail: Folder "+f.toString()+" opened at store "+st.toString()+".");
	return f;
    }
    
	
    /**
       Disconnect from mailhost "name"
    */
    public void disconnect(String name) {
	try {
	    Folder f=(Folder)connections.get(name);
	    if(f != null && f.isOpen()) {
		f.close(true);
		Store st=((Folder)connections.get(name)).getStore();
		//st.close();
		parent.getStorage().log(Storage.LOG_INFO,"Mail: Disconnected from folder "+f.toString()+" at store "+st.toString()+".");
	    } else {
		parent.getStorage().log(Storage.LOG_WARN,"Mail: Folder "+name+" was null???.");
	    }
	} catch(MessagingException ex) {
	    // Should not happen
	    ex.printStackTrace();
	} catch(NullPointerException ex) {
	    // This happens when deleting a folder with an error
	    ex.printStackTrace();
	} finally {
	    connections.remove(name);
	}
    }
	
    /**
     * Terminate this session.
     *
     * This will expunge deleted messages, close all mailbox connections, save the user data and then
     * remove this session from the session list, effectively destroying this session.
     */
    public void logout() {
	if(!is_logged_out) {
	    is_logged_out=true;
	    expungeFolders();
	    disconnectAll();
	    user.logout();
	    saveData();	    
	    parent.getStorage().log(Storage.LOG_INFO,"WebMail: Session "+getSessionCode()+" logout.");
	    // Make sure the session is invalidated
	    if(sess != null) {
		try {
		    Class srvltreq=Class.forName("javax.servlet.http.HttpSession");
		    if(srvltreq.isInstance(sess)) {
			((javax.servlet.http.HttpSession)sess).invalidate();
		    }
		} catch(Throwable t) {
		}
	    }
	    if(parent.getSession(getSessionCode()) != null) {
		parent.removeSession(this);
	    }	
	} else {
	    System.err.println("WARNING: Session was already logged out. Ignoring logout request.");
	}
    }
    
    /**
     * Check whether this session is already logged out.
     * Useful to avoid loops.
     */
    public boolean isLoggedOut() {
	return is_logged_out;
    }

    /**
     * Return the session id that was generated for this session.
     */
    public String getSessionCode() {
	return session_code;
    }
    
    /**
     * Return the last access time of this session
     *
     * @see TimeableConnection
     */
    public long getLastAccess() {
	return last_access;
    }
    
    /**
     * Update the last access time.
     * Sets the last access time to the current time.
     *
     * @see TimeableConnection
     */
    public void setLastAccess() {
	last_access=System.currentTimeMillis();
	//System.err.println("Setting last access to session: "+last_access);
    }
	
    /**
     * Handle a timeout for this session.
     * This calls the logout method, effectively terminating this session.
     *
     * @see TimeableConnection
     * @see logout()
     */
    public void timeoutOccured() {
	parent.getStorage().log(Storage.LOG_WARN,"WebMail: Session "+getSessionCode()+" timeout.");
	logout();
    }
    
    public long getTimeout() {
	long i=600000;
	try {
	    i=Long.parseLong(parent.getStorage().getConfig("session timeout"));
	} catch(NumberFormatException ex) {
	    ex.printStackTrace();
	}
	return i;
    }
	
    public Locale getLocale() {
	return user.getPreferredLocale();
    }
    
    public void saveData() {
	parent.getStorage().saveUserData(user.getUserName(),user.getDomain());
    }
	
	
	
    protected static int[] getSelectedMessages(HTTPRequestHeader head, int max) {
	//	System.err.print(" - select messages...");
		
	Enumeration e=head.getContent().keys();
	int _msgs[]=new int[max];
	int j=0;
		
	while(e.hasMoreElements()) {
	    String s=(String)e.nextElement();
	    if(s.startsWith("CH") && head.getContent(s).equals("on")) {
		try {
		    _msgs[j]=Integer.parseInt(s.substring(3));
		    //    System.err.print(_msgs[j]+" ");
		    j++;
		} catch(NumberFormatException ex) {
		    ex.printStackTrace();
		}
	    }
	}
	//System.err.println();
		
	int msgs[]=new int[j];
	for(int i=0;i<j;i++) {
	    msgs[i]=_msgs[i];
	}
	return msgs;
    }
	

    /** 
     * Expunge all folders that have messages waiting to be deleted
     */
    public void expungeFolders() {
	if(need_expunge_folders != null) {
	    Enumeration enum=need_expunge_folders.elements();
	    while(enum.hasMoreElements()) {
		String hash=(String)enum.nextElement();
		if(user.wantsSetFlags()) {
		    Folder f=getFolder(hash);
		    try {
			if(f.isOpen()) {
			    f.close(false);
			}
			f.open(Folder.READ_WRITE);
			// POP3 doesn't support expunge!
			try {
			    f.expunge();
			} catch(MessagingException ex) {}
			f.close(true);
		    } catch(MessagingException ex) {
			// XXXX
			ex.printStackTrace();
		    }
		}
	    }
	}
    }
	
    /**
       Change the Flags of the messages the user selected.
	 
    */
    public void setFlags(String folderhash, HTTPRequestHeader head) throws MessagingException {
		
	if(head.isContentSet("copymovemsgs") && head.getContent("COPYMOVE").equals("COPY")) {
	    copyMoveMessage(folderhash,head.getContent("TO"),head,false);
	} else if(head.isContentSet("copymovemsgs") && head.getContent("COPYMOVE").equals("MOVE")) {
	    copyMoveMessage(folderhash,head.getContent("TO"),head,true);
	} else if(head.isContentSet("flagmsgs")) {
			
	    System.err.println("setting message flags");
	    Folder folder=getFolder(folderhash);
			
			
	    //System.err.println("Processing Request Header...");
			
	    /* Get selected messages */
	    int msgs[]=getSelectedMessages(head,folder.getMessageCount());
			
	    //System.err.println(" - get flags...");
			
	    /* Get selected flags */
	    Flags fl=new Flags(Flags.Flag.USER);
	    if(head.getContent("MESSAGE FLAG").equals("DELETED")) {
		fl=new Flags(Flags.Flag.DELETED);
		if(need_expunge_folders == null) {
		    need_expunge_folders=new Vector();
		}
		need_expunge_folders.addElement(folderhash);
	    } else if(head.getContent("MESSAGE FLAG").equals("SEEN")) {
		fl=new Flags(Flags.Flag.SEEN);
	    } else if(head.getContent("MESSAGE FLAG").equals("RECENT")) {
		fl=new Flags(Flags.Flag.RECENT);
	    } else if(head.getContent("MESSAGE FLAG").equals("ANSWERED")) {
		fl=new Flags(Flags.Flag.ANSWERED);
	    } else if(head.getContent("MESSAGE FLAG").equals("DRAFT")) {
		fl=new Flags(Flags.Flag.DRAFT);
	    }
			
	    boolean value=true;
	    if(head.getContent("MARK").equals("UNMARK")) {
		value=false;
	    }
			
	    //System.err.println("Done!");
	    //System.err.println("Setting flags...");
			
	    if(user.wantsSetFlags()) {
		if(folder.isOpen() && folder.getMode()==Folder.READ_ONLY) {
		    folder.close(false);
		    folder.open(Folder.READ_WRITE);
		} else if(!folder.isOpen()) {
		    folder.open(Folder.READ_WRITE);
		}
		folder.setFlags(msgs,fl,value);
		if(user.getBoolVar("autoexpunge")) {
		    folder.close(true);
		    if(need_expunge_folders != null) {
			need_expunge_folders.removeElement(folderhash);
		    }
		} else {
		    folder.close(false);
		}
	    }

	    refreshFolderInformation(folderhash);
	    
	}
    }
	
    /**
     * Copy or move the selected messages from folder fromfolder to folder tofolder.
     */
    public void copyMoveMessage(String fromfolder, String tofolder, HTTPRequestHeader head, boolean move) throws MessagingException {
	Folder from=getFolder(fromfolder);
	Folder to=getFolder(tofolder);
	if(user.wantsSetFlags()) {
	    if(from.isOpen() && from.getMode() == Folder.READ_ONLY) {
		from.close(false);
		from.open(Folder.READ_WRITE);
	    } else if(!from.isOpen()) {
		from.open(Folder.READ_WRITE);
	    }
	    if(to.isOpen() && to.getMode() == Folder.READ_ONLY) {
		to.close(false);
		to.open(Folder.READ_WRITE);
	    } else if(!to.isOpen()) {
		to.open(Folder.READ_WRITE);
	    }
	} else {
	    if(!from.isOpen()) {
		from.open(Folder.READ_ONLY);
	    }
	    if(to.isOpen() && to.getMode() == Folder.READ_ONLY) {
		to.close(false);
		to.open(Folder.READ_

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -