/*
 * Write by cocobear
 * cocobear.cn@gmail.com
 * http://cocobear.info
 *
 */

//package Jwind;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.*;
import org.apache.commons.httpclient.methods.*;
import java.util.*;
import org.apache.commons.httpclient.params.*;
import org.apache.commons.httpclient.methods.multipart.*;

public class Jwind
{
	public static void main(String[] args) {
		BackFrame frame = new BackFrame();
	}




}

class BackFrame extends JFrame
{
	public TopJPanel panela;
	public DownJPanel panelb;
	public AutoRegister UserPass;
	public BackFrame() {
		setLocation(180,180);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setResizable(false);
		setTitle("Jwind -- by cocobear.info);
		setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
		setLayout(new GridLayout(2,1,1,1));
		panela = new TopJPanel();
		panelb = new DownJPanel();

		add(panela);
		add(panelb);
		setVisible(true);	/*在添加完所有组件后再设置可见*/



	}
	
	public static final int DEFAULT_WIDTH = 600;
	public static final int DEFAULT_HEIGHT = 400;

	class ButtonAction implements ActionListener 
	{

		public ButtonAction(int i) {
			;
		}
		public void actionPerformed(ActionEvent event) {
			System.out.println("start click!");
			String url = panela.panela.URL.getText();
			String user = panela.panela.User.getText();
			String pass = panela.panela.Pass.getText();
			String fid = panela.panela.FID.getText();
			String tid = panela.panela.TID.getText();
			String encode = panela.panela.Encode.getText();
			String title = panelb.Title.getText();
			String content = panelb.Content.getText();

			int PostType = 3;
			int AutoReg = 0;
			int AllFid = 0;

			if (panela.panelb.AutoReg.isSelected()) {
				AutoReg = 1;
				try {
					UserPass = new AutoRegister(url); 
					user = UserPass.getUser();
					pass = UserPass.getPass();
					System.out.println("注册成功用户:"+user);
					System.out.println("密码为:"+pass);

				} catch (IOException e) {
					System.out.println("Error"+e.toString());
				}
			}


			if (panela.panelb.AllF.isSelected()) {
				AllFid = 1;
			}

			
			if (panela.panelb.AutoReply.isSelected()) {
				PostType = 1;
			}
			else if (panela.panelb.ReplyOld.isSelected()) {
				PostType = 2;
			}
			else {
				PostType = 3;
					if (url.equals("") || user.equals("") || pass.equals("") || fid.equals("") || title.equals("") || content.equals("") || encode.equals("") ) {
					System.out.println("少参数");
					}
				try {
				NewPost post = new NewPost(url,user,pass,fid,title,content,encode);
				} catch (IOException e) {

					System.out.println("Error"+e.toString());
				}
			}
			


			System.out.println("原始URL:"+url);
			System.out.println("发贴类型: "+PostType);
			System.out.println("自动注册"+AutoReg);
			System.out.println("所有版块"+AllFid);


		}
	}	


class TopJPanel extends JPanel
{
	public TLeftJPanel panela;
	public TRightJPanel panelb;
	public TopJPanel() {
		
		setLayout(new GridBagLayout());
		GridBagConstraints gc = new GridBagConstraints();
		gc.fill = GridBagConstraints.BOTH;
		panela = new TLeftJPanel();
		panelb = new TRightJPanel();
		JPanel panelc = new JPanel();
		gc.weightx = 1;		/*上部左边面板占2/3空间*/
		gc.weighty = 1;		/*左右面板占满纵向空间*,改为其它数值也可以,但必须设置*/
	//	gc.gridwidth = 3;
		gc.gridx = 0;
		add(panela,gc);
		
		gc.gridx = 1;
		add(panelc,gc);

		gc.gridx = 2;
		//gc.gridwidth = 2;
		add(panelb,gc);
		setVisible(true);
	
	}
}

class TLeftJPanel extends JPanel
{
	public	JTextField User;
	public	JTextField Pass;
	public	JTextField URL;
	public	JTextField FID;
	public	JTextField TID;
	public	JTextField Encode;

	public TLeftJPanel() {

		JLabel LabUser;
		JLabel LabURL;
		JLabel LabPass;
		JLabel LabFID;		/*版块ID*/
		JLabel LabTID;		/*贴子ID*/
		JLabel LabEncode;


		
		//setBackground(Color.BLACK);
		setLayout(new GridBagLayout());
		GridBagConstraints gc = new GridBagConstraints();
		gc.fill = GridBagConstraints.HORIZONTAL;

		LabURL = new JLabel("论坛地址:");
		LabUser = new JLabel("用户名:");
		LabPass = new JLabel("密码:");
		LabFID = new JLabel("版块ID:");
		LabTID = new JLabel("贴子ID:");
		LabEncode = new JLabel("网页编码:");

		
		LabURL.setHorizontalAlignment(JLabel.CENTER);	/*设置居中*/
		LabUser.setHorizontalAlignment(JLabel.CENTER);
		LabPass.setHorizontalAlignment(JLabel.CENTER);
		LabFID.setHorizontalAlignment(JLabel.CENTER);
		LabTID.setHorizontalAlignment(JLabel.CENTER);
		LabEncode.setHorizontalAlignment(JLabel.CENTER);

		URL = new JTextField("http://1g50.cn/upload");
		User = new JTextField("test");
		Pass = new JTextField("ffffff");
		FID = new JTextField("2");
		TID = new JTextField("0");
		Encode = new JTextField("GBK");


		URL.setColumns(8);
		gc.gridx = 0;
		gc.weightx = 1;		/*标签宽度为1*/
		gc.weighty = 1;		/*高度全部为1*/
		add(LabURL,gc);
		gc.gridx = 2;
		gc.weightx = 2;		/*输入框宽度为2*/
		add(URL,gc);
		
		gc.gridx = 0;
		gc.weightx = 1;
		add(LabUser,gc);
		gc.gridx = 2;
		gc.weightx = 2;
		add(User,gc);
		
		gc.gridx = 0;
		gc.weightx = 1;
		add(LabPass,gc);
		gc.gridx = 2;
		gc.weightx = 2;
		add(Pass,gc);
		
		gc.gridx = 0;
		gc.weightx = 1;
		add(LabFID,gc);
		gc.gridx = 2;
		gc.weightx = 2;
		add(FID,gc);
		
		gc.gridx = 0;
		gc.weightx = 1;
		add(LabTID,gc); 

		gc.gridx = 2;
	       	gc.weightx = 2;
		add(TID,gc);

		gc.gridx = 0;
		gc.weightx = 1;
		add(LabEncode,gc); 

		gc.gridx = 2;
	       	gc.weightx = 2;
		add(Encode,gc);
		setVisible(true);
	}
}

class TRightJPanel extends JPanel
{
	public	JCheckBox AutoReg;
	public	JCheckBox AllF;
	public	JRadioButton AutoReply;
	public	JRadioButton ReplyOld;
	public	JRadioButton NewThread;
	public	ButtonGroup group;

	public TRightJPanel() {


		AutoReg = new JCheckBox("自动注册");
		AllF = new JCheckBox("所有版块发贴");


		
		group = new ButtonGroup();

		AutoReply = new JRadioButton("发新贴后自动顶");
		ReplyOld = new JRadioButton("顶原来发的贴");
		NewThread = new JRadioButton("一直发新贴",true);

		group.add(AutoReply);
		group.add(ReplyOld);
		group.add(NewThread);

		
		//setBackground(Color.GREEN);
		setLayout(new GridBagLayout());
		GridBagConstraints gc = new GridBagConstraints();
		gc.fill = GridBagConstraints.BOTH;
		gc.weightx = 1;
		gc.weighty = 1;

		gc.gridx = 0;
		gc.gridwidth = 1;
		add(AutoReg,gc);
		gc.gridx = 0;
		gc.gridwidth = 1;
		add(AllF,gc);
		gc.gridx = 0;

		add(AutoReply,gc);
		//gc.gridx = 0;
		add(ReplyOld,gc);
		//gc.gridx = 0;
		add(NewThread,gc);

		setVisible(true);
	}
}

/*
 * 下部面板
 *
 */

class DownJPanel extends JPanel
{

	public JTextField Title;
	public JTextArea Content;
	public DownJPanel() {

		JLabel LabTitle;
		JLabel LabContent;
		JLabel LabStatus;


		JButton StartButton;

		LabTitle = new JLabel("主题:");
		LabContent = new JLabel("内容:");
		LabStatus = new JLabel("欢迎访问http://cocobear.info);

		LabTitle.setHorizontalAlignment(JLabel.CENTER);
		LabContent.setHorizontalAlignment(JLabel.CENTER);
	//	LabStatus.setHorizontalAlignment(JLabel.CENTER);

		StartButton = new JButton("开始");

		Title = new JTextField("版主快删了,这是灌水贴");
		Content = new JTextArea("灌水来了!");
		Content.setRows(4);
		Content.setColumns(10);

		JScrollPane sp = new JScrollPane(Content);	/*为TextArea加入滚动条*/
		//setBackground(Color.BLUE);
		setLayout(new GridBagLayout());
		GridBagConstraints gc = new GridBagConstraints();

		gc.fill = GridBagConstraints.HORIZONTAL;
		gc.weightx = 1;
		gc.weighty = 1;
		add(LabTitle,gc);

		gc.weightx = 6;
		gc.gridx = 2;
		add(Title,gc);

		gc.gridx = 0;
		gc.weightx = 1;
		gc.weighty = 6;
		add(LabContent,gc);


		Content.setLineWrap(true);
		gc.fill = GridBagConstraints.BOTH;	/*扩展TextArea*/
		gc.gridx = 2;
		gc.weightx = 6;
		add(sp,gc);
	
		gc.fill = GridBagConstraints.NONE;	/*使StartButton不扩展*/
		gc.gridx = 0;
		gc.weightx = 1;
		gc.weighty = 1;
		add(StartButton,gc);

		gc.gridx = 2;
		gc.weightx = 6;
		add(LabStatus,gc);
		setVisible(true); 

		/*End of GUI*/
		int start = 1;	
		ButtonAction StartAction = new ButtonAction(start);
		StartButton.addActionListener(StartAction);
	
	}
	



}

}


class AutoRegister
{
	public String name = "";
	public String pass = "";

	public AutoRegister(String url) throws IOException {
		String host = "";
		String port = "80";
		try {
			URL regurl = new URL(url);
			host = regurl.getHost();
			port = "" + ((regurl.getPort() == -1)?80:regurl.getPort());
			System.out.println("Host is :"+host);
			System.out.println("Port is :"+port);
			}catch (MalformedURLException ex) {
		}
		
		Random rd = new Random();
		int rdget;
		do {
			if ((rdget = rd.nextInt(122)) > 97) {
				char c = (char)rdget;
				String tmp = Character.toString(c);
				name+=tmp;
			}
		} while (name.length() < 6 );
		System.out.println(name);
		do {
			if ((rdget = rd.nextInt(122)) > 97) {
				char c = (char)rdget;
				String tmp = Character.toString(c);
				pass+=tmp;
			}
		} while (pass.length() < 6 );

		System.out.println(pass);

		HttpClient regclient = new HttpClient();
		regclient.getHostConfiguration().setHost(host,80,"http");
		String regurl = url.concat("/register.php");
		System.out.println(regurl);
		HttpMethod regmethod = regPostMethod(regurl,name,pass);
		regclient.executeMethod(regmethod);

	
		System.out.println(regmethod.getStatusLine());

		String regresponse = new String(regmethod.getResponseBodyAsString().getBytes("8859_1"));


		System.out.println(regresponse);

		regmethod.releaseConnection();
		
	}


	private static HttpMethod regPostMethod(String regurl,String name,String pass) {
		PostMethod reg = new PostMethod(regurl);



		NameValuePair regname = new NameValuePair("regname",name);
		NameValuePair regpwd = new NameValuePair("regpwd",pass);
		NameValuePair regemail = new NameValuePair("regemail","cocobear.cn@gmail.com");
	//	NameValuePair regpwdrepeat = new NameValuePair("regpwdrepeat","ffffff");
		NameValuePair forward = new NameValuePair("forward","");
		NameValuePair step = new NameValuePair("step","2");

		reg.setRequestBody(new NameValuePair[] {regname,regpwd,regemail,forward,step});
       		return reg;



	}

	String getUser() {
		return name;
	}
	String getPass() {
		return pass;
	}


}


class NewPost  
{

	public NewPost(String url,String user,String pass,String fid,String title,String content,String encode) throws IOException {
		String host = "";
		String port = "80";
		try {
			URL regurl = new URL(url);
			host = regurl.getHost();
			port = "" + ((regurl.getPort() == -1)?80:regurl.getPort());
			System.out.println("Host is :"+host);
			System.out.println("Port is :"+port);
			}catch (MalformedURLException ex) {
		}


        HttpClient client = new HttpClient();
        client.getHostConfiguration().setHost(host, 80, "http");/*需要更改端口*/
        //client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

	String posturl = url.concat("/post.php");	
	String loginurl = url.concat("/login.php");
	String geturl1 = posturl.concat("?fid=");
	String geturl = geturl1.concat(fid);
        
	System.out.println("Post url is "+posturl);
	System.out.println("User is "+user);
	System.out.println("Password is "+pass);
	System.out.println("geturl is "+geturl);

	
	/*登录论坛*/
        PostMethod authpost = new PostMethod(loginurl);
        NameValuePair userid   = new NameValuePair("pwuser", user);
        NameValuePair password = new NameValuePair("pwpwd", pass);
	NameValuePair hideid   = new NameValuePair("hideid","0");
	NameValuePair cktime   = new NameValuePair("cktime","31536000");
	NameValuePair forward  = new NameValuePair("forward","/");
	NameValuePair jumpurl  = new NameValuePair("jumpurl","/");
	NameValuePair step     = new NameValuePair("step","2");

        authpost.setRequestBody( 
          new NameValuePair[] {userid, password,hideid,cktime,forward,jumpurl,step});
	Map<String,String> headers = new HashMap<String,String>();

       	client.executeMethod(authpost);

        authpost.releaseConnection();
	/*登录完成*/


	/*获取cookie;自动cookie处理有问题,cookie信息不全*/

	for(Header header : authpost.getResponseHeaders("Set-Cookie")) {
		String[] sArray = header.getValue().split(";")[0].split("=");
		headers.put(sArray[0],sArray[1]);
	}

	StringBuffer buffer = new StringBuffer();
	for (Iterator iterator = headers.keySet().iterator();iterator.hasNext();) {
	String key = (String) iterator.next();
	buffer.append(buffer.length() > 0 ? ";":"").append(key).append("=").append(headers.get(key));
	}

	/*获取verify值*/

	GetMethod getverify = new GetMethod(geturl);
	getverify.addRequestHeader("Cookie",buffer.toString());
	client.executeMethod(getverify);

	String result = null;
	StringBuffer resultBuffer = new StringBuffer();
	BufferedReader in = new BufferedReader(
	new InputStreamReader(

	getverify.getResponseBodyAsStream(),
	getverify.getResponseCharSet()));

	String inputLine = null;
	String strverify = null;
	while ((inputLine = in.readLine()) != null) {
	
		String strofverify = "verify";
		if (inputLine.indexOf(strofverify) != -1) {
			strverify = inputLine.substring(42,50);/*verify值在一行的指定位置*/
		}

	}

	System.out.println("verify is :" + strverify);
	in.close();
	/*String encode = "gbk";
	result = ConverterStringCode(resultBuffer.toString(), getverify.getResponseCharSet(), encode); 
	System.out.println(result);
	*/
	

        getverify.releaseConnection();
	
	/*获取verify值完成*/


	/*开始提交贴子*/
	PostMethod autopost = new PostMethod(posturl);

	autopost.addRequestHeader("Cookie",buffer.toString());
        autopost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());

	//autopost.removeRequestHeader("Content-Type");
	//autopost.addRequestHeader(new Header("Content-Type","text/html; charset=GBK"));
	
	System.out.println(strverify);
	StringPart verify = new StringPart("verify",strverify);
	StringPart atc_title = new StringPart("atc_title",title,encode);
	StringPart atc_autourl = new StringPart("atc_autourl","1");
	StringPart atc_usesign = new StringPart("atc_usesign","1");
	StringPart atc_convert = new StringPart("atc_convert","1");
	StringPart atc_content = new StringPart("atc_content",content,encode);
	StringPart atc_rvrc = new StringPart("act_rvrc","0");
	//StringPart atc_hide = new StringPart("atc_hide","1");
	StringPart atc_money = new StringPart("atc_money","0");
	StringPart atc_downrvrc1 = new StringPart("atc_downrvrc1","0");
	StringPart atc_desc1 = new StringPart("atc_desc1","");
	
	StringPart atc_step = new StringPart("step","2");
	StringPart pid = new StringPart("pid","");
	StringPart action =new StringPart("action","new");
	StringPart atc_fid  = new StringPart("fid","2");
	StringPart tid = new StringPart("tid","0");
	StringPart special = new StringPart("special","0");

	Part[] parts = {verify,atc_title,atc_autourl,atc_usesign,atc_convert,atc_content,atc_rvrc,atc_money,atc_downrvrc1,atc_desc1,atc_step,pid,action,atc_fid,tid,special,};
	autopost.setRequestEntity(new MultipartRequestEntity(parts,autopost.getParams()));





 	int status = client.executeMethod(autopost);
	System.out.println("autopost return "+status);


	String response = new String(autopost.getResponseBodyAsString().getBytes("8859_1"));

	System.out.println(response);
    }

private static String ConverterStringCode(String source, String srcEncode, String destEncode) {

	if (source != null) {

		try {

			return new String(source.getBytes(srcEncode), destEncode);

		} catch (UnsupportedEncodingException e) {

			e.printStackTrace();

			return "";

		}


	} else {

		return "";

	}

}
    
}
