using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Web;
using System.Text.RegularExpressions;
namespace Fetion
{
public class WapFetion
{
private static string server = "http://f.10086.cn";
private string mobile;
private string password;
private CookieContainer cookies = new CookieContainer();
/// <summary>
/// 构造函数
/// </summary>
/// <param name="mobile">手机号码</param>
/// <param name="password">密码</param>
public WapFetion(string mobile, string password)
{
this.mobile = mobile;
this.password = password.ToUrlEncode();
}
protected string PostWithCookie(string uri, string data)
{
using (HttpWebClient hwc = new HttpWebClient(cookies))
{
hwc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
return Encoding.UTF8.GetString(hwc.UploadData(uri, Encoding.UTF8.GetBytes(data)));
}
}
protected string GetUid(string mobile)
{
string uri = server + "/im/index/searchOtherInfoList.action";
string data = "searchText=" + mobile;
string result = PostWithCookie(uri, data);
Match mc = Regex.Match(result, @"toinputMsg\.action\?touserid=(\d+)");
if (mc.Success)
{
return mc.Result("$1");
}
return null;
}
protected bool ToUid(string uid, string message)
{
string uri = server + "/im/chat/sendMsg.action?touserid=" + uid;
string data = "msg=" + message.ToUrlEncode();
string result = PostWithCookie(uri, data);
return result != null && result.Contains("发送消息成功!");
}
protected bool ToMyself(string message)
{
string uri = server + "/im/user/sendMsgToMyselfs.action";
string data = "msg=" + message.ToUrlEncode();
string result = PostWithCookie(uri, data);
return result != null && result.Contains("短信发送成功!");
}
/// <summary>
/// 登陆
/// </summary>
/// <returns></returns>
public string Login()
{
string uri = server + "/im/login/inputpasssubmit1.action";
return PostWithCookie(uri, string.Format("m={0}&pass={1}&loginstatus=1", mobile, password));
}
/// <summary>
/// 注销
/// </summary>
/// <returns></returns>
public string Logout()
{
string uri = server + "/im/index/logoutsubmit.action";
return PostWithCookie(uri, "");
}
/// <summary>
/// 通过手机号,给自己会好友发送消息
/// </summary>
/// <param name="mobile">手机号</param>
/// <param name="message">消息</param>
/// <returns></returns>
public bool Send(string mobile, string message)
{
if (string.IsNullOrWhiteSpace(message))
{
return false;
}
if (mobile == this.mobile)
{
return ToMyself(message);
}
else
{
string uid = GetUid(mobile);
if (uid == null)
{
return false;
}
return ToUid(uid, message);
}
}
}
}