Thinkai's Blog

Autohotkey|Python|php|aardio|VOIP|IT 爱好者

Centos6安装STUN服务器 8832

作者为 发表

LinuxVOIP

虽然免费的stun服务器也能凑合着用,但是也越来越不适用于中国的网络环境,所以你可以到大的IDC去买云主机并购买额外IP来搭建STUN服务器,主流成本100多RMB一个月。

首先你的有两个公网IP的服务器!然后注意把防火墙关掉。

#下载stun

wget http://ncu.dl.sourceforge.net/project/stun/stun/0.97/stund-0.97.tgz

#检查安装编译环境

yum -y install gcc automake autoconf libtool make

#解压

tar -zxvf stund-0.97.tgz

#进入目录

cd stund

#编译

make

#复制服务端

mkdir /root/bin/
cp server /root/bin/stunserver

#创建服务脚本

vi /etc/init.d/stund

#然后填充服务脚本

#!/bin/bash
# 
#chkconfig: 2345 70 30
#description:STUN Server
RETVAL=0 
start(){ #启动服务的入口函数  
echo  "STUN Server is started..."  
/root/bin/stunserver -v -h 8.8.8.8  -a 4.4.4.4 -v
#主IP 辅助IP
}  
  
stop(){ #关闭服务的入口函数  
echo  "STUN Server is stoped..."  
}  
  
#使用case选择  
case $1 in  
start)  
start  
;;  
stop)  
stop  
;;  
*)  
echo "error choice ! please input start or stop";;  
esac  
exit $RETVA

#按【ESC】输入:wq保存退出

#设置权限

chmod +x /etc/init.d/stund

#添加服务

chkconfig --add stund

#设置防火墙

setup

#找到Firewall设置 把Enable去掉,然后Save保存退出

#为了安全 可以修改root用户名和设置denyhosts

#重启后,你就可以下载NatTypeTester测试你的服务器了。

php smtp&pop3收发邮件代码 2450

作者为 发表

网站建设

<?php 
if ($EMAIL_INC) return; 
$EMAIL_INC= "defined"; 
define( "SmtpPort",25); 

class Pop3 { 
var $subject; // 邮件主题 
var $from_email; // 发件人地址
var $from_name; // 发件人姓名
var $to_email; // 收件人地址
var $to_name; // 收件人姓名
var $body; // 邮件内容
var $filename; // 文件名
var $socket; // 当前的 socket 
var $Line; 
var $Status; 

function pop3_open($server, $port) 
{ 

$this->Socket = fsockopen($server, $port); 
if ($this->Socket <= 0){ 
return false; 
} 
$this->Line = fgets($this->Socket, 1024); 
$this->Status[ "LASTRESULT"] = substr($this->Line, 0, 1); 
$this->Status[ "LASTRESULTTXT"] = substr($this->Line, 0, 1024); 

if ($this->Status[ "LASTRESULT"] <> "+") return false; 
return true; 
} 

function pop3_user($user) 
{ 

if ($this->Socket < 0){ 
return false; 
} 
fputs($this->Socket, "USER $this->user\r\n"); 
$this->Line = fgets($this->Socket, 1024); 
$this->Status[ "LASTRESULT"] = substr($this->Line, 0, 1); 
$this->Status[ "LASTRESULTTXT"] = substr($this->Line, 0, 1024); 

if ($this->Status[ "LASTRESULT"] <> "+") return false; 

return true; 
} 

function pop3_pass( $pass) 
{ 

fputs($this->Socket, "PASS $pass\r\n"); 
$this->Line = fgets($this->Socket, 1024); 
$this->Status[ "LASTRESULT"] = substr($this->Line, 0, 1); 
$this->Status[ "LASTRESULTTXT"] = substr($this->Line, 0, 1024); 

if ($this->Status[ "LASTRESULT"] <> "+") return 0; 

return 1; 
} 

function pop3_stat() 
{ 

fputs($this->Socket, "STAT\r\n"); 
$this->Line = fgets($this->Socket, 1024); 
$this->Status[ "LASTRESULT"] = substr($this->Line, 0, 1); 
$this->Status[ "LASTRESULTTXT"] = substr($this->Line, 0, 1024); 

if ($this->Status[ "LASTRESULT"] <> "+") return 0; 

if (!eregi( "+OK (.*) (.*)", $this->Line, $regs)) 
return 0; 

return $regs[1]; 
} 

function pop3_list() 
{ 
fputs($this->Socket, "LIST\r\n"); 
$this->Line = fgets($this->Socket, 1024); 
$this->Status[ "LASTRESULT"] = substr($this->Line, 0, 1); 
$this->Status[ "LASTRESULTTXT"] = substr($this->Line, 0, 1024); 

if ($this->Status[ "LASTRESULT"] <> "+") return 0; 

$i = 0; 
while (substr($this->Line = fgets($this->Socket, 1024), 0, 1) <> ".") 
{ 
$articles[$i] = $this->Line; 
$i++; 
} 
$articles[ "count"] = $i; 

return $articles; 
} 

function pop3_retr($nr) 
{ 

fputs($this->Socket, "RETR $nr\r\n"); 
$this->Line = fgets($this->Socket, 1024); 
$this->Status[ "LASTRESULT"] = substr($this->Line, 0, 1); 
$this->Status[ "LASTRESULTTXT"] = substr($this->Line, 0, 1024); 

if ($this->Status[ "LASTRESULT"] <> "+") return 0; 

while (substr($this->Line = fgets($this->Socket, 1024), 0, 1) <> ".") 
{ 
$data[$i] = $this->Line; 
$i++; 
} 
$data[ "count"] = $i; 

return $data; 
} 

function pop3_dele( $nr) 
{ 

fputs($this->Socket, "DELE $nr\r\n"); 
$this->Line = fgets($this->Socket, 1024); 
$this->Status[ "LASTRESULT"] = substr($this->Line, 0, 1); 
$this->Status[ "LASTRESULTTXT"] = substr($this->Line, 0, 1024); 

if ($this->Status[ "LASTRESULT"] <> "+") return 0; 
return 1; 
} 

function pop3_quit() 
{ 

fputs($this->Socket, "QUIT\r\n"); 
$this->Line = fgets($this->Socket, 1024); 
$this->Status[ "LASTRESULT"] = substr($this->Line, 0, 1); 
$this->Status[ "LASTRESULTTXT"] = substr($this->Line, 0, 1024); 

if ($this->Status[ "LASTRESULT"] <> "+") return 0; 

return 1; 
} 
} 

class Smtp { 

var $Subject; // string the email's subject 
var $FromName; // string sender's name (opt) 
var $ToName; // string recipient's name (opt) 
var $Body; // string body copy 
var $Attachment; // attachment (optional) 
var $AttachmentType; 
var $Socket; 
var $Line; 
var $Status; 

function Smtp($Server = "localhost",$Port = SmtpPort) 
{ 
return $this->Open($Server, $Port); 
} 

function SmtpMail($FromEmail, $FromName, $ToEmail, $ToName, $Subject, $Body, $Attachment=null, $AttachmentType= "TEXT") 
{ 
$this->Subject = $Subject; 
$this->ToName = $ToName; 

$this->FromName = $FromName; 
$this->Body = $Body; 

$this->Attachment = $Attachment; 
$this->AttachmentType = $AttachmentType; 

if ($this->Helo() == false){ 
return false; 
} 
if ($this->MailFrom($FromEmail) == false){ 
return false; 
} 
if ($this->RcptTo($ToEmail) == false){ 
return false; 
} 
if ($this->Body() == false){ 
return false; 
} 
if ($this->Quit() == false){ 
return false; 
} 
} 

function Open($Server, $Port) 
{ 

$this->Socket = fsockopen($Server, $Port); 
if ($this->Socket < 0) return false; 

$this->Line = fgets($this->Socket, 1024); 

$this->Status[ "LASTRESULT"] = substr($this->Line, 0, 1); 
$this->Status[ "LASTRESULTTXT"] = substr($this->Line, 0, 1024); 

if ($this->Status[ "LASTRESULT"] <> "2") return false; 

return true; 
} 

function Helo() 
{ 
if (fputs($this->Socket, "helo\r\n") < 0 ){ 
return false; 
} 
$this->Line = fgets($this->Socket, 1024); 

$this->Status[ "LASTRESULT"] = substr($this->Line, 0, 1); 
$this->Status[ "LASTRESULTTXT"] = substr($this->Line, 0, 1024); 

if ($this->Status[ "LASTRESULT"] <> "2") return false; 

return true; 
} 

function Ehlo() 
{ 

/* Well, let's use "helo" for now.. Until we need the 
extra func's [Unk] 
*/ 
if(fputs($this->Socket, "helo localhost\r\n")<0){ 
return false; 
} 
$this->Line = fgets($this->Socket, 1024); 

$this->Status[ "LASTRESULT"] = substr($this->Line, 0, 1); 
$this->Status[ "LASTRESULTTXT"] = substr($this->Line, 0, 1024); 

if ($this->Status[ "LASTRESULT"] <> "2") return false; 

return true; 
} 

function MailFrom($FromEmail) 
{ 

if (fputs($this->Socket, "MAIL FROM: <$FromEmail>\r\n")<0){ 
return false; 
} 

$this->Line = fgets($this->Socket, 1024); 

$this->Status[ "LASTRESULT"] = substr($this->Line, 0, 1); 
$this->Status[ "LASTRESULTTXT"] = substr($this->Line, 0, 1024); 

if ($this->Status[ "LASTRESULT"] <> "2") return false; 

return true; 
} 

function RcptTo($ToEmail) 
{ 

if(fputs($this->Socket, "RCPT TO: <$ToEmail>\r\n")<0){ 
return false; 
} 
$this->Line = fgets($this->Socket, 1024); 

$this->Status[ "LASTRESULT"] = substr($this->Line, 0, 1); 
$this->Status[ "LASTRESULTTXT"] = substr($this->Line, 0, 1024); 

if ($this->Status[ "LASTRESULT"] <> "2") return false; 
return true; 
} 

function Body() 
{ 
$FileSize = 0; 
$Attachment = null; 
$fp = null; 

$buffer = sprintf( "From: %s\r\nTo:%s\r\nSubject:%s\r\n", $this->FromName, $this->ToName, $this->Subject); 

if(fputs($this->Socket, "DATA\r\n")<0){ 
return false; 
} 
$this->Line = fgets($this->Socket, 1024); 

$this->Status[ "LASTRESULT"] = substr($this->Line, 0, 1); 
$this->Status[ "LASTRESULTTXT"] = substr($this->Line, 0, 1024); 

if ($this->Status[ "LASTRESULT"] <> "3") return false; 

if(fputs($this->Socket, $buffer)<0){ 
return false; 
} 

if ($this->Attachment == null){ 

if(fputs($this->Socket, "MIME-Version: 1.0\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Transfer-Encoding: 7bit\r\n\r\n")<0){ 
return false; 
} 
if(fputs($this->Socket, "$this->Body\r\n\r\n")<0){ 
return false; 
} 

if(fputs($this->Socket, ".\r\n")<0){ 
return false; 
} 

$this->Line = fgets($this->Socket, 1024); 
if (substr($this->Line, 0, 1) <> "2"){ 
return false; 
}else{ 
return true; 
} 
}else{ 
if(fputs($this->Socket, "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"----=_NextPart_000_01BCFA61.A3697360\"\r\n". 
"Content-Transfer-Encoding: 7bit\r\n\r\n". 
"This is a multi-part message in MIME format.\r\n". 
"\r\n------=_NextPart_000_01BCFA61.A3697360\r\n". 
"Content-Type: text/plain; charset=ISO-8859-1\r\n". 
"Content-Transfer-Encoding: 7bit\r\n". 
"\r\n")<0){ 
return false; 
} 

/* 输出邮件内容 */ 
if(fputs($this->Socket, "$this->Body\r\n\r\n")<0){ 
return false; 
} 

if ( fputs($this->Socket, "\r\n------=_NextPart_000_01BCFA61.A3697360\r\n")<0){ 
return false; 
} 
$FileSize = filesize($this->Attachment); 
if ($FileSize == false){ 
return false; 
} 
if (($fp = fopen($this->Attachment, "r"))== false) { 
return false; 
}else{ 
$Attachment = fread($fp,$FileSize); 
} 

// 如果没有附件的目录 
if (($AttachName = strrchr($this->Attachment, '/')) == false){ 

$AttachName = $this->Attachment; 
} 

if( fputs($this->Socket, 
"Content-Type: application/octet-stream; \r\nname=\"$AttachName\"\r\n". 
"Content-Transfer-Encoding: quoted-printable\r\n". 
"Content-Description: $AttachName\r\n". 
"Content-Disposition: attachment; \r\n\tfilename=\"$AttachName\"\r\n". 
"\r\n")<0){ 
return false; 
} 

/* 输出附件*/ 
if( fputs($this->Socket, $Attachment)<0){ 
return false; 
} 
if ( fputs($this->Socket, "\r\n\r\n------=_NextPart_000_01BCFA61.A3697360--\r\n")<0){ 
return false; 
} 

if( fputs($this->Socket, ".\r\n")<0){ 
return false; 
} 

$this->Line = fgets($this->Socket, 1024); 
if (substr($this->Line, 0, 1) <> "2") 
return false; 

return true; 

} 
} 

function Quit() 
{ 

if(fputs($this->Socket, "QUIT\r\n")<0){ 
return false; 
} 
$this->Line = fgets($this->Socket, 1024); 

$this->Status[ "LASTRESULT"] = substr($this->Line, 0, 1); 
$this->Status[ "LASTRESULTTXT"] = substr($this->Line, 0, 1024); 

if ($this->Status[ "LASTRESULT"] <> "2") return 0; 

return 1; 
} 
function Close() 
{ 
fclose($this->Socket); 
} 
} 
/* 

怎样使用这个程序的一个示例 

$MailTo = new Smtp(); 
$MailTo->SmtpMail("Dave@micro-automation.net","Dave Cramer", 
"Dave@micro-automation.net","David", 
"Test Mail",$MailMessage,"service.tab",0); 
$MailTo->Close(); 
$MailTo=null; 

*/ 
/* 
$pop3 = pop3_open("localhost", "110"); 
if (!$pop3) { 
printf("[ERROR] Failed to connect to localhost<BR>\n"); 
return 0; 
} 

if (!pop3_user($pop3, "unk")) { 
printf("[ERROR] Username failed!<BR>\n"); 
return 0; 
} 

if (!pop3_pass($pop3, "secret")) { 
printf("[ERROR] PASS failed!<BR>\n"); 
return 0; 
} 

$articles = pop3_list($pop3); 
if (!$articles) { 
printf("[ERROR] LIST failed!<BR>\n"); 
return 0; 
} 

for ($i = 1; $i < $articles ["count"] + 1; $i++) 
{ 
printf("i=$i<BR>\n"); 
$data = pop3_retr($pop3,$i); 
if (!$data) { 
printf("data goes wrong on '$i'<BR>\n"); 
return 0; 
} 

for ($j = 0; $j < $data["count"]; $j++) 
{ 
printf("$data[$j]<BR>\n"); 
} 
} 
*/ 
?>
分享给朋友:


CDO.Message 发邮件 Autohotkey 5730

作者为 发表

Autohotkey

Mail("sender@mail.com","receiver@mail.com","测试" A_Now,"正文空空如也")
;qq邮箱需要到网页邮箱设置-账户里面开启smtp服务,密码是另外生成的密码

Mail(from,to,subject,content,attach*){ ;发件人,收件人,标题,正文,附件文件路径数组 eg:["d:\a.xls","d:\b.doc"]
NameSpace := "http://schemas.microsoft.com/cdo/configuration/"
Email := ComObjCreate("CDO.Message")
Email.From := from
Email.To := to
;Email.Cc := "cc@mail.com" ;抄送
;Email.Bcc := "bcc@mail.com" ;暗送
Email.Subject := subject
;Email.Htmlbody := content ;html格式的正文
Email.Textbody := content ;纯文本格式的正文
for k,v in attach
{
IfExist, % v
Email.AddAttachment(v)
}
Email.Configuration.Fields.Item(NameSpace "sendusing") := 2
Email.Configuration.Fields.Item(NameSpace "smtpserver") := "smtp.mail.com" ;SMTP服务器地址
Email.Configuration.Fields.Item(NameSpace "smtpserverport") := 25 ;smtp发送端口 qq:465
Email.Configuration.Fields.Item(NameSpace "smtpauthenticate") := 1 ;需要验证
;Email.Configuration.Fields.Item(NameSpace "smtpusessl") := true ;使用ssl qq等需要
Email.Configuration.Fields.Item(NameSpace "sendusername") := "sender@mail.com" ;邮箱账号
Email.Configuration.Fields.Item(NameSpace "sendpassword") := "password" ;邮箱密码
Email.Configuration.Fields.update()

Email.Fields.Item("urn:schemas:mailheader:disposition-notification-to") := from ;设置“已读”回执
Email.Fields.Item("urn:schemas:mailheader:return-receipt-to") := from ;设置“已送达”回执
Email.Fields.Update()

Email.Send
}


文件与十六进制显示值互转 Autohotkey 4614

作者为 发表

Autohotkey


这是使用File对象把可见十六进制与文件互转的一个函数。

;文件转十六进制
file2hex(file){
	tmp_file := FileOpen(file, "r")
	while not tmp_file.AtEOF { ;没有到结尾
		tmp_file.RawRead(Data, 1)
	tmp_hex := SubStr("00" . ToBase(Asc(Data),16),-1)
	hex = % hex tmp_hex
}
tmp_file.Close()
return hex
}

;十六进制转文件 比如hex=313233 ,文件内容则为123
hex2file(hex,file){
	tmp_file := FileOpen(file, "w")
	if (Mod(StrLen(hex),2)=1) ;不是双数长度
		return -1
	while hex
	{
		StringLeft, tmp_hex, hex, 2
		StringTrimLeft, hex,hex, 2
		tmp_hex := "0x" tmp_hex
		tmp_file.WriteUChar(tmp_hex)
	}
	tmp_file.Close()
	tmp_file =
}

;进制转换函数
ToBase(n,b){
	return (n < b ? "" : ToBase(n//b,b)) . ((d:=Mod(n,b)) < 10 ? d : Chr(d+55))
}


售后CRM定时客户关怀提醒 Autohotkey 3183

作者为 发表

Autohotkey

此脚本为单机绿色小软件,着重突出自定义日期提醒规则,方便与客户高效的进行联系和记录。


注意事项:

1、此脚本所内置的sqlite3.dll为Navicat11自带版本,部分函数其他版本dll没有,请注意不要搞混(编译exe不用考虑此项)。

2、姓名和产品型号可以快速输入,只要你输入部分字词,会自动检索相关项目并添加到下拉框中。

3、16项字段里面有3个日期规则,销售日期匹配提醒规则模板的内容,专属提醒则为指定一次性日期,生日每年当天提醒。

4、标记有6种状态,在刷选的时候注意按提示输入数字而不是汉字。

5、导出的列表为csv格式,如果日期格式有问题可以改后缀为.txt再用Excel手动打开,类型选择”文本“。

#NoEnv
#SingleInstance froce
#Include SQLiteDB.ahk
OnExit, ExitScript
;DIY项目

;主标题
maintitle = 售后定时客户关怀提醒

;预置文件
FileCreateDir, % A_ScriptDir "\ico\"
FileInstall, 1.ico, % A_ScriptDir "\ico\1.ico"
FileInstall, 2.ico, % A_ScriptDir "\ico\2.ico"
FileInstall, 3.ico, % A_ScriptDir "\ico\3.ico"
FileInstall, 4.ico, % A_ScriptDir "\ico\4.ico"
FileInstall, 5.ico, % A_ScriptDir "\ico\5.ico"
FileInstall, 6.ico, % A_ScriptDir "\ico\6.ico"

FileInstall, sqlite3.dll, sqlite3.dll

;初始化连接数据库 以便反复查询
DBFileName := A_ScriptDir . "\after_sales_noti.db"
DB := new SQLiteDB
if !DB.OpenDB(DBFileName) {
	MsgBox, 16, SQLite错误, % "消息:`t" . DB.ErrorMsg . "`n代码:`t" . DB.ErrorCode
	ExitApp
}

;首先检查初始化
if !IsObject(Query("select 1 from sqlite_master where name='noti'")) ;检查提醒模板表
	Exec("CREATE TABLE ""noti"" ( ""noti_level"" TEXT(50), ""noti_rules"" TEXT(255), ""id"" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, CONSTRAINT ""noti_level"" UNIQUE (""noti_level"") ON CONFLICT REPLACE )")
if !IsObject(Query("select 1 from sqlite_master where name='detail'")) ;检查提醒清单表
	Exec("CREATE TABLE ""detail"" (""name""  TEXT(50),""phone""  TEXT(15),""cell""  TEXT(15),""birthday""  TEXT(50),""product_model""  TEXT(255),""product_info""  TEXT(255),""sale_date""  TEXT(20),""qq""  TEXT(50),""mail""  TEXT(100),""address""  TEXT(255),""note""  TEXT(255),""noti_level""  TEXT(50),""timer""  TEXT(50),""state""  INTEGER,""create_date""  TEXT(50),""id""  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)")
if !IsObject(Query("select 1 from sqlite_master where name='setting'")) ;检查设置表
	Exec("CREATE TABLE ""setting"" (""name""  TEXT(50),""value""  TEXT(255),""id""  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)")
if !IsObject(Query("select 1 from setting")) ;如果没有设置项
	Exec("Insert INTO setting (""name"", ""value"") select 'last_login',date('" thisday "');Insert INTO setting (""name"", ""value"") select 'viewed',0;")
if !IsObject(Query("select 1 from noti")) ;如果没有提醒模板
	Exec("Insert INTO noti (""noti_level"", ""noti_rules"") VALUES ('普通用户', '+7|+15');Insert INTO noti (""noti_level"", ""noti_rules"") VALUES ('VIP', '+3|+7|+15');")

;刷选预设
search_options := {"姓名":{"real":"name","method":"等于|包含"}
	,"电话":{"real":"phone","method":"等于|包含"}
	,"手机":{"real":"cell","method":"等于|包含"}
	,"生日":{"real":"date(birthday)","method":"等于|介于|不等于|包含|大于|小于","example1":"1949-10-01","example2":"1959-10-01"}
	,"产品型号":{"real":"product_model","method":"等于|包含"}
	,"产品信息":{"real":"product_info","method":"等于|包含"}
	,"QQ":{"real":"qq","method":"等于|介于|包含|大于|小于"}
	,"邮箱":{"real":"mail","method":"等于|包含"}
	,"地址":{"real":"address","method":"等于|包含"}
	,"备注":{"real":"note","method":"等于|包含"}
	,"提醒规则模板":{"real":"noti_level","method":"等于|包含"}
	,"专属提醒时间":{"real":"date(timer)","method":"等于|介于|大于|小于","example1":"1949-10-01","example2":"1959-10-01"}
	,"标记状态":{"real":"state","method":"等于|不等于","example1":"1"}
	,"创建时间":{"real":"date(create_date)","method":"等于|介于|不等于|包含|大于|小于","example1":"1949-10-01","example2":"1959-10-01"}}

;创建托盘菜单
menu, Tray, NoStandard
Menu, tray, Add, 主界面
Menu, tray, Add, 提醒规则管理
Menu, tray, Add, 开机启动
Menu, tray, Add, 退出
Menu, tray, Default, 主界面

;图标列表
ImageListID := IL_Create(6)
Loop 6
	IL_Add(ImageListID, A_ScriptDir "\ico\" A_Index ".ico")

gosub, 主界面
return

主界面:
	;提醒模板
	noti := Query("select * from noti")
	noti_para =
	for k,v in noti
		noti_para .= noti_para ? "|" v[1] : v[1]
	If main_gui_showed
	{
		Gui, main:show
		ControlGet, l, List, Count, ComboBox3, % maintitle
		Loop % (StrSplit(l,"`n")).MaxIndex()
			Control, Delete, 1, ComboBox3, % maintitle
		GuiControl, main:, noti_level, % noti_para
	}
	else
	{
		Gui, main:Add, Text, x0 y0 w60 h20, 姓  名
		Gui, main:Add, ComboBox, x40 y0 w170 vname gname
		Gui, main:Add, Text, x0 y20 w60 h20, 电  话
		Gui, main:Add, Edit, x40 y20 w170 h20 -Multi vphone
		Gui, main:Add, Text, x0 y40 w60 h20, 手  机
		Gui, main:Add, Edit, x40 y40 w170 h20 -Multi vcell
		Gui, main:Add, Text, x0 y60 w60 h20, Q    Q
		Gui, main:Add, Edit, x40 y60 w170 h20 -Multi vqq
		Gui, main:Add, Text, x0 y80 w60 h20, 邮  箱
		Gui, main:Add, Edit, x40 y80 w170 h20 -Multi vmail
		Gui, main:Add, Text, x0 y120 w60 h20, 地  址
		Gui, main:Add, Edit, x40 y100 w170 h60 vaddress

		Gui, main:Add, Text, x210 y0 w60, 产品型号
		Gui, main:Add, ComboBox, x260 y0 w170 h20 vproduct_model gproduct_model
		Gui, main:Add, Text, x210 y20 w60 h20, 产品信息
		Gui, main:Add, Edit, x260 y20 w170 h40 vproduct_info
		Gui, main:Add, Text, x210 y60 w60 h20, 销售日期
		Gui, main:Add, DateTime, x260 y60 w170 h20 vsale_date
		Gui, main:Add, Text, x210 y80 w60 h20, 专属提醒
		Gui, main:Add, DateTime, x260 y80 w170 h20 vtimer
		Gui, main:Add, Text, x210 y100 w60 h20, 用户生日
		Gui, main:Add, DateTime, x260 y100 w170 h20 vbirthday
		Gui, main:Add, Text, x210 y120 w60 h20, 备    注
		Gui, main:Add, Edit, x260 y120 w170 h40 vnote

		Gui, main:Add, GroupBox, x440 y0 w200 h120, 标记状态
		Gui, main:Add, Radio, x450 y26 w60 h20 gr1 vr1, 1初始化
		Gui, main:Add, Picture, x510 y20 w32 h32 gp1, %A_ScriptDir%\ico\1.ico
		Gui, main:Add, Radio, x542 y26 w60 h20 gr2 vr2, 2再联系
		Gui, main:Add, Picture, x602 y20 w32 h32 gp2, %A_ScriptDir%\ico\2.ico
		Gui, main:Add, Radio, x450 y58 w60 h20 gr3 vr3, 3已完成
		Gui, main:Add, Picture, x510 y52 w32 h32 gp3, %A_ScriptDir%\ico\3.ico
		Gui, main:Add, Radio, x542 y58 w60 h20 gr4 vr4, 4失败
		Gui, main:Add, Picture, x602 y52 w32 h32 gp4, %A_ScriptDir%\ico\4.ico
		Gui, main:Add, Radio, x450 y90 w60 h20 gr5 vr5, 5黑名单
		Gui, main:Add, Picture, x510 y84 w32 h32 gp5, %A_ScriptDir%\ico\5.ico
		Gui, main:Add, Radio, x542 y90 w60 h20 gr6 vr6, 6要上心
		Gui, main:Add, Picture, x602 y84 w32 h32 gp6, %A_ScriptDir%\ico\6.ico
		Gui, main:Add, Text, x440 y120 w200 h20, 客户提醒规则模板
		Gui, main:Add, DDL, x440 y140 w200 R20 vnoti_level, % noti_para

		Gui, main:Add, Button, x0 y170 w100 h20 gnew, 新建资料
		Gui, main:Add, Button, x108 y170 w100 h20 gsave vsave, 保存资料
		Gui, main:Add, Button, x216 y170 w100 h20 gdelete, 删除资料
		Gui, main:Add, Button, x324 y170 w100 h20 gexport, 导出下方列表
		Gui, main:Add, DateTime, x432 y170 w110 h20 vsearch_date,
		Gui, main:Add, Button, x542 y170 w100 h20 gview_thisday, 查看此日提醒

		Gui, main:Add, Text, x20 y203 w100 h20, 查询销售日期从
		Gui, main:Add, DateTime, x120 y200 w200 h20 vsearch_startdate,
		Gui, main:Add, Text, x320 y203 w20 h20, 到
		Gui, main:Add, DateTime, x340 y200 w200 h20 vsearch_enddate,
		Gui, main:Add, Text, x540 y203 w90 h20, 的清单数据

		Gui, main:Add, Text, x20 y223 w30 h20, 筛选
		Gui, main:Add, DropDownList, x50 y220 w150 h20 R20 vsearch_key gsearch_key, 无|姓名|电话|手机|生日|产品型号|产品信息|QQ|邮箱|地址|备注|提醒规则模板|专属提醒时间|标记状态|创建时间
		Gui, main:Add, DropDownList, x200 y220 w50 h20 R10 vsearch_method gsearch_method, 等于|介于|不等于|包含|大于|小于
		Gui, main:Add, Edit, x250 y220 w150 h20 -Multi vsearch_value1,
		Gui, main:Add, Edit, x400 y220 w150 h20 -Multi vsearch_value2,
		Gui, main:Add, Button, x550 y220 w80 h20 gsearch, 查询

		Gui, main:Add, ListView, x0 y240 w640 h200 vmylv gmylv, 姓名|电话|手机|生日|产品型号|产品信息|销售日期|QQ|邮箱|地址|备注|提醒规则模板|专属提醒时间|标记状态|创建时间|ID
		Gui, main:Add, StatusBar, x0 y440 w640 h20,
		Gui, main:Show, , % maintitle
		Gui, main:Default
		LV_SetImageList(ImageListID)
		;OnMessage(0x201, "WM_LButtonDOWN")
		GuiControl, main:, r1, 1
		GuiControl, main:, timer, 19000101
		GuiControl, main:, birthday, 19000101
		main_gui_showed = 1
	}
	gosub, view_thisday
return

;姓名快速提示
name:
	GuiControlGet, name
	result := append2obj(Query("select name from detail where name like '" name "%' group by name"),Query("select name from detail where name like '%" name "%' and name not like '" name "%' group by name"))
	if IsObject(result)
	{
		name_para =
		ControlGet, l, List, Count, ComboBox1, % maintitle
		Loop % (StrSplit(l,"`n")).MaxIndex()
			Control, Delete, 1, ComboBox1, % maintitle
		for k,v in result
			name_para .= name_para ? "|" v[1] : v[1]
		GuiControl, main:, name, % name_para
		SB_SetText("下拉【姓名】可点击待选快速输入!")
	}
return

;产品型号快速提示
product_model:
	GuiControlGet, product_model
	result := append2obj(Query("select product_model from detail where product_model like '" product_model "%' group by product_model"),Query("select product_model from detail where product_model like '%" product_model "%' and product_model not like '" product_model "%' group by product_model"))
	if IsObject(result)
	{
		product_model_para =
		ControlGet, l, List, Count, ComboBox2, % maintitle
		Loop % (StrSplit(l,"`n")).MaxIndex()
			Control, Delete, 1, ComboBox2, % maintitle
		for k,v in result
			product_model_para .= product_model_para ? "|" v[1] : v[1]
		GuiControl, main:, product_model, % product_model_para
		SB_SetText("下拉【产品型号】点击待选可快速输入!")
	}
return

;新建
new:
	SB_SetText("新建")
	change=
	GuiControl, main:, save, 保存资料
	for k,v in ["phone","cell","qq","mail","address","product_info","note"]
	GuiControl, main:, % v,
	for k,v in ["name","product_model","noti_level"]
	GuiControl, main:Choose, % v, 0
	GuiControl, main:, sale_date, % A_Now
	GuiControl, main:, timer, 19000101
	GuiControl, main:, birthday, 19000101
	GuiControl, main:, r1, 1
	gosub, r1
return

;保存
save:
	Gui, main:Submit, NoHide
	if (!noti_level)
	{
		MsgBox, 4112, 错误, 您未选择客户提醒规则模板,请核对!
		return
	}
	if (!name && !phone && !cell)
	{
		MsgBox, 4112, 错误, 您未填写用户姓名或电话,请至少填一项有效信息!
		return
	}
	Loop, 6
	{
		if (r%A_Index%=1)
		{
			state := A_index
			break
		}
	}
	FormatTime, sale_date, % sale_date, yyyy-MM-dd HH:mm:ss
	FormatTime, timer, % timer, yyyy-MM-dd HH:mm:ss
	FormatTime, birthday, % birthday, yyyy-MM-dd HH:mm:ss
	address := RegExReplace(RegExReplace(address,"`r","\r"),"`n","\n")
	note := RegExReplace(RegExReplace(note,"`r","\r"),"`n","\n")
	if !change
		result := Exec("Insert into detail ('name','phone','cell','qq','mail','address','product_model','product_info','sale_date','timer','birthday','note','noti_level','state','create_date') select '" name "','" phone "','" cell "','" qq "','" mail "','" address "','" product_model "','" product_info "','" sale_date "','" timer "','" birthday "','" note "','" noti_level "'," state ",date('" thisday "')")
	else
		result := Exec("update detail set name='" name "',phone='" phone "',cell='" cell "',qq='" qq "',mail='" mail "',address='" address "',product_model='" product_model "',product_info='" product_info "',sale_date='" sale_date "',timer='" timer "',birthday='" birthday "',note='" note "',noti_level='" noti_level "',state=" state " where id=" change_id)
	if result
	{
		SB_SetText("已保存!")
		if issearch
			gosub, refresh
		else
			gosub, view_thisday
		gosub, new
	}
return

;查询
search:
	issearch = 1
	Gui, main:Submit, NoHide
	FormatTime, search_startdate, % search_startdate, yyyy-MM-dd
	FormatTime, search_enddate, % search_enddate, yyyy-MM-dd
	SQL = select * from detail
	condition := {}
	conditions =
	condition.Insert("date(sale_date) between '" search_startdate "' and '" search_enddate "'")
	if (search_key && search_method)
	{
		if search_method = 等于
			condition.Insert(search_options[search_key]["real"] "='" search_value1 "'")
		else if search_method = 介于
			condition.Insert(search_options[search_key]["real"] " between '" search_value1 "' and '" search_value2 "'")
		else if search_method = 不等于
			condition.Insert(search_options[search_key]["real"] "<>'" search_value1 "'")
		else if search_method = 包含
			condition.Insert(search_options[search_key]["real"] " like '%" search_value1 "%'")
		else if search_method = 大于
			condition.Insert(search_options[search_key]["real"] ">'" search_value1 "'")
		else if search_method = 小于
			condition.Insert(search_options[search_key]["real"] "<'" search_value1 "'")
	}
	for k,v in condition
		conditions .= conditions ? " and " v : " where " v
	gosub, refresh
return

;查看指定日期按规则生成的提醒
view_thisday:
	GuiControlGet, search_date
	if search_date
		FormatTime, thisday, % search_date, yyyy-MM-dd
	if !thisday
		FormatTime, thisday, % A_Now, yyyy-MM-dd
	lv_result=
	issearch=
	;获取提醒规则模板
	levels := Query("select noti_level,noti_rules from noti")
	;枚举循环规则
	for i,r in levels
	{
		level := r[1],rule_c:=r[2]
		rules := StrSplit(rule_c,"|")
		for i,rule in rules
		{
			if RegExMatch(rule,"\+(\d{1,5})$",m) ;+xx天
				lv_result := append2obj(lv_result,Query("SELECT * FROM detail WHERE julianday(date('" thisday "'))-julianday(date(sale_date))=" m1 " and noti_level='" level "'"))
			if RegExMatch(rule,"E(\d{1,5})$",m) ;每隔xx天
				lv_result := append2obj(lv_result,Query("SELECT * FROM detail WHERE (Floor(julianday(date('" thisday "'))-julianday(sale_date))-Floor(Floor(julianday(date('" thisday "'))-julianday(sale_date))/" m1 ")*" m1 ")<1 AND julianday(date('" thisday "'))-julianday(date(sale_date))>=1  and noti_level='" level "'"))
			if RegExMatch(rule,"EW$",m) ;按周重复
				lv_result := append2obj(lv_result,Query("SELECT * FROM detail WHERE strftime('%w',sale_date)=strftime('%w',date('" thisday "')) AND julianday(date('" thisday "'))-julianday(date(sale_date))>=1  and noti_level='" level "'"))
			if RegExMatch(rule,"EM$",m) ;按月重复
				lv_result := append2obj(lv_result,Query("SELECT * FROM detail WHERE strftime('%d',sale_date)=strftime('%d',date('" thisday "')) AND julianday(date('" thisday "'))-julianday(date(sale_date))>=1  and noti_level='" level "'"))
			if RegExMatch(rule,"EY$",m) ;按年重复
				lv_result := append2obj(lv_result,Query("SELECT * FROM detail WHERE strftime('%m-%d',sale_date)=strftime('%m-%d',date('" thisday "')) AND julianday(date('" thisday "'))-julianday(date(sale_date))>=1  and noti_level='" level "'"))
			if RegExMatch(rule,"EW(\d{1})$",m) ;每周X
			{
				if (A_WDay=(m1+1>7 ? 1 : a+m1))
					lv_result := append2obj(lv_result,Query("SELECT * FROM detail WHERE noti_level='" level "'"))
			}
			if RegExMatch(rule,"EM(\d{1,2})$",m) ;每月XX
			{
				if (A_DD=m1)
					lv_result := append2obj(lv_result,Query("SELECT * FROM detail WHERE noti_level='" level "'"))
			}
			if RegExMatch(rule,"EM(\d{1,2})$",m) ;每月XX
			{
				if (A_DD=m1)
					lv_result := append2obj(lv_result,Query("SELECT * FROM detail WHERE noti_level='" level "'"))
			}
		}
	}
	;定时提醒
	lv_result := append2obj(lv_result,Query("SELECT * FROM detail WHERE  date(timer)='" A_YYYY "-" A_MM "-" A_DD "'"))
	;生日提醒
	lv_result := append2obj(lv_result,Query("SELECT * FROM detail WHERE  strftime('%m-%d',birthday)='" A_MM "-" A_DD "' AND date(birthday)<>'1900-01-01'"))
	gosub, refresh
return

;筛选方式
search_method:
	GuiControlGet, search_method
	if search_method
	{
		if search_method in 等于,不等于,包含,大于,小于
		{
			GuiControl, main:Enable, search_value1
			GuiControl, main:Disable, search_value2
		}
		else if search_method = 介于
		{
			GuiControl, main:Enable, search_value1
			GuiControl, main:Enable, search_value2
		}
	}
	else
	{
		GuiControl, main:Disable, search_value1
		GuiControl, main:Disable, search_value2
	}
return

;筛选项
search_key:
	GuiControlGet, search_key
	if (search_key<>"无" && search_key)
		GuiControl, main:Enable, search_method
	else
		GuiControl, main:Disable, search_method
	GuiControl, main:Disable, search_value1
	GuiControl, main:Disable, search_value2
	;search_options
	ControlGet, l, List, Count, ComboBox5, % maintitle
	Loop % (StrSplit(l,"`n")).MaxIndex()
		Control, Delete, 1, ComboBox5, % maintitle
	GuiControl, main:, search_method, % search_options[search_key]["method"]
	GuiControl, main:, search_value1, % search_options[search_key]["example1"]
	GuiControl, main:, search_value2, % search_options[search_key]["example2"]
return

;列表
mylv:
show_detail:
	change := 1
	GuiControl, main:, save, 保存修改
	FocusedRowNumber := LV_GetNext(0, "F")
	if not FocusedRowNumber
		return
	SB_SetText("显示列表中第" FocusedRowNumber "行详细信息,可修改保存")
	Loop 16
	{
		LV_GetText(var%A_Index%, FocusedRowNumber,A_Index)
	}
	change_id := var16
	for k,v in {"phone":var2,"cell":var3,"product_info":var6,"qq":var8,"mail":var9}
	GuiControl, main:, % k, % v
	for k,v in {"address":var10,"note":var11}
		GuiControl, main:, % k, % RegExReplace(RegExReplace(v,"\\n","`n"),"\\r","`r")
	for k,v in {"Edit1":var1,"Edit7":var5}
		ControlSetText, % k, % v, % maintitle
	for k,v in noti
	{
		if (var12=v[1])
		{
			GuiControl, main:Choose, noti_level, % k
			break
		}
	}
	for k,v in {"birthday":var4,"sale_date":var7,"timer":var13}
	GuiControl, main:, % k, % RegExReplace(RegExReplace(RegExReplace(v,"\s",""),"-",""),":","")
	gosub, % "r" var14
return

delete:
	FocusedRowNumber := LV_GetNext(0, "F")
	if not FocusedRowNumber
		return
	LV_GetText(Delete_id, FocusedRowNumber,16)
	result := Exec("Delete from detail where id=" Delete_id)
	if result
	{
		MsgBox, 64, 提示, 已删除选中项!
		gosub, refresh
	}
return

;刷新
refresh:
	LV_Delete()
	if issearch
		lv_result := Query(SQL conditions)
	if (IsObject(lv_result) && ObjKeyCount(lv_result))
	{
		for k,v in lv_result
		{
			LV_Add("Icon" . v[14],v[1],v[2],v[3],v[4],v[5],v[6],v[7],v[8],v[9],v[10],v[11],v[12],v[13],v[14],v[15],v[16])
		}
		LV_ModifyCol()
		SB_SetText(k "项结果,双击指定行查看、修改")
	}
	else
		SB_SetText("无结果")
return

;导出
export:
	FileSelectFile, file, S, , 请选择保存位置, CSV文件(*.csv)
	if file
	{
		content = `"姓名`",`"电话`",`"手机`",`"生日`",`"产品型号`",`"产品信息`",`"销售日期`",`"QQ`",`"邮箱`",`"地址`",`"备注`",`"提醒规则模板`",`"专属提醒时间`",`"标记状态`",`"创建时间`",`"ID`"
		for k,v in lv_result
		{
			line =
			for x,y in v
			{
				line .= line ? ",""" y """" : """" y """"
			}
			content .= "`n" line
		}
		file := InStr(file,".csv") ? file : file ".csv"
		FileDelete, % file
		FileAppend, % content, % file
		Run, % file
	}
return

提醒规则管理:
	for k,v in Query("select * from noti")
		notis .= notis ? "|" v[1] : v[1]
	Gui, noti:Destroy
	Gui, noti:Add, Text, x0 y0 w400 h20, 规则模板名称:
	Gui, noti:Add, ComboBox, x0 y20 w400 R20 vnotilevelname gnotilevelname, % notis
	Gui, noti:Add, Text, x0 y40 w400 h20, 规则
	Gui, noti:Add, Edit, x0 y60 w400 h20 -Multi vnotilevelvalue,
	Gui, noti:Add, Button, x0 y80 w130 h20 gnotisubmit, 提交
	Gui, noti:Add, Button, x135 y80 w130 h20 gnotidelete, 删除
	Gui, noti:Add, Button, x270 y80 w130 h20 gnotihelp, 帮助
	Gui, noti:Show, , 提醒规则管理
	Gui, noti:+AlwaysOnTop
return

notilevelname:
	GuiControlGet, notilevelname
	if IsObject(t := Query("select noti_rules from noti where noti_level='" notilevelname "'"))
		GuiControl, noti:, notilevelvalue, % t[1][1]
return

notisubmit:
	Gui, noti:Submit, NoHide
	if (Exec("Replace INTO noti (""noti_level"", ""noti_rules"") VALUES ('" notilevelname "', '" notilevelvalue "')"))
		MsgBox, 4160, 提示, 添加/修改成功!
return

notidelete:
	Gui, noti:Submit, NoHide
	if (Exec("Delete from noti where noti_level='" notilevelname "'"))
		MsgBox, 4160, 提示, 删除成功!
return

notihelp:
	MsgBox, 64, 规则帮助, 规则(n代表数值):`n+nn 延后nn天`nEnn 每隔nn天`nEW 每周`nEWn 每周星期n`nEM 每月`nEMnn 每月nn日`nEY 每年`n多项以“|”分隔`n参照日期以销售日期为准。
return


开机启动:
	RegRead, var, HKCU, Software\Microsoft\Windows\CurrentVersion\Run, after_sales_noti
	last := A_LastError
	if last=2
	{
		RegWrite, REG_SZ, HKCU, Software\Microsoft\Windows\CurrentVersion\Run, after_sales_noti, %A_ScriptFullPath%
		if Errorlevel
			MsgBox, 16, 错误, 没有权限或者被安全软件拦截了,请下次再试!
		else
			Menu, Tray, Check, 开机启动
	}
	if last=0
	{
		RegDelete, HKCU, Software\Microsoft\Windows\CurrentVersion\Run, after_sales_noti
		if Errorlevel
			MsgBox, 16, 错误, 没有权限或者被安全软件拦截了,请下次再试!
		else
			Menu, Tray, UnCheck, 开机启动
	}
return

GuiClose:
	Gui, main:Hide
return

notiGuiClose:
	Gui, noti:Destroy
return

退出:
viewGuiClose:
ExitScript:
	DB.Close
	ExitApp

r1:
p1:
r2:
p2:
r3:
p3:
r4:
p4:
r5:
p5:
r6:
p6:
	lst := [1,2,3,4,5,6]
	Loop % lst.MaxIndex()
	{
		if (RegExReplace(A_ThisLabel,"^\w(\d)$","$1")=A_Index)
			GuiControl, main:, % "r" A_Index, 1
		else
			GuiControl, main:, % "r" lst[A_Index], 0
	}
return

;WM_LButtonDOWN(wParam, lParam)
;{
;	ControlGetFocus, Focus, % maintitle
;	if Focus = SysListView321
;	{
;		change := 1
;        gosub, show_detail
;	}
;}

;合并结果
append2obj(mainobj,obj){
if !IsObject(mainobj)
	mainobj := Object()
id := []
for a,b in mainobj
	id[b[16]]:=1
for k,v in obj
{
	if !id[v[16]]
		mainobj.Insert(v)
}
return mainobj
}

;获取数组项目数
ObjKeyCount(obj){
for k in obj
	i++
return i
}

;构造查询SQL函数
Query(SQL){ ;返回数组
global DB ;全局
if !DB.GetTable(SQL, Result)
	MsgBox, 16, SQLite错误: 获取结果, % "消息:`t" . DB.ErrorMsg . "`n代码:`t" . DB.ErrorCode
if (Result.HasRows) {
	return Result.Rows
}
}

;构造执行SQL函数
Exec(SQL){ ;返回执行影响行数
global DB ;全局
if !DB.Exec(SQL)
	MsgBox, 16, SQLite错误: 获取结果, % "消息:`t" . DB.ErrorMsg . "`n代码:`t" . DB.ErrorCode
return DB._Changes()
}

售后定时客户关怀提醒.zip


httpQuery——强大的网络下载函数 Autohotkey 5555

作者为 发表

Autohotkey网站建设


取自:http://www.autohotkey.com/board/topic/30624-function-httpquery-get-and-post-requests-update-036

httpQuery(byref p1 = "", p2 = "", p3="", p4="")
{   ; v0.3.6 (w) Oct, 26 2010 by derRaphael / zLib-Style release
	; currently the verbs showHeader, storeHeader, and updateSize are supported in httpQueryOps
	; in case u need a different UserAgent, Proxy, ProxyByPass, Referrer, and AcceptType just
	; specify them as global variables - mind the varname for referrer is httpQueryReferer [sic].
	; Also if any special dwFlags are needed such as INTERNET_FLAG_NO_AUTO_REDIRECT or cache
	; handling this might be set using the httpQueryDwFlags variable as global
	global httpQueryOps, httpAgent, httpProxy, httpProxyByPass, httpQueryReferer, httpQueryAcceptType
		, httpQueryDwFlags
	; Get any missing default Values

	;v0.3.6
	; check for syntax
	if ( VarSetCapacity(p1) != 0 )
		dreturn:=true,  result := "", lpszUrl := p1, POSTDATA := p2, HEADERS  := p3
	else
		result := p1, lpszUrl := p2, POSTDATA := p3, HEADERS  := p4

	DefaultOps =
	(LTrim Join|
		httpAgent=AutoHotkeyScript|httpProxy=0|httpProxyByPass=0|INTERNET_FLAG_SECURE=0x00800000
		SECURITY_FLAG_IGNORE_UNKNOWN_CA=0x00000100|SECURITY_FLAG_IGNORE_CERT_CN_INVALID=0x00001000
		SECURITY_FLAG_IGNORE_CERT_DATE_INVALID=0x00002000|SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE=0x00000200
		INTERNET_OPEN_TYPE_PROXY=3|INTERNET_OPEN_TYPE_DIRECT=1|INTERNET_SERVICE_HTTP=3
	)
	Loop,Parse,DefaultOps,|
	{
		RegExMatch(A_LoopField,"(?P<Option>[^=]+)=(?P<Default>.*)",http)
		if StrLen(%httpOption%)=0
			%httpOption% := httpDefault
	}

	; Load Library
	hModule := DllCall("LoadLibrary", "Str", "WinINet.Dll")

	; SetUpStructures for URL_COMPONENTS / needed for InternetCrackURL
	; http://msdn.microsoft.com/en-us/library/aa385420(VS.85).aspx
	offset_name_length:= "4-lpszScheme-255|16-lpszHostName-1024|28-lpszUserName-1024|"
	. "36-lpszPassword-1024|44-lpszUrlPath-1024|52-lpszExtrainfo-1024"
	VarSetCapacity(URL_COMPONENTS,60,0)
	; Struc Size               ; Scheme Size                  ; Max Port Number
	NumPut(60,URL_COMPONENTS,0), NumPut(255,URL_COMPONENTS,12), NumPut(0xffff,URL_COMPONENTS,24)

	Loop,Parse,offset_name_length,|
	{
		RegExMatch(A_LoopField,"(?P<Offset>\d+)-(?P<Name>[a-zA-Z]+)-(?P<Size>\d+)",iCU_)
		VarSetCapacity(%iCU_Name%,iCU_Size,0)
		NumPut(&%iCU_Name%,URL_COMPONENTS,iCU_Offset)
		NumPut(iCU_Size,URL_COMPONENTS,iCU_Offset+4)
	}

	; Split the given URL; extract scheme, user, pass, authotity (host), port, path, and query (extrainfo)
	; http://msdn.microsoft.com/en-us/library/aa384376(VS.85).aspx
	DllCall("WinINet\InternetCrackUrlA","Str",lpszUrl,"uInt",StrLen(lpszUrl),"uInt",0,"uInt",&URL_COMPONENTS)

	; Update variables to retrieve results
	Loop,Parse,offset_name_length,|
	{
		RegExMatch(A_LoopField,"-(?P<Name>[a-zA-Z]+)-",iCU_)
		VarSetCapacity(%iCU_Name%,-1)
	}
	nPort:=NumGet(URL_COMPONENTS,24,"uInt")

	; Import any set dwFlags
	dwFlags := httpQueryDwFlags
	; For some reasons using a selfsigned https certificates doesnt work
	; such as an own webmin service - even though every security is turned off
	; https with valid certificates works when
	if (lpszScheme = "https")
		dwFlags |= (INTERNET_FLAG_SECURE|SECURITY_FLAG_IGNORE_CERT_CN_INVALID
	|SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE)

	; Check for Header and drop exception if unknown or invalid URL
	if (lpszScheme="unknown") {
		Result := "ERR: No Valid URL supplied."
		return StrLen(Result)
	}

	; Initialise httpQuery's use of the WinINet functions.
	; http://msdn.microsoft.com/en-us/library/aa385096(VS.85).aspx
	hInternet := DllCall("WinINet\InternetOpenA"
		,"Str",httpAgent,"UInt"
		,(httpProxy != 0 ?  INTERNET_OPEN_TYPE_PROXY : INTERNET_OPEN_TYPE_DIRECT )
		,"Str",httpProxy,"Str",httpProxyBypass,"Uint",0)

	; Open HTTP session for the given URL
	; http://msdn.microsoft.com/en-us/library/aa384363(VS.85).aspx
	hConnect := DllCall("WinINet\InternetConnectA"
		,"uInt",hInternet,"Str",lpszHostname, "Int",nPort
		,"Str",lpszUserName, "Str",lpszPassword,"uInt",INTERNET_SERVICE_HTTP
		,"uInt",0,"uInt*",0)

	; Do we POST? If so, check for header handling and set default
	if (StrLen(POSTDATA)>0) {
		HTTPVerb:="POST"
		if StrLen(Headers)=0
Headers:="Content-Type: application/x-www-form-urlencoded"
} else ; otherwise mode must be GET - no header Defaults needed
	HTTPVerb:="GET"

; Form the request with proper HTTP protocol version and create the request handle
; http://msdn.microsoft.com/en-us/library/aa384233(VS.85).aspx
hRequest := DllCall("WinINet\HttpOpenRequestA"
	,"uInt",hConnect,"Str",HTTPVerb,"Str",lpszUrlPath . lpszExtrainfo
	,"Str",ProVer := "HTTP/1.1", "Str",httpQueryReferer,"Str",httpQueryAcceptTypes
	,"uInt",dwFlags,"uInt",Context:=0 )

; Send the specified request to the server
; http://msdn.microsoft.com/en-us/library/aa384247(VS.85).aspx
sRequest := DllCall("WinINet\HttpSendRequestA"
	, "uInt",hRequest,"Str",Headers, "uInt",StrLen(Headers)
	, "Str",POSTData,"uInt",StrLen(POSTData))

VarSetCapacity(header, 2048, 0)  ; max 2K header data for httpResponseHeader
VarSetCapacity(header_len, 4, 0)

; Check for returned server response-header (works only _after_ request been sent)
; http://msdn.microsoft.com/en-us/library/aa384238.aspx
Loop, 5
if ((headerRequest:=DllCall("WinINet\HttpQueryInfoA","uint",hRequest
	,"uint",21,"uint",&header,"uint",&header_len,"uint",0))=1)
	break

if (headerRequest=1) {
	VarSetCapacity(res,headerLength:=NumGet(header_len),32)
	DllCall("RtlMoveMemory","uInt",&res,"uInt",&header,"uInt",headerLength)
	Loop,% headerLength
		if (*(&res-1+a_index)=0) ; Change binary zero to linefeed
			NumPut(Asc("`n"),res,a_index-1,"uChar")
	VarSetCapacity(res,-1)
} else
	res := "timeout"

; Get 1st Line of Full Response
Loop,Parse,res,`n,`r
{
	RetValue := A_LoopField
	break
}

; No Connection established - drop exception
if (RetValue="timeout") {
	html := "Error: timeout"
	return -1
}
; Strip protocol version from return value
RetValue := RegExReplace(RetValue,"HTTP/1\.[01]\s+")

; List taken from http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
HttpRetCodes := "100=continue|101=Switching Protocols|102=Processing (WebDAV) (RFC 2518)|"
. "200=OK|201=Created|202=Accepted|203=Non-Authoritative Information|204=No"
. " Content|205=Reset Content|206=Partial Content|207=Multi-Status (WebDAV)"
. "|300=Multiple Choices|301=Moved Permanently|302=Found|303=See Other|304="
. "Not Modified|305=Use Proxy|306=Switch Proxy|307=Temporary Redirect|400=B"
. "ad Request|401=Unauthorized|402=Payment Required|403=Forbidden|404=Not F"
. "ound|405=Method Not Allowed|406=Not Acceptable|407=Proxy Authentication "
. "Required|408=Request Timeout|409=Conflict|410=Gone|411=Length Required|4"
. "12=Precondition Failed|413=Request Entity Too Large|414=Request-URI Too "
. "Long|415=Unsupported Media Type|416=Requested Range Not Satisfiable|417="
. "Expectation Failed|418=I'm a teapot (RFC 2324)|422=UnProcessable Entity "
. "(WebDAV) (RFC 4918)|423=Locked (WebDAV) (RFC 4918)|424=Failed Dependency"
. " (WebDAV) (RFC 4918)|425=Unordered Collection (RFC 3648)|426=Upgrade Req"
. "uired (RFC 2817)|449=Retry With|500=Internal Server Error|501=Not Implem"
. "ented|502=Bad Gateway|503=Service Unavailable|504=Gateway Timeout|505=HT"
. "TP Version Not Supported|506=Variant Also Negotiates (RFC 2295)|507=Insu"
. "fficient Storage (WebDAV) (RFC 4918)|509=Bandwidth Limit Exceeded|510=No"
. "t Extended (RFC 2774)"

; Gather numeric response value
RetValue := SubStr(RetValue,1,3)

; Parse through return codes and set according informations
Loop,Parse,HttpRetCodes,|
{
	HttpreturnCode := SubStr(A_LoopField,1,3)    ; Numeric return value see above
	HttpreturnMsg  := SubStr(A_LoopField,5)      ; link for additional information
	if (RetValue=HttpreturnCode) {
		RetMsg := HttpreturnMsg
		break
	}
}

; Global HttpQueryOps handling
if StrLen(HTTPQueryOps)>0 {
	; Show full Header response (usefull for debugging)
	if (InStr(HTTPQueryOps,"showHeader"))
		MsgBox % res
	; Save the full Header response in a global Variable
	if (InStr(HTTPQueryOps,"storeHeader"))
		global HttpQueryHeader := res
	; Check for size updates to export to a global Var
	if (InStr(HTTPQueryOps,"updateSize")) {
		Loop,Parse,res,`n
			if RegExMatch(A_LoopField,"Content-Length:\s+?(?P<Size>\d+)",full) {
				global HttpQueryFullSize := fullSize
				break
			}
		if (fullSize+0=0)
			HttpQueryFullSize := "size unavailable"
	}
}

; Check for valid codes and drop exception if suspicious
if !(InStr("100 200 201 202 302",RetValue)) {
	Result := RetValue " " RetMsg
	return StrLen(Result)
}

VarSetCapacity(BytesRead,4,0)
fsize := 0
Loop            ; the receiver loop - rewritten in the need to enable
{               ; support for larger file downloads
	bc := A_Index
	VarSetCapacity(buffer%bc%,1024,0) ; setup new chunk for this receive round
	ReadFile := DllCall("wininet\InternetReadFile"
		,"uInt",hRequest,"uInt",&buffer%bc%,"uInt",1024,"uInt",&BytesRead)
	ReadBytes := NumGet(BytesRead)    ; how many bytes were received?
	if ((ReadFile!=0)&&(!ReadBytes))  ; we have had no error yet and received no more bytes
		break                         ; we must be done! so lets break the receiver loop
	else {
		fsize += ReadBytes            ; sum up all chunk sizes for correct return size
		sizeArray .= ReadBytes "|"
	}
	if (InStr(HTTPQueryOps,"updateSize"))
		Global HttpQueryCurrentSize := fsize
}
sizeArray := SubStr(sizeArray,1,-1)   ; trim last PipeChar

VarSetCapacity( ( dReturn == true ) ? result : p1 ,fSize+1,0)      ; reconstruct the result from above generated chunkblocks
Dest := ( dreturn == true ) ? &result : &p1                 ; to a our ByRef result variable
Loop,Parse,SizeArray,|
DllCall("RtlMoveMemory","uInt",Dest,"uInt",&buffer%A_Index%,"uInt",A_LoopField)
	, Dest += A_LoopField

DllCall("WinINet\InternetCloseHandle", "uInt", hRequest)   ; close all opened
DllCall("WinINet\InternetCloseHandle", "uInt", hInternet)
DllCall("WinINet\InternetCloseHandle", "uInt", hConnect)
DllCall("FreeLibrary", "UInt", hModule)                    ; unload the library

if ( dreturn == true ) {
	VarSetCapacity( result, -1 )
	ErrorLevel := fSize
	return Result
} else
return fSize                      ; return the size - strings need update via VarSetCapacity(res,-1)
}


说明:

这个函数有以下功能:


● 支持URL含有端口

● “用户名:密码@域名”格式的URL

● SSL(https)

● HTTP 报头信息 / Dumping(转储) / Storing(存储)

● 下载进度条界面

● 网络连接处理的标识 (自动跟踪特性等)

● 来源页支持

● 客户端接受到的MIME类型的支持

● 代理支持

● 超时支持

● 自定义浏览器UserAgent


使用方法很简单:

0.3.6版本引入另外一种语法与功能支持。从而简化了功能的使用。长话短说:

如果第一个参数不是空变量且包含有URL,httpquery会直接返回数据,消除了额外varsetcapacity的调用需要。然而旧的语法仍然是可用的和工作,所以使用此功能的脚本都需要进行改变。

记住,当处理二进制数据为压缩文件、下载可执行文件、或图片,我们将第一个参数为空值和第二包含URL。


使用新的语法:


html := httpQUERY(URL:="http://url") 将会返回获取到的html全文,长度为Errorlevel,使用的是GET方式,postparams(POST参数)长度为零。

html := httpQUERY(URL:="http://url",POSTDATA) 将会POST数据如果POSTDATA长度不为0


使用老的语法:


你需要定义一个变量将接收返回的数据缓存。所以VarSetCapacity(buffer,-1)释放内存是有必要的。


httpQUERY(buffer:="",URL) 将会返回长度,第一个参数将会缓存获取到的html全文,使用的是GET方式,postparams(POST参数)长度为零。

httpQUERY(buffer:="",URL,POSTDATA) 将会POST数据如果POSTDATA长度不为0


现在支持以下格式的URL:

<!– m –>http://username:pass… … s#fragment<!– m –>


Since httpQuery has been updated to use InternetCrackURL from winINet, all essential parts will be recognized. so there is no need to set up any additional parameters. Attention: When u need to authetificate in the Website the username / password attempt will not work. u have to submit those parameters via POST or GET method. 


Additional Parameters:

To see a dump of the received httpHeaders, there is buildIn support for a global Variable named httpQueryOps. It may consist of one or more Verbs. For now "showHeader", "storeHeader", and "updateSize" verbs are supported. If You use storeHeader the complete Header will be saved in a variable named HttpQueryHeader which will be made global at runtime. The verb updateSize will make two variables globally Available: httpQueryFullSize and httpQueryCurrentSize. An usage example to show a download status indicator is included


以下变量进行全局:

httpAgent:UserAgent,默认是AutoHotkeyScript

httpProxy: 代理,default = 0

httpProxyByPass: 不使用代理的网址列表. default = 0

httpQueryReferer: 来源页

httpQueryAcceptType: 客户端接受到的MIME类型

httpQueryDwFlags: if in need for any special flags for the current connection this is the variable to set (example V shows an useCase for this feat)


示例1 POST数据

url := "http://thinkai.net/test.php"
MsgBox, % httpQUERY(url,"a=1&b=我")

示例2 GET数据

url := "http://thinkai.net/test.php"
MsgBox, % httpQUERY(url "?a=1&b=我")

示例3 下载文件并存储

#noenv
data     := ""
URL      := "http://www.autohotkey.net/programs/AutoHotkey104706.zip"
httpQueryOps := "updateSize"
SetTimer,showSize,10
length   := httpQuery(data,URL)
Tooltip
if (write_bin(data,"ahk.exe",length)!=1)
	MsgBox "出错!"
else
	MsgBox "ahk.zip"已保存!
Return

showSize:
   Tooltip,% HttpQueryCurrentSize "/" HttpQueryFullSize
return

GuiClose:
GuiEscape:
   ExitApp

write_bin(byref bin,filename,size){
   h := DllCall("CreateFile","str",filename,"Uint",0x40000000
            ,"Uint",0,"UInt",0,"UInt",4,"Uint",0,"UInt",0)
   IfEqual h,-1, SetEnv, ErrorLevel, -1
   IfNotEqual ErrorLevel,0,ExitApp ; couldn't create the file
   r := DllCall("SetFilePointerEx","Uint",h,"Int64",0,"UInt *",p,"Int",0)
   IfEqual r,0, SetEnv, ErrorLevel, -3
   IfNotEqual ErrorLevel,0, {
      t = %ErrorLevel%              ; save ErrorLevel to be returned
      DllCall("CloseHandle", "Uint", h)
      ErrorLevel = %t%              ; return seek error
   }
   result := DllCall("WriteFile","UInt",h,"Str",bin,"UInt"
               ,size,"UInt *",Written,"UInt",0)
   h := DllCall("CloseHandle", "Uint", h)
   return, 1
}

#include httpQuery.ahk

示例4  上传图片到Imageshack使用官方(免费)API

; exmpl.imageshack.httpQuery.ahk
; This example uploads an image and constructs a multipart/form-data Type
; for fileuploading and returns the XML which is returned to show the stored Imagepath
	FileSelectFile,image
	FileGetSize,size,%image%
	SplitPath,image,OFN
	FileRead,img,%image%
	VarSetCapacity(placeholder,size,32)
	boundary := makeProperBoundary()
	post:="--" boundary "`ncontent-disposition: form-data; name=""MAX_FILE_SIZE""`n`n"
		. "1048576`n--" boundary "`ncontent-disposition: form-data; name=""xml""`n`nyes`n--"
		. boundary "`ncontent-disposition: form-data; name=""fileupload""; filename="""
		. ofn """`nContent-type: " MimeType(img) "`nContent-Transfer-Encoding: binary`n`n" 
		. placeholder "`n--" boundary "--"
	headers:="Content-type: multipart/form-data, boundary=" boundary "`nContent-Length: " strlen(post)
	DllCall("RtlMoveMemory","uInt",(offset:=&post+strlen(post)-strlen(Boundary)-size-5)
			,"uInt",&img,"uInt",size)
	size := httpQuery(result:="","http://www.imageshack.us/index.php",post,headers)
	VarSetCapacity(result,-1)
	Gui,Add,Edit,w800 h600, % result
	Gui,Show
return

GuiClose:
GuiEscape:
	ExitApp

makeProperBoundary(){
	Loop,26
		n .= chr(64+a_index)
	n .= "0123456789"
	Loop,% StrLen(A_Now) {
		Random,rnd,1,% StrLen(n)
		Random,UL,0,1
		b .= RegExReplace(SubStr(n,rnd,1),".$","$" (round(UL)? "U":"L") "0")
	}
	Return b
}

MimeType(ByRef Binary) {
	MimeTypes:="424d image/bmp|4749463 image/gif|ffd8ffe image/jpeg|89504e4 image/png|4657530"
			 . " application/x-shockwave-flash|49492a0 image/tiff"
	@:="0123456789abcdef"
	Loop,8
		hex .= substr(@,(*(a:=&Binary-1+a_index)>>4)+1,1) substr(@,((*a)&15)+1,1)
	Loop,Parse,MimeTypes,|
		if ((substr(hex,1,strlen(n:=RegExReplace(A_Loopfield,"\s.*"))))=n) 
			Mime := RegExReplace(A_LoopField,".*?\s")
	Return (Mime!="") ? Mime : "application/octet-stream"
}

#include httpQuery.ahk

更多示例详见顶部来源

字符串MD5生成 Autohotkey 4172

作者为 发表

Autohotkey

Clipboard := MD5("mypassword")

MD5(string, encoding = "UTF-8")
{
    return CalcStringHash(string, 0x8003, encoding)
}

; CalcAddrHash ======================================================================
CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0)
{
    static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f"]
    static b := h.minIndex()
    hProv := hHash := o := ""
    if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xf0000000))
    {
        if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash))
        {
            if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0))
            {
                if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0))
                {
                    VarSetCapacity(hash, hashlength, 0)
                    if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0))
                    {
                        loop % hashlength
                        {
                            v := NumGet(hash, A_Index - 1, "UChar")
                            o .= h[(v >> 4) + b] h[(v & 0xf) + b]
                        }
                    }
                }
            }
            DllCall("advapi32\CryptDestroyHash", "Ptr", hHash)
        }
        DllCall("advapi32\CryptReleaseContext", "Ptr", hProv, "UInt", 0)
    }
    return o
}

; CalcStringHash ====================================================================
CalcStringHash(string, algid, encoding = "UTF-8", byref hash = 0, byref hashlength = 0)
{
    chrlength := (encoding = "CP1200" || encoding = "UTF-16") ? 2 : 1
    length := (StrPut(string, encoding) - 1) * chrlength
    VarSetCapacity(data, length, 0)
    StrPut(string, &data, floor(length / chrlength), encoding)
    return CalcAddrHash(&data, length, algid, hash, hashlength)
}

摘自HashCalc http://www.autohotkey.com/board/topic/86157-hashgenerator-with-verify-md2-md5-sha1-sha2-hmac

这个函数改自http://www.autohotkey.com/board/topic/101686-objectresponsetext-error/#entry667257

实现的是免文件读写下载网页代码

;示例1 POST数据
url := "http://thinkai.net/test.php"
MsgBox, % URLDownloadToVar(url,"utf-8","POST","a=1&b=2")

;示例2 GET数据
url := "http://thinkai.net/test.php"
MsgBox, % URLDownloadToVar(url "?config=设置","utf-8","GET")

URLDownloadToVar(url, Encoding = "",Method="GET",postData=""){ ;网址,编码,请求方式,post数据
	hObject:=ComObjCreate("WinHttp.WinHttpRequest.5.1")
	try
	{
		hObject.SetTimeouts(30000,30000,1200000,1200000)
		hObject.Open(Method,url,(Method="POST" ? True : False))
		hObject.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
		if IsObject(headers)
		{
			for k,v in headers
				hObject.SetRequestHeader(k, v)
		}
		hObject.Send(postData)
		if (Method="POST")
			hObject.WaitForResponse(-1)
	}
	catch e
		return -1
	if (Encoding && hObject.ResponseBody)
	{
		oADO := ComObjCreate("adodb.stream")
		oADO.Type := 1
		oADO.Mode := 3
		oADO.Open()
		oADO.Write(hObject.ResponseBody)
		oADO.Position := 0
		oADO.Type := 2
		oADO.Charset := Encoding
		return oADO.ReadText(), oADO.Close()
	}
	return hObject.ResponseText
}


Excel维语汉语数据分离(通过姓名) Autohotkey 10266

作者为 发表

Autohotkey

#MaxMem 1024
#NoTrayIcon
#SingleInstance, force
gui, add, button, x0 y0 w300 h42 gget, 复制Excel表格数据后点此分析生成
gui, show, , 维汉语筛选区分工具
Return

get:
;转化为数组
;初始化
ExcelObj := {}
;获取
Clip_now := Clipboard
;转化成数组
if (InStr(Clip_now, "`t"))
{
	StringReplace, Clip_now, Clip_now, `r, , All
	StringSplit, line, Clip_now, `n
	Loop % line0
	{
		tmp_line := line%A_Index%
		y_id := A_Index
		if tmp_line
		{
			StringSplit, var, tmp_line, `t
			Loop % var0
			{
				tmp_var := var%A_Index%
				x_id := A_index
				ExcelObj[y_id,x_id] := tmp_var
			}
		}
	}
}

InputBox, title, 提示, 请输入一个名称!
if title =
	title = 未命名
if !isobject(ExcelObj)
{
	MsgBox, 48, 错误, 您未粘贴EXCEL数据!
	Return
}
;横向纵向最列数   后面不会用到
x_max := ExcelObj[1].Maxindex()
y_max := ExcelObj.Maxindex()
outf =
id=0
;生成选择的下拉菜单
for k,v in  ExcelObj[1]
{
	id++
	outf .= outf ? "|" id "【" v "】" : id "【" v "】"
}
gui, 2:add, DropDownList, x0 y0 w300 h400 vchoose, %outf%
gui, 2:add, button, x0 y20 w300 h20 gok, 确定
gui, 2:show, ,请选择姓名所在字段!
Return

ok:
GuiControlGet, choose
if choose =
{
	MsgBox, 48, 错误, 您为选择姓名所在字段!
	Return
}
SplashTextOn, 200, 20, 提示, 分析生成中!
gui, 2:Destroy
;分割所选
StringSplit, v, choose, 【,
;姓名所在列id
ziduan = %v1%
goto, goon
Return

goon:
hanyu_data =
uyghur_data =
idx = 0
;
for k,v in ExcelObj
{
idx++
key := ExcelObj[idx][ziduan]
StringReplace, key, key, %A_Space%, , All
key := RegExReplace(key,"(\.|。|·)$","")
;汉字姓氏开头
if RegExMatch(key,"^(赵|钱|孙|李|周|吴|郑|王|冯|陈|褚|卫|蒋|沈|韩|杨|朱|秦|尤|许|何|吕|施|张|孔|曹|严|华|金|魏|陶|姜|戚|谢|邹|喻|柏|水|窦|章|云|苏|潘|葛|奚|范|彭|郎|鲁|韦|昌|马|苗|凤|花|方|俞|任|袁|柳|酆|鲍|史|唐|费|廉|岑|薛|雷|贺|倪|汤|滕|殷|罗|毕|郝|邬|安|常|乐|于|时|傅|皮|卞|齐|康|伍|余|元|卜|顾|孟|平|黄|和|穆|萧|尹|姚|邵|湛|汪|祁|毛|禹|狄|米|贝|明|臧|计|伏|成|戴|谈|宋|茅|庞|熊|纪|舒|屈|项|祝|董|梁|杜|阮|蓝|闵|席|季|麻|强|贾|路|娄|危|江|童|颜|郭|梅|盛|林|刁|钟|徐|邱|骆|高|夏|蔡|田|樊|胡|凌|霍|虞|万|支|柯|咎|管|卢|莫|经|房|裘|缪|干|解|应|宗|宣|丁|贲|邓|郁|单|杭|洪|包|诸|左|石|崔|吉|钮|龚|程|嵇|邢|滑|裴|陆|荣|翁|荀|羊|於|惠|甄|魏|加|封|芮|羿|储|靳|汲|邴|糜|松|井|段|富|巫|乌|焦|巴|弓|牧|隗|山|谷|车|侯|宓|蓬|全|郗|班|仰|秋|仲|伊|宫|宁|仇|栾|暴|甘|钭|厉|戎|祖|武|符|刘|姜|詹|束|龙|叶|幸|司|韶|郜|黎|蓟|薄|印|宿|白|怀|蒲|台|从|鄂|索|咸|籍|赖|卓|蔺|屠|蒙|池|乔|阴|郁|胥|能|苍|双|闻|莘|党|翟|谭|贡|劳|逄|姬|申|扶|堵|冉|宰|郦|雍|却|璩|桑|桂|濮|牛|寿|通|边|扈|燕|冀|郏|浦|尚|农|温|别|庄|晏|柴|瞿|阎|充|慕|连|茹|习|宦|艾|鱼|容|向|古|易|慎|戈|廖|庚|终|暨|居|衡|步|都|耿|满|弘|匡|国|文|寇|广|禄|阙|东|殴|殳|沃|利|蔚|越|夔|隆|师|巩|厍|聂|晁|勾|敖|融|冷|訾|辛|阚|那|简|饶|空|曾|毋|沙|乜|养|鞠|须|丰|巢|关|蒯|相|查|后|江|红|游|竺|权|逯|盖|益|桓|公|万|俟|司马|上官|欧阳|夏侯|诸葛|闻人|东方|赫连|皇甫|尉迟|公羊|澹台|公冶|宗政|濮阳|淳于|仲孙|太叔|申屠|公孙|乐正|轩辕|令狐|钟离|闾丘|长孙|慕容|鲜于|宇文|司徒|司空|亓官|司寇|仉督|子车|颛孙|端木|巫马|公西|漆雕|乐正|壤驷|公良|拓拔|夹谷|宰父|谷粱|晋楚|阎法|汝鄢|涂钦|段干|百里|东郭|南门|呼延|归海|羊舌|微生|岳帅|缑亢|况后|有琴|梁丘|左丘|东门|西门|商牟|佘佴|伯赏|南宫|墨哈|谯笪|年爱|阳佟|第五|言福).*")
{
	tmp_line =
	for a,b in ExcelObj[idx]
		tmp_line .= tmp_line ? "," b : b
	hanyu_data .= hanyu_data ? "`n" tmp_line : tmp_line
}
;维语名字关键词
Else if key Contains 阿巴,阿卜,阿不,阿布,阿达,阿迪,阿地,阿尔,阿洪,阿吉,阿勒,阿里,阿力,阿丽,阿曼,阿米,阿娜,阿西,阿依,阿克,努尔,阿依,曼孜,沙吾,喀拉,阿拜,别克,迈尔,迈尔,扎提,艾伟,帕,霍尔,艾伟,阿依,夏姆,阿依,乌力,夏木,阿依,谢姆,阿扎,提,艾尔,艾海,提,艾合,艾科,拜尔,艾克,巴尔,艾拉,艾勒,坎木,艾里,艾力,凯木,艾尼,瓦尔,艾萨,艾散,艾沙,艾山,艾依,艾则,孜,艾孜,安拉,安外,奥斯,巴哈,巴克,巴拉,巴图,巴土,巴依,拜合,亚尔,包尔,布里,布力,布威,布韦,布维,达尼,达瓦,达伍,托科,达吾,迪里,迪丽,热巴,迪亚,额敏,古海,古丽,罕,娜尔,斯坦,苏如,苏茹,扎尔,扎热,古再,古赞,果海,哈迪,哈尔,哈古,哈基,哈克,哈里,哈丽,哈力,哈米,哈热,哈斯,哈孜,海力,且木,海丽,且姆,罕,扎代,赫克,买提,赫克木,赫木热,吉利力,吉乃,斯太,加马力,贾马力,杰力力,居尔,艾提,居玛,居麦,居热,喀迪,喀日,喀斯,喀伍,卡,佧马力,佧米力,开萨尔,凯赛尔,坎吉,坎曼尔,柯日木,柯则,柯孜,克热木,克孜,库尔班,阔其,喀尔,玛斯,买买提,麦尔,麦合,麦吉,麦丽,麦买,买买,买卖,麦麦,麦苏木,毛拉,莫敏,莫明,姆,穆巴,热科,穆巴,热克,穆海,麦提,穆罕,买提,穆合,塔尔,穆坎,妲斯,穆萨,穆台,力甫,穆太,力普,木丽,德尔,穆再,排尔,娜扎,开提,乃比,南比,妮尕尔,妮萨,尼格尔,尼加提,尼鲁,尼露,尼萨,尼莎,尼牙孜,尼亚孜,尼叶蒂,尼扎木,努尔,努斯,热提,则力,帕,孜力,皮达,普拉提,齐曼,奇曼,乔力潘,乔丽番,乔丽潘,冉娜,热合曼,热赫木,热杰普,热介甫,热克甫,热娜,热依罕,热依汉,热扎克,热孜宛,热孜婉,肉索力,肉孜,如苏力,如孜,茹仙,萨阿,代提,萨巴,海提,萨比尔,萨比提,萨迪克,萨拉,买提,萨拉,麦提,萨拉木,萨吾提,萨依提,赛尔旦,赛福鼎,赛娜瓦尔,赛乃姆,赛乃木,赛排尔,赛皮丁,赛依提,色提,瓦力迪,色依提,沙巴海提,沙比尔,沙比提,沙拉买提,沙吾提,沙依提,司的克,斯拉木,苏里唐,苏力坦,苏皮,塔吉古丽,塔里甫,塔力甫,塔力普,塔西布拉克,塔依,坦吾皮克,提拉,提力瓦力迪,铁木尔,图尔,吐,托合提,瓦力斯,瓦热斯,维力,乌齐坤,乌图克,吾,吾守尔,吾吐克,吴尔凯西,西力甫,西热甫,西仁,希林,希仁,夏热拜提,仙拜,鲜拜,肖开特,肖开提,谢力甫,谢木斯,谢热甫,秀库尔,许库尔,雪合,拉提,来提,牙力昆,雅库甫,亚库,亚里坤,亚力坤,尧乐,博斯,尧勒,巴斯,伊巴,代提,伊禅,伊盖,伊里,哈木,依力,伊力,伊马木,伊敏,伊纳耶提,伊排提,伊善,伊斯拉哈提,伊斯拉木,依干拜尔迪,依明,吐尔,尤丽吐孜,玉丽吐孜,玉素甫,玉孜,叶尔,约麦尔,约日耶提,哈斯德尔,再乃甫,再乃普,扎伊提,罗提,布拉,孜,孜巴,孜亚,祖合热,祖姆,祖木,佐合热
{
	tmp_line =
	for a,b in ExcelObj[idx]
		tmp_line .= tmp_line ? "," b : b
	uyghur_data .= uyghur_data ? "`n" tmp_line : tmp_line
}
;中间带点
Else if RegExMatch(key,".*(\.|。|·).*")
{
	tmp_line =
	for a,b in ExcelObj[idx]
		tmp_line .= tmp_line ? "," b : b
	uyghur_data .= uyghur_data ? "`n" tmp_line : tmp_line
}
Else
{
{
	tmp_line =
	for a,b in ExcelObj[idx]
		tmp_line .= tmp_line ? "," b : b
	hanyu_data .= hanyu_data ? "`n" tmp_line : tmp_line
}
}
}
FileCreateDir, %A_ScriptDir%\%title%\
FileAppend, %uyghur_data%, %A_ScriptDir%\%title%\%title%_维语_%A_Now%.csv
FileAppend, %hanyu_data%, %A_ScriptDir%\%title%\%title%_汉语_%A_Now%.csv
SplashTextOff
MsgBox, 64, 提示, 已经分析生成完成!将会为您打开所在文件夹!
content =
run, %A_ScriptDir%\%title%\
Return


GuiClose:
ExitApp

EXCEL分维汉语数据.zip


Socket套接字后台服务器和客户端 Autohotkey 7794

作者为 发表

Autohotkey


因工作需要使用Asterisk AMI接口,是套接字连接方式的,用php单线程不好用,所以找了一下资料,改动下成后台静默模式,当然你也可以自己改有界面的。

服务器Server:

;thinkai@2014-11-08
;Based on http://www.autohotkey.com/board/topic/29650-tcpip-serverclient-chat-script-w-features
#singleinstance force
OnExit, exit
;创建窗口以接收数据
Gui, add, Edit
gui, hide
;ip和端口
Network_Address = 0.0.0.0
Network_Port = 1000
;准备传入连接
socket := PrepareForIncomingConnection(Network_Address, Network_Port)
if socket = -1
    ExitApp
Process, Exist
;获取窗口句柄
DetectHiddenWindows On
ScriptMainWindowId := WinExist("ahk_class AutoHotkey ahk_pid " . ErrorLevel)
DetectHiddenWindows Off
NotificationMsg = 0x5555
;设置接收消息的函数
OnMessage(NotificationMsg, "ReceiveData")
FD_READ = 1
FD_CLOSE = 32
FD_CONNECT = 20
if DllCall("Ws2_32\WSAAsyncSelect", "UInt", socket, "UInt", ScriptMainWindowId, "UInt", NotificationMsg, "Int", FD_READ|FD_CONNECT)
{
    MsgBox % "WSAAsyncSelect() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError")
    ExitApp
}
;循环获取新连入客户端
i=1
Loop
{
    VarSetCapacity(SocketAddress, SizeOfSocketAddress:=16)
    ;Socket连接
    conectioncheck%i% := DllCall("Ws2_32\accept", "UInt", socket, "UInt", &SocketAddress, "Int*", SizeOfSocketAddress)
    if conectioncheck%i% != -1
    {
        ;该客户端连接对象为conectioncheck%i% 发送数据时需要
        ;客户端IP:端口 xxx.xxx.xxx.xxx:xxxx
        peername := DllCall("Ws2_32\inet_ntoa", "uint", NumGet(SocketAddress,4), "str")
            . ":" NumGet(SocketAddress,2,"ushort")
        ;发送欢迎信息
        SendData(conectioncheck%i%,"欢迎" peername)
        i++
    }
    sleep 500
}
return

;给所有客户端发消息
sendall:
Loop %i% {
   SendData(conectioncheck%A_Index%,SendText)
}
SendText=
return


;准备传入连接函数
PrepareForIncomingConnection(IPAddress, Port)
{
    VarSetCapacity(wsaData, 32)
    result := DllCall("Ws2_32\WSAStartup", "UShort", 0x0002, "UInt", &wsaData) ; Request Winsock 2.0 (0x0002)

    if ErrorLevel
    {
        MsgBox WSAStartup() could not be called due to error %ErrorLevel%. Winsock 2.0 or higher is required.
        return -1
    }
    if result
    {
        MsgBox % "WSAStartup() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError")
        return -1
    }

    AF_INET = 2
    SOCK_STREAM = 1
    IPPROTO_TCP = 6
    socket := DllCall("Ws2_32\socket", "Int", AF_INET, "Int", SOCK_STREAM, "Int", IPPROTO_TCP)
    if socket = -1
    {
        MsgBox % "socket() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError")
        return -1
    }


    SizeOfSocketAddress = 16
    VarSetCapacity(SocketAddress, SizeOfSocketAddress)
    InsertInteger(2, SocketAddress, 0, AF_INET)   ; sin_family
    InsertInteger(DllCall("Ws2_32\htons", "UShort", Port), SocketAddress, 2, 2)   ; sin_port
    InsertInteger(DllCall("Ws2_32\inet_addr", "Str", IPAddress), SocketAddress, 4, 4)   ; sin_addr.s_addr

    if DllCall("Ws2_32\bind", "UInt", socket, "UInt", &SocketAddress, "Int", SizeOfSocketAddress)
    {
        MsgBox % "bind() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError") . "?"
        return -1
    }
    if DllCall("Ws2_32\listen", "UInt", socket, "UInt", "SOMAXCONN")
    {
        MsgBox % "LISTEN() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError") . "?"
        return -1
    }
    return socket
}

;接收消息函数
ReceiveData(wParam, lParam)
{
Critical
   global ShowRecieved
    socket := wParam
    ReceivedDataSize = 4096
    Loop
    {
        VarSetCapacity(ReceivedData, ReceivedDataSize, 0)
        ReceivedDataLength := DllCall("Ws2_32\recv", "UInt", socket, "Str", ReceivedData, "Int", ReceivedDataSize, "Int", 0)
        if ReceivedDataLength = -1
        {
            WinsockError := DllCall("Ws2_32\WSAGetLastError")
            if WinsockError = 10035
                return 1
            if WinsockError <> 10054

MsgBox % "recv() indicated Winsock error " . WinsockError
ExitApp
        }
    ;addmsg(ReceivedData)
    ;此处已获取到消息
    MsgBox % ReceivedData
    }
    return 1
}

;发送消息函数
SendData(wParam,SendData)
{
socket := wParam
SendDataSize := VarSetCapacity(SendData)
SendDataSize += 1
sendret := DllCall("Ws2_32\send", "UInt", socket, "Str", SendData, "Int", SendDatasize, "Int", 0)
}



InsertInteger(pInteger, ByRef pDest, pOffset = 0, pSize = 4)
{
    Loop %pSize%
        DllCall("RtlFillMemory", "UInt", &pDest + pOffset + A_Index-1, "UInt", 1, "UChar", pInteger >> 8*(A_Index-1) & 0xFF)
}


CloseSocket(Socket)
{
    Result := DllCall("Ws2_32\closesocket"
                       , "UInt", Socket)
    Return result
}


exit:
;清除连接
Loop %i% {
   CloseSocket(conectioncheck%A_Index%)
}
DllCall("Ws2_32\WSACleanup")
ExitApp

客户端Client:

;thinkai@2014-11-08
;Based on http://www.autohotkey.com/board/topic/29650-tcpip-serverclient-chat-script-w-features
#singleinstance force
OnExit, exit
;创建窗口以接收数据
Gui, add, Edit
Gui, hide
;客户端名称 服务器地址 端口
ClientName=%A_Computername%
Network_Address = 135.230.71.250
Network_Port = 1000
;连接到服务器
socket := ConnectToAddress(Network_Address, Network_Port)
if socket = -1
    ExitApp
;获取窗口句柄
Process, Exist
DetectHiddenWindows On
ScriptMainWindowId := WinExist("ahk_class AutoHotkey ahk_pid " . ErrorLevel)
DetectHiddenWindows Off
;获取窗口句柄
NotificationMsg = 0x5555  ; An arbitrary message number, but should be greater than 0x1000.
OnMessage(NotificationMsg, "ReceiveData")
FD_READ = 1     ; Received when data is available to be read.
FD_CLOSE = 32   ; Received when connection has been closed.
if DllCall("Ws2_32\WSAAsyncSelect", "UInt", socket, "UInt", ScriptMainWindowId, "UInt", NotificationMsg, "Int", FD_READ|FD_CLOSE)
{
    MsgBox % "WSAAsyncSelect() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError")
    ExitApp
}
;发送连接好消息
SendData(socket,ClientName " Login!")
return

;发送消息
send:
SendData(socket,SendText)
SendText =
return

;连接服务器函数
ConnectToAddress(IPAddress, Port)
{
    VarSetCapacity(wsaData, 32)
    result := DllCall("Ws2_32\WSAStartup", "UShort", 0x0002, "UInt", &wsaData)
    if ErrorLevel
    {
        MsgBox WSAStartup() could not be called due to error %ErrorLevel%. Winsock 2.0 or higher is required.
        return -1
    }
    if result
    {
        MsgBox % "WSAStartup() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError")
        return -1
    }

    AF_INET = 2
    SOCK_STREAM = 1
    IPPROTO_TCP = 6
    socket := DllCall("Ws2_32\socket", "Int", AF_INET, "Int", SOCK_STREAM, "Int", IPPROTO_TCP)
    if socket = -1
    {
        MsgBox % "socket() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError")
        return -1
    }


    SizeOfSocketAddress = 16
    VarSetCapacity(SocketAddress, SizeOfSocketAddress)
    InsertInteger(2, SocketAddress, 0, AF_INET)
    InsertInteger(DllCall("Ws2_32\htons", "UShort", Port), SocketAddress, 2, 2)
    InsertInteger(DllCall("Ws2_32\inet_addr", "Str", IPAddress), SocketAddress, 4, 4)


    if DllCall("Ws2_32\connect", "UInt", socket, "UInt", &SocketAddress, "Int", SizeOfSocketAddress)
    {
        MsgBox % "connect() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError") . "?"
        return -1
    }
    return socket
}

;接收函数
ReceiveData(wParam, lParam)
{
Critical
   global ShowRecieved
    socket := wParam
    ReceivedDataSize = 4096
    Loop
    {
        VarSetCapacity(ReceivedData, ReceivedDataSize, 0)
        ReceivedDataLength := DllCall("Ws2_32\recv", "UInt", socket, "Str", ReceivedData, "Int", ReceivedDataSize, "Int", 0)
        if ReceivedDataLength = 0
            ExitApp
        if ReceivedDataLength = -1
        {
            WinsockError := DllCall("Ws2_32\WSAGetLastError")
            if WinsockError = 10035
                return 1
            if WinsockError <> 10054

              MsgBox % "recv() indicated Winsock error " . WinsockError
            ExitApp
        }
		;ReceivedData
    }
    return 1
}

;发送函数
SendData(wParam,SendData)
{
socket := wParam
SendDataSize := VarSetCapacity(SendData)
SendDataSize += 1
sendret := DllCall("Ws2_32\send", "UInt", socket, "Str", SendData, "Int", SendDatasize, "Int", 0)
}

InsertInteger(pInteger, ByRef pDest, pOffset = 0, pSize = 4)

{
    Loop %pSize%
        DllCall("RtlFillMemory", "UInt", &pDest + pOffset + A_Index-1, "UInt", 1, "UChar", pInteger >> 8*(A_Index-1) & 0xFF)
}


CloseSocket(Socket)
{
    Result := DllCall("Ws2_32\closesocket"
                       , "UInt", Socket)
    Return result
}


GuiClose:
exit:
;清除连接
CloseSocket(socket)
DllCall("Ws2_32\WSACleanup")
ExitApp



友情链接:Autohotkey中文帮助Autohotkey官网Autohotkey中文网联系作者免GooglePlay APK下载

 主题设计 • skyfrit.com  Thinkai's Blog | 保留所有权利

43 queries in 1.191 seconds |