init
This commit is contained in:
1 parent
300b277af3
commit
7084aa69f4
328 files changed
+55628
No files matched your search
@@ -0,0 +1,301 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.33.0
|
||||
// protoc v3.6.1
|
||||
// source: msg.proto
|
||||
|
||||
package wechat
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type SubMessage1 struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Field1 int32 `protobuf:"varint,1,opt,name=field1,proto3" json:"field1,omitempty"`
|
||||
Field2 int32 `protobuf:"varint,2,opt,name=field2,proto3" json:"field2,omitempty"`
|
||||
}
|
||||
|
||||
func (x *SubMessage1) Reset() {
|
||||
*x = SubMessage1{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_msg_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *SubMessage1) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*SubMessage1) ProtoMessage() {}
|
||||
|
||||
func (x *SubMessage1) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_msg_proto_msgTypes[0]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use SubMessage1.ProtoReflect.Descriptor instead.
|
||||
func (*SubMessage1) Descriptor() ([]byte, []int) {
|
||||
return file_msg_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *SubMessage1) GetField1() int32 {
|
||||
if x != nil {
|
||||
return x.Field1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *SubMessage1) GetField2() int32 {
|
||||
if x != nil {
|
||||
return x.Field2
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type SubMessage2 struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Field1 int32 `protobuf:"varint,1,opt,name=field1,proto3" json:"field1,omitempty"`
|
||||
Field2 string `protobuf:"bytes,2,opt,name=field2,proto3" json:"field2,omitempty"`
|
||||
}
|
||||
|
||||
func (x *SubMessage2) Reset() {
|
||||
*x = SubMessage2{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_msg_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *SubMessage2) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*SubMessage2) ProtoMessage() {}
|
||||
|
||||
func (x *SubMessage2) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_msg_proto_msgTypes[1]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use SubMessage2.ProtoReflect.Descriptor instead.
|
||||
func (*SubMessage2) Descriptor() ([]byte, []int) {
|
||||
return file_msg_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *SubMessage2) GetField1() int32 {
|
||||
if x != nil {
|
||||
return x.Field1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *SubMessage2) GetField2() string {
|
||||
if x != nil {
|
||||
return x.Field2
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type MessageBytesExtra struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Message1 *SubMessage1 `protobuf:"bytes,1,opt,name=message1,proto3" json:"message1,omitempty"`
|
||||
Message2 []*SubMessage2 `protobuf:"bytes,3,rep,name=message2,proto3" json:"message2,omitempty"`
|
||||
}
|
||||
|
||||
func (x *MessageBytesExtra) Reset() {
|
||||
*x = MessageBytesExtra{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_msg_proto_msgTypes[2]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *MessageBytesExtra) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*MessageBytesExtra) ProtoMessage() {}
|
||||
|
||||
func (x *MessageBytesExtra) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_msg_proto_msgTypes[2]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use MessageBytesExtra.ProtoReflect.Descriptor instead.
|
||||
func (*MessageBytesExtra) Descriptor() ([]byte, []int) {
|
||||
return file_msg_proto_rawDescGZIP(), []int{2}
|
||||
}
|
||||
|
||||
func (x *MessageBytesExtra) GetMessage1() *SubMessage1 {
|
||||
if x != nil {
|
||||
return x.Message1
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *MessageBytesExtra) GetMessage2() []*SubMessage2 {
|
||||
if x != nil {
|
||||
return x.Message2
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_msg_proto protoreflect.FileDescriptor
|
||||
|
||||
var file_msg_proto_rawDesc = []byte{
|
||||
0x0a, 0x09, 0x6d, 0x73, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0c, 0x61, 0x70, 0x70,
|
||||
0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x22, 0x3d, 0x0a, 0x0b, 0x53, 0x75, 0x62,
|
||||
0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x31, 0x12, 0x16, 0x0a, 0x06, 0x66, 0x69, 0x65, 0x6c,
|
||||
0x64, 0x31, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x06, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x31,
|
||||
0x12, 0x16, 0x0a, 0x06, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x32, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05,
|
||||
0x52, 0x06, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x32, 0x22, 0x3d, 0x0a, 0x0b, 0x53, 0x75, 0x62, 0x4d,
|
||||
0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x32, 0x12, 0x16, 0x0a, 0x06, 0x66, 0x69, 0x65, 0x6c, 0x64,
|
||||
0x31, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x06, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x31, 0x12,
|
||||
0x16, 0x0a, 0x06, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x32, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52,
|
||||
0x06, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x32, 0x22, 0x81, 0x01, 0x0a, 0x11, 0x4d, 0x65, 0x73, 0x73,
|
||||
0x61, 0x67, 0x65, 0x42, 0x79, 0x74, 0x65, 0x73, 0x45, 0x78, 0x74, 0x72, 0x61, 0x12, 0x35, 0x0a,
|
||||
0x08, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x31, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32,
|
||||
0x19, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53,
|
||||
0x75, 0x62, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x31, 0x52, 0x08, 0x6d, 0x65, 0x73, 0x73,
|
||||
0x61, 0x67, 0x65, 0x31, 0x12, 0x35, 0x0a, 0x08, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x32,
|
||||
0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x70, 0x72, 0x6f,
|
||||
0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x75, 0x62, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65,
|
||||
0x32, 0x52, 0x08, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x32, 0x42, 0x09, 0x5a, 0x07, 0x2e,
|
||||
0x3b, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
|
||||
}
|
||||
|
||||
var (
|
||||
file_msg_proto_rawDescOnce sync.Once
|
||||
file_msg_proto_rawDescData = file_msg_proto_rawDesc
|
||||
)
|
||||
|
||||
func file_msg_proto_rawDescGZIP() []byte {
|
||||
file_msg_proto_rawDescOnce.Do(func() {
|
||||
file_msg_proto_rawDescData = protoimpl.X.CompressGZIP(file_msg_proto_rawDescData)
|
||||
})
|
||||
return file_msg_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_msg_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
|
||||
var file_msg_proto_goTypes = []interface{}{
|
||||
(*SubMessage1)(nil), // 0: app.protobuf.SubMessage1
|
||||
(*SubMessage2)(nil), // 1: app.protobuf.SubMessage2
|
||||
(*MessageBytesExtra)(nil), // 2: app.protobuf.MessageBytesExtra
|
||||
}
|
||||
var file_msg_proto_depIdxs = []int32{
|
||||
0, // 0: app.protobuf.MessageBytesExtra.message1:type_name -> app.protobuf.SubMessage1
|
||||
1, // 1: app.protobuf.MessageBytesExtra.message2:type_name -> app.protobuf.SubMessage2
|
||||
2, // [2:2] is the sub-list for method output_type
|
||||
2, // [2:2] is the sub-list for method input_type
|
||||
2, // [2:2] is the sub-list for extension type_name
|
||||
2, // [2:2] is the sub-list for extension extendee
|
||||
0, // [0:2] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_msg_proto_init() }
|
||||
func file_msg_proto_init() {
|
||||
if File_msg_proto != nil {
|
||||
return
|
||||
}
|
||||
if !protoimpl.UnsafeEnabled {
|
||||
file_msg_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*SubMessage1); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_msg_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*SubMessage2); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
file_msg_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*MessageBytesExtra); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: file_msg_proto_rawDesc,
|
||||
NumEnums: 0,
|
||||
NumMessages: 3,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
GoTypes: file_msg_proto_goTypes,
|
||||
DependencyIndexes: file_msg_proto_depIdxs,
|
||||
MessageInfos: file_msg_proto_msgTypes,
|
||||
}.Build()
|
||||
File_msg_proto = out.File
|
||||
file_msg_proto_rawDesc = nil
|
||||
file_msg_proto_goTypes = nil
|
||||
file_msg_proto_depIdxs = nil
|
||||
}
|
||||
@@ -0,0 +1,653 @@
|
||||
package wechat
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"database/sql"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"unsafe"
|
||||
"wechatDataBackup/pkg/lame"
|
||||
"wechatDataBackup/pkg/silk"
|
||||
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
"github.com/shirou/gopsutil/v3/process"
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
type WeChatInfo struct {
|
||||
ProcessID uint32
|
||||
FilePath string
|
||||
AcountName string
|
||||
Version string
|
||||
Is64Bits bool
|
||||
DllBaseAddr uintptr
|
||||
DllBaseSize uint32
|
||||
DBKey string
|
||||
}
|
||||
|
||||
type wechatMediaMSG struct {
|
||||
Key string
|
||||
MsgSvrID int
|
||||
Buf []byte
|
||||
}
|
||||
|
||||
func GetWeChatAllInfo() (WeChatInfo, error) {
|
||||
info, err := GetWeChatInfo()
|
||||
if err != nil {
|
||||
log.Println("GetWeChatInfo:", err)
|
||||
return info, err
|
||||
}
|
||||
|
||||
info.DBKey = GetWeChatKey(&info)
|
||||
|
||||
return info, nil
|
||||
}
|
||||
|
||||
func ExportWeChatAllData(info WeChatInfo, expPath string, progress chan<- string) {
|
||||
defer close(progress)
|
||||
fileInfo, err := os.Stat(info.FilePath)
|
||||
if err != nil || !fileInfo.IsDir() {
|
||||
progress <- fmt.Sprintf("{\"status\":\"error\", \"result\":\"%s error\"}", info.FilePath)
|
||||
return
|
||||
}
|
||||
if !exportWeChatDateBase(info, expPath, progress) {
|
||||
return
|
||||
}
|
||||
|
||||
exportWeChatBat(info, expPath, progress)
|
||||
exportWeChatVideoAndFile(info, expPath, progress)
|
||||
exportWeChatVoice(info, expPath, progress)
|
||||
}
|
||||
|
||||
func exportWeChatVoice(info WeChatInfo, expPath string, progress chan<- string) {
|
||||
progress <- "{\"status\":\"processing\", \"result\":\"export WeChat voice start\", \"progress\": 61}"
|
||||
|
||||
voicePath := fmt.Sprintf("%s\\FileStorage\\Voice", expPath)
|
||||
if _, err := os.Stat(voicePath); err != nil {
|
||||
if err := os.MkdirAll(voicePath, 0644); err != nil {
|
||||
log.Printf("MkdirAll %s failed: %v\n", voicePath, err)
|
||||
progress <- fmt.Sprintf("{\"status\":\"error\", \"result\":\"%v error\"}", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
index := -1
|
||||
MSGChan := make(chan wechatMediaMSG, 100)
|
||||
go func() {
|
||||
for {
|
||||
index += 1
|
||||
mediaMSGDB := fmt.Sprintf("%s\\Msg\\Multi\\MediaMSG%d.db", expPath, index)
|
||||
_, err := os.Stat(mediaMSGDB)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
db, err := sql.Open("sqlite3", mediaMSGDB)
|
||||
if err != nil {
|
||||
log.Printf("open %s failed: %v\n", mediaMSGDB, err)
|
||||
continue
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
rows, err := db.Query("select Key, Reserved0, Buf from Media;")
|
||||
if err != nil {
|
||||
log.Printf("Query failed: %v\n", err)
|
||||
continue
|
||||
}
|
||||
|
||||
msg := wechatMediaMSG{}
|
||||
for rows.Next() {
|
||||
err := rows.Scan(&msg.Key, &msg.MsgSvrID, &msg.Buf)
|
||||
if err != nil {
|
||||
log.Println("Scan failed: ", err)
|
||||
break
|
||||
}
|
||||
|
||||
MSGChan <- msg
|
||||
}
|
||||
}
|
||||
close(MSGChan)
|
||||
}()
|
||||
|
||||
for i := 0; i < 20; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for msg := range MSGChan {
|
||||
mp3Path := fmt.Sprintf("%s\\%d.mp3", voicePath, msg.MsgSvrID)
|
||||
_, err := os.Stat(mp3Path)
|
||||
if err == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
err = silkToMp3(msg.Buf[:], mp3Path)
|
||||
if err != nil {
|
||||
log.Printf("silkToMp3 %s failed: %v\n", mp3Path, err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
progress <- "{\"status\":\"processing\", \"result\":\"export WeChat voice end\", \"progress\": 100}"
|
||||
}
|
||||
|
||||
func exportWeChatVideoAndFile(info WeChatInfo, expPath string, progress chan<- string) {
|
||||
progress <- "{\"status\":\"processing\", \"result\":\"export WeChat Video and File start\", , \"progress\": 41}"
|
||||
videoRootPath := info.FilePath + "\\FileStorage\\Video"
|
||||
fileRootPath := info.FilePath + "\\FileStorage\\File"
|
||||
cacheRootPath := info.FilePath + "\\FileStorage\\Cache"
|
||||
rootPaths := []string{videoRootPath, fileRootPath, cacheRootPath}
|
||||
var wg sync.WaitGroup
|
||||
taskChan := make(chan [2]string, 100)
|
||||
go func() {
|
||||
for _, rootPath := range rootPaths {
|
||||
log.Println(rootPath)
|
||||
err := filepath.Walk(rootPath, func(path string, finfo os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
log.Printf("filepath.Walk:%v\n", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if !finfo.IsDir() {
|
||||
expFile := expPath + path[len(info.FilePath):]
|
||||
_, err := os.Stat(filepath.Dir(expFile))
|
||||
if err != nil {
|
||||
os.MkdirAll(filepath.Dir(expFile), 0644)
|
||||
}
|
||||
|
||||
_, err = os.Stat(expFile)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
task := [2]string{path, expFile}
|
||||
taskChan <- task
|
||||
return nil
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
log.Println("filepath.Walk:", err)
|
||||
progress <- fmt.Sprintf("{\"status\":\"error\", \"result\":\"%v\"}", err)
|
||||
}
|
||||
}
|
||||
close(taskChan)
|
||||
}()
|
||||
|
||||
for i := 1; i < 30; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for task := range taskChan {
|
||||
_, err := copyFile(task[0], task[1])
|
||||
if err != nil {
|
||||
log.Println("DecryptDat:", err)
|
||||
progress <- fmt.Sprintf("{\"status\":\"error\", \"result\":\"copyFile %v\"}", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
progress <- "{\"status\":\"processing\", \"result\":\"export WeChat Video and File end\", \"progress\": 60}"
|
||||
}
|
||||
|
||||
func exportWeChatBat(info WeChatInfo, expPath string, progress chan<- string) {
|
||||
progress <- "{\"status\":\"processing\", \"result\":\"export WeChat Dat start\", \"progress\": 21}"
|
||||
datRootPath := info.FilePath + "\\FileStorage\\MsgAttach"
|
||||
fileInfo, err := os.Stat(datRootPath)
|
||||
if err != nil || !fileInfo.IsDir() {
|
||||
progress <- fmt.Sprintf("{\"status\":\"error\", \"result\":\"%s error\"}", datRootPath)
|
||||
return
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
taskChan := make(chan [2]string, 100)
|
||||
go func() {
|
||||
err = filepath.Walk(datRootPath, func(path string, finfo os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
log.Printf("filepath.Walk:%v\n", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if !finfo.IsDir() && strings.HasSuffix(path, ".dat") {
|
||||
expFile := expPath + path[len(info.FilePath):]
|
||||
_, err := os.Stat(filepath.Dir(expFile))
|
||||
if err != nil {
|
||||
os.MkdirAll(filepath.Dir(expFile), 0644)
|
||||
}
|
||||
|
||||
_, err = os.Stat(expFile)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
task := [2]string{path, expFile}
|
||||
taskChan <- task
|
||||
return nil
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Println("filepath.Walk:", err)
|
||||
progress <- fmt.Sprintf("{\"status\":\"error\", \"result\":\"%v\"}", err)
|
||||
}
|
||||
close(taskChan)
|
||||
}()
|
||||
|
||||
for i := 1; i < 30; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for task := range taskChan {
|
||||
err = DecryptDat(task[0], task[1])
|
||||
if err != nil {
|
||||
log.Println("DecryptDat:", err)
|
||||
progress <- fmt.Sprintf("{\"status\":\"error\", \"result\":\"DecryptDat %v\"}", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
progress <- "{\"status\":\"processing\", \"result\":\"export WeChat Dat end\", \"progress\": 40}"
|
||||
}
|
||||
|
||||
func exportWeChatDateBase(info WeChatInfo, expPath string, progress chan<- string) bool {
|
||||
|
||||
progress <- "{\"status\":\"processing\", \"result\":\"export WeChat DateBase start\", \"progress\": 1}"
|
||||
|
||||
dbKey, err := hex.DecodeString(info.DBKey)
|
||||
if err != nil {
|
||||
log.Println("DecodeString:", err)
|
||||
progress <- fmt.Sprintf("{\"status\":\"error\", \"result\":\"%v\"}", err)
|
||||
return false
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
taskChan := make(chan [2]string, 20)
|
||||
go func() {
|
||||
err = filepath.Walk(info.FilePath+"\\Msg", func(path string, finfo os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
log.Printf("filepath.Walk:%v\n", err)
|
||||
return err
|
||||
}
|
||||
if !finfo.IsDir() && strings.HasSuffix(path, ".db") {
|
||||
expFile := expPath + path[len(info.FilePath):]
|
||||
_, err := os.Stat(filepath.Dir(expFile))
|
||||
if err != nil {
|
||||
os.MkdirAll(filepath.Dir(expFile), 0644)
|
||||
}
|
||||
|
||||
task := [2]string{path, expFile}
|
||||
taskChan <- task
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
log.Println("filepath.Walk:", err)
|
||||
progress <- fmt.Sprintf("{\"status\":\"error\", \"result\":\"%v\"}", err)
|
||||
}
|
||||
close(taskChan)
|
||||
}()
|
||||
|
||||
for i := 1; i < 20; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for task := range taskChan {
|
||||
if filepath.Base(task[0]) == "xInfo.db" {
|
||||
copyFile(task[0], task[1])
|
||||
} else {
|
||||
err = DecryptDataBase(task[0], dbKey, task[1])
|
||||
if err != nil {
|
||||
log.Println("DecryptDataBase:", err)
|
||||
progress <- fmt.Sprintf("{\"status\":\"error\", \"result\":\"%s %v\"}", task[0], err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
progress <- "{\"status\":\"processing\", \"result\":\"export WeChat DateBase end\", \"progress\": 20}"
|
||||
return true
|
||||
}
|
||||
|
||||
func GetWeChatInfo() (info WeChatInfo, rerr error) {
|
||||
info = WeChatInfo{}
|
||||
processes, err := process.Processes()
|
||||
if err != nil {
|
||||
log.Println("Error getting processes:", err)
|
||||
rerr = err
|
||||
return
|
||||
}
|
||||
|
||||
found := false
|
||||
for _, p := range processes {
|
||||
name, err := p.Name()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if name == "WeChat.exe" {
|
||||
found = true
|
||||
info.ProcessID = uint32(p.Pid)
|
||||
info.Is64Bits, _ = Is64BitProcess(info.ProcessID)
|
||||
log.Println("ProcessID", info.ProcessID)
|
||||
files, err := p.OpenFiles()
|
||||
if err != nil {
|
||||
log.Println("OpenFiles failed")
|
||||
return
|
||||
}
|
||||
|
||||
for _, f := range files {
|
||||
if strings.HasSuffix(f.Path, "\\Media.db") {
|
||||
// fmt.Printf("opened %s\n", f.Path[4:])
|
||||
filePath := f.Path[4:]
|
||||
parts := strings.Split(filePath, string(filepath.Separator))
|
||||
if len(parts) < 4 {
|
||||
return info, errors.New("Error filePath " + filePath)
|
||||
}
|
||||
info.FilePath = strings.Join(parts[:len(parts)-2], string(filepath.Separator))
|
||||
info.AcountName = strings.Join(parts[len(parts)-3:len(parts)-2], string(filepath.Separator))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if len(info.FilePath) == 0 {
|
||||
rerr = errors.New("wechat not log in")
|
||||
return
|
||||
}
|
||||
|
||||
hModuleSnap, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPMODULE|windows.TH32CS_SNAPMODULE32, uint32(p.Pid))
|
||||
if err != nil {
|
||||
log.Println("CreateToolhelp32Snapshot failed", err)
|
||||
return
|
||||
}
|
||||
defer windows.CloseHandle(hModuleSnap)
|
||||
|
||||
var me32 windows.ModuleEntry32
|
||||
me32.Size = uint32(windows.SizeofModuleEntry32)
|
||||
|
||||
err = windows.Module32First(hModuleSnap, &me32)
|
||||
if err != nil {
|
||||
log.Println("Module32First failed", err)
|
||||
return
|
||||
}
|
||||
|
||||
for ; err == nil; err = windows.Module32Next(hModuleSnap, &me32) {
|
||||
if windows.UTF16ToString(me32.Module[:]) == "WeChatWin.dll" {
|
||||
// fmt.Printf("MODULE NAME: %s\n", windows.UTF16ToString(me32.Module[:]))
|
||||
// fmt.Printf("executable NAME: %s\n", windows.UTF16ToString(me32.ExePath[:]))
|
||||
// fmt.Printf("base address: 0x%08X\n", me32.ModBaseAddr)
|
||||
// fmt.Printf("base ModBaseSize: %d\n", me32.ModBaseSize)
|
||||
info.DllBaseAddr = me32.ModBaseAddr
|
||||
info.DllBaseSize = me32.ModBaseSize
|
||||
|
||||
var zero windows.Handle
|
||||
driverPath := windows.UTF16ToString(me32.ExePath[:])
|
||||
infoSize, err := windows.GetFileVersionInfoSize(driverPath, &zero)
|
||||
if err != nil {
|
||||
log.Println("GetFileVersionInfoSize failed", err)
|
||||
return
|
||||
}
|
||||
versionInfo := make([]byte, infoSize)
|
||||
if err = windows.GetFileVersionInfo(driverPath, 0, infoSize, unsafe.Pointer(&versionInfo[0])); err != nil {
|
||||
log.Println("GetFileVersionInfo failed", err)
|
||||
return
|
||||
}
|
||||
var fixedInfo *windows.VS_FIXEDFILEINFO
|
||||
fixedInfoLen := uint32(unsafe.Sizeof(*fixedInfo))
|
||||
err = windows.VerQueryValue(unsafe.Pointer(&versionInfo[0]), `\`, (unsafe.Pointer)(&fixedInfo), &fixedInfoLen)
|
||||
if err != nil {
|
||||
log.Println("VerQueryValue failed", err)
|
||||
return
|
||||
}
|
||||
// fmt.Printf("%s: v%d.%d.%d.%d\n", windows.UTF16ToString(me32.Module[:]),
|
||||
// (fixedInfo.FileVersionMS>>16)&0xff,
|
||||
// (fixedInfo.FileVersionMS>>0)&0xff,
|
||||
// (fixedInfo.FileVersionLS>>16)&0xff,
|
||||
// (fixedInfo.FileVersionLS>>0)&0xff)
|
||||
|
||||
info.Version = fmt.Sprintf("%d.%d.%d.%d",
|
||||
(fixedInfo.FileVersionMS>>16)&0xff,
|
||||
(fixedInfo.FileVersionMS>>0)&0xff,
|
||||
(fixedInfo.FileVersionLS>>16)&0xff,
|
||||
(fixedInfo.FileVersionLS>>0)&0xff)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
rerr = errors.New("not found process")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func Is64BitProcess(pid uint32) (bool, error) {
|
||||
is64Bit := false
|
||||
handle, err := windows.OpenProcess(windows.PROCESS_QUERY_INFORMATION, false, pid)
|
||||
if err != nil {
|
||||
log.Println("Error opening process:", err)
|
||||
return is64Bit, errors.New("OpenProcess failed")
|
||||
}
|
||||
defer windows.CloseHandle(handle)
|
||||
|
||||
err = windows.IsWow64Process(handle, &is64Bit)
|
||||
if err != nil {
|
||||
log.Println("Error IsWow64Process:", err)
|
||||
}
|
||||
return !is64Bit, err
|
||||
}
|
||||
|
||||
func GetWeChatKey(info *WeChatInfo) string {
|
||||
handle, err := windows.OpenProcess(windows.PROCESS_QUERY_INFORMATION|windows.PROCESS_VM_READ, false, uint32(info.ProcessID))
|
||||
if err != nil {
|
||||
log.Println("Error opening process:", err)
|
||||
return ""
|
||||
}
|
||||
defer windows.CloseHandle(handle)
|
||||
|
||||
buffer := make([]byte, info.DllBaseSize)
|
||||
err = windows.ReadProcessMemory(handle, uintptr(info.DllBaseAddr), &buffer[0], uintptr(len(buffer)), nil)
|
||||
if err != nil {
|
||||
log.Println("Error ReadProcessMemory:", err)
|
||||
return ""
|
||||
}
|
||||
|
||||
offset := 0
|
||||
// searchStr := []byte(info.AcountName)
|
||||
for {
|
||||
index := hasDeviceSybmol(buffer[offset:])
|
||||
if index == -1 {
|
||||
fmt.Println("hasDeviceSybmolxxxx")
|
||||
break
|
||||
}
|
||||
fmt.Printf("hasDeviceSybmol: 0x%X\n", index)
|
||||
keys := findDBKeyPtr(buffer[offset:index], info.Is64Bits)
|
||||
// fmt.Println("keys:", keys)
|
||||
|
||||
key, err := findDBkey(handle, info.FilePath+"\\Msg\\Media.db", keys)
|
||||
if err == nil {
|
||||
// fmt.Println("key:", key)
|
||||
return key
|
||||
}
|
||||
|
||||
offset += (index + 20)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func hasDeviceSybmol(buffer []byte) int {
|
||||
sybmols := [...][]byte{
|
||||
{'a', 'n', 'd', 'r', 'o', 'i', 'd', 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00},
|
||||
{'i', 'p', 'h', 'o', 'n', 'e', 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00},
|
||||
{'i', 'p', 'a', 'd', 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00},
|
||||
}
|
||||
for _, syb := range sybmols {
|
||||
if index := bytes.Index(buffer, syb); index != -1 {
|
||||
return index
|
||||
}
|
||||
}
|
||||
|
||||
return -1
|
||||
}
|
||||
|
||||
func findDBKeyPtr(buffer []byte, is64Bits bool) [][]byte {
|
||||
keys := make([][]byte, 0)
|
||||
step := 8
|
||||
keyLen := []byte{0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
|
||||
if !is64Bits {
|
||||
keyLen = keyLen[:4]
|
||||
step = 4
|
||||
}
|
||||
|
||||
offset := len(buffer) - step
|
||||
for {
|
||||
if bytes.Contains(buffer[offset:offset+step], keyLen) {
|
||||
keys = append(keys, buffer[offset-step:offset])
|
||||
}
|
||||
|
||||
offset -= step
|
||||
if offset <= 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
func findDBkey(handle windows.Handle, path string, keys [][]byte) (string, error) {
|
||||
var keyAddrPtr uint64
|
||||
addrBuffer := make([]byte, 0x08)
|
||||
for _, key := range keys {
|
||||
copy(addrBuffer, key)
|
||||
err := binary.Read(bytes.NewReader(addrBuffer), binary.LittleEndian, &keyAddrPtr)
|
||||
if err != nil {
|
||||
log.Println("binary.Read:", err)
|
||||
continue
|
||||
}
|
||||
if keyAddrPtr == 0x00 {
|
||||
continue
|
||||
}
|
||||
log.Println("keyAddrPtr: 0x%X\n", keyAddrPtr)
|
||||
keyBuffer := make([]byte, 0x20)
|
||||
err = windows.ReadProcessMemory(handle, uintptr(keyAddrPtr), &keyBuffer[0], uintptr(len(keyBuffer)), nil)
|
||||
if err != nil {
|
||||
// fmt.Println("Error ReadProcessMemory:", err)
|
||||
continue
|
||||
}
|
||||
if checkDataBaseKey(path, keyBuffer) {
|
||||
return hex.EncodeToString(keyBuffer), nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", errors.New("not found key")
|
||||
}
|
||||
|
||||
func checkDataBaseKey(path string, password []byte) bool {
|
||||
fp, err := os.Open(path)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer fp.Close()
|
||||
|
||||
fpReader := bufio.NewReaderSize(fp, defaultPageSize*100)
|
||||
|
||||
buffer := make([]byte, defaultPageSize)
|
||||
|
||||
n, err := fpReader.Read(buffer)
|
||||
if err != nil && n != defaultPageSize {
|
||||
log.Println("read failed:", err, n)
|
||||
return false
|
||||
}
|
||||
|
||||
salt := buffer[:16]
|
||||
key := pbkdf2HMAC(password, salt, defaultIter, keySize)
|
||||
|
||||
page1 := buffer[16:defaultPageSize]
|
||||
|
||||
macSalt := xorBytes(salt, 0x3a)
|
||||
macKey := pbkdf2HMAC(key, macSalt, 2, keySize)
|
||||
|
||||
hashMac := hmac.New(sha1.New, macKey)
|
||||
hashMac.Write(page1[:len(page1)-32])
|
||||
hashMac.Write([]byte{1, 0, 0, 0})
|
||||
|
||||
return hmac.Equal(hashMac.Sum(nil), page1[len(page1)-32:len(page1)-12])
|
||||
}
|
||||
|
||||
func (info WeChatInfo) String() string {
|
||||
return fmt.Sprintf("PID: %d\nVersion: v%s\nBaseAddr: 0x%08X\nDllSize: %d\nIs 64Bits: %v\nFilePath %s\nAcountName: %s",
|
||||
info.ProcessID, info.Version, info.DllBaseAddr, info.DllBaseSize, info.Is64Bits, info.FilePath, info.AcountName)
|
||||
}
|
||||
|
||||
func copyFile(src, dst string) (int64, error) {
|
||||
sourceFile, err := os.Open(src)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer sourceFile.Close()
|
||||
|
||||
destFile, err := os.Create(dst)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer destFile.Close()
|
||||
|
||||
bytesWritten, err := io.Copy(destFile, sourceFile)
|
||||
if err != nil {
|
||||
return bytesWritten, err
|
||||
}
|
||||
|
||||
return bytesWritten, nil
|
||||
}
|
||||
|
||||
func silkToMp3(amrBuf []byte, mp3Path string) error {
|
||||
amrReader := bytes.NewReader(amrBuf)
|
||||
|
||||
var pcmBuffer bytes.Buffer
|
||||
sr := silk.NewWriter(&pcmBuffer)
|
||||
sr.Decoder.SetSampleRate(24000)
|
||||
amrReader.WriteTo(sr)
|
||||
sr.Close()
|
||||
|
||||
if pcmBuffer.Len() == 0 {
|
||||
return errors.New("silk to mp3 failed " + mp3Path)
|
||||
}
|
||||
|
||||
of, err := os.Create(mp3Path)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
defer of.Close()
|
||||
|
||||
wr := lame.NewWriter(of)
|
||||
wr.Encoder.SetInSamplerate(24000)
|
||||
wr.Encoder.SetNumChannels(1)
|
||||
wr.Encoder.SetBitrate(16)
|
||||
wr.Encoder.SetQuality(7)
|
||||
// IMPORTANT!
|
||||
wr.Encoder.InitParams()
|
||||
|
||||
pcmBuffer.WriteTo(wr)
|
||||
wr.Close()
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package wechat
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
const (
|
||||
keySize = 32
|
||||
defaultIter = 64000
|
||||
defaultPageSize = 4096
|
||||
)
|
||||
|
||||
func DecryptDataBase(path string, password []byte, expPath string) error {
|
||||
sqliteFileHeader := []byte("SQLite format 3")
|
||||
sqliteFileHeader = append(sqliteFileHeader, byte(0))
|
||||
|
||||
fp, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer fp.Close()
|
||||
|
||||
fpReader := bufio.NewReaderSize(fp, defaultPageSize*100)
|
||||
// fpReader := bufio.NewReader(fp)
|
||||
|
||||
buffer := make([]byte, defaultPageSize)
|
||||
|
||||
n, err := fpReader.Read(buffer)
|
||||
if err != nil && n != defaultPageSize {
|
||||
return fmt.Errorf("read failed")
|
||||
}
|
||||
|
||||
salt := buffer[:16]
|
||||
key := pbkdf2HMAC(password, salt, defaultIter, keySize)
|
||||
|
||||
page1 := buffer[16:defaultPageSize]
|
||||
|
||||
macSalt := xorBytes(salt, 0x3a)
|
||||
macKey := pbkdf2HMAC(key, macSalt, 2, keySize)
|
||||
|
||||
hashMac := hmac.New(sha1.New, macKey)
|
||||
hashMac.Write(page1[:len(page1)-32])
|
||||
hashMac.Write([]byte{1, 0, 0, 0})
|
||||
|
||||
if !hmac.Equal(hashMac.Sum(nil), page1[len(page1)-32:len(page1)-12]) {
|
||||
return fmt.Errorf("incorrect password")
|
||||
}
|
||||
|
||||
outFilePath := expPath
|
||||
outFile, err := os.Create(outFilePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer outFile.Close()
|
||||
|
||||
// Write SQLite file header
|
||||
_, err = outFile.Write(sqliteFileHeader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
page1 = buffer[16:defaultPageSize]
|
||||
iv := page1[len(page1)-48 : len(page1)-32]
|
||||
stream := cipher.NewCBCDecrypter(block, iv)
|
||||
decrypted := make([]byte, len(page1)-48)
|
||||
stream.CryptBlocks(decrypted, page1[:len(page1)-48])
|
||||
_, err = outFile.Write(decrypted)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = outFile.Write(page1[len(page1)-48:])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for {
|
||||
n, err = fpReader.Read(buffer)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
return err
|
||||
} else if n < defaultPageSize {
|
||||
return fmt.Errorf("read data to short %d", n)
|
||||
}
|
||||
|
||||
iv := buffer[len(buffer)-48 : len(buffer)-32]
|
||||
stream := cipher.NewCBCDecrypter(block, iv)
|
||||
decrypted := make([]byte, len(buffer)-48)
|
||||
stream.CryptBlocks(decrypted, buffer[:len(buffer)-48])
|
||||
_, err = outFile.Write(decrypted)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = outFile.Write(buffer[len(buffer)-48:])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func pbkdf2HMAC(password, salt []byte, iter, keyLen int) []byte {
|
||||
dk := make([]byte, keyLen)
|
||||
loop := (keyLen + sha1.Size - 1) / sha1.Size
|
||||
key := make([]byte, 0, len(salt)+4)
|
||||
u := make([]byte, sha1.Size)
|
||||
for i := 1; i <= loop; i++ {
|
||||
key = key[:0]
|
||||
key = append(key, salt...)
|
||||
key = append(key, byte(i>>24), byte(i>>16), byte(i>>8), byte(i))
|
||||
hmac := hmac.New(sha1.New, password)
|
||||
hmac.Write(key)
|
||||
digest := hmac.Sum(nil)
|
||||
copy(u, digest)
|
||||
for j := 2; j <= iter; j++ {
|
||||
hmac.Reset()
|
||||
hmac.Write(digest)
|
||||
digest = hmac.Sum(digest[:0])
|
||||
for k, di := range digest {
|
||||
u[k] ^= di
|
||||
}
|
||||
}
|
||||
copy(dk[(i-1)*sha1.Size:], u)
|
||||
}
|
||||
return dk
|
||||
}
|
||||
|
||||
func xorBytes(a []byte, b byte) []byte {
|
||||
result := make([]byte, len(a))
|
||||
for i := range a {
|
||||
result[i] = a[i] ^ b
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/*
|
||||
func main() {
|
||||
|
||||
str := "82b1a210335140a1bc8a57397391186494abe666595b4f408095538b5518f7d5"
|
||||
// 将十六进制字符串解码为字节
|
||||
password, err := hex.DecodeString(str)
|
||||
if err != nil {
|
||||
fmt.Println("解码出错:", err)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println(hex.EncodeToString(password))
|
||||
|
||||
err = decryptMsg("Media.db", password)
|
||||
if err != nil {
|
||||
fmt.Println("Error:", err)
|
||||
} else {
|
||||
fmt.Println("Decryption successful!")
|
||||
}
|
||||
}
|
||||
*/
|
||||
@@ -0,0 +1,878 @@
|
||||
package wechat
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
sync "sync"
|
||||
"time"
|
||||
|
||||
"github.com/beevik/etree"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
"github.com/pierrec/lz4"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
const (
|
||||
Wechat_Message_Type_Text = 1
|
||||
Wechat_Message_Type_Picture = 3
|
||||
Wechat_Message_Type_Voice = 34
|
||||
Wechat_Message_Type_Video = 43
|
||||
Wechat_Message_Type_Emoji = 47
|
||||
Wechat_Message_Type_Misc = 49
|
||||
Wechat_Message_Type_System = 10000
|
||||
)
|
||||
|
||||
const (
|
||||
Wechat_Misc_Message_TEXT = 1
|
||||
Wechat_Misc_Message_CardLink = 5
|
||||
Wechat_Misc_Message_File = 6
|
||||
Wechat_Misc_Message_CustomEmoji = 8
|
||||
Wechat_Misc_Message_ForwardMessage = 19
|
||||
Wechat_Misc_Message_Applet = 33
|
||||
Wechat_Misc_Message_Applet2 = 36
|
||||
Wechat_Misc_Message_Refer = 57
|
||||
Wechat_Misc_Message_Live = 63
|
||||
Wechat_Misc_Message_Notice = 87
|
||||
Wechat_Misc_Message_Live2 = 88
|
||||
Wechat_Misc_Message_Transfer = 2000
|
||||
Wechat_Misc_Message_RedPacket = 2003
|
||||
)
|
||||
|
||||
const (
|
||||
Wechat_System_Message_Notice = 1
|
||||
Wechat_System_Message_Tickle = 4
|
||||
Wechat_System_Message_Notice2 = 8000
|
||||
)
|
||||
|
||||
type Message_Search_Direction int
|
||||
|
||||
const (
|
||||
Message_Search_Forward Message_Search_Direction = iota
|
||||
Message_Search_Backward
|
||||
Message_Search_Both
|
||||
)
|
||||
|
||||
type WeChatUserInfo struct {
|
||||
UserName string `json:"UserName"`
|
||||
Alias string `json:"Alias"`
|
||||
ReMark string `json:"ReMark"`
|
||||
NickName string `json:"NickName"`
|
||||
SmallHeadImgUrl string `json:"SmallHeadImgUrl"`
|
||||
BigHeadImgUrl string `json:"BigHeadImgUrl"`
|
||||
}
|
||||
|
||||
type WeChatSession struct {
|
||||
UserName string `json:"UserName"`
|
||||
NickName string `json:"NickName"`
|
||||
Content string `json:"Content"`
|
||||
UserInfo WeChatUserInfo `json:"UserInfo"`
|
||||
Time uint64 `json:"Time"`
|
||||
IsGroup bool `json:IsGroup`
|
||||
}
|
||||
|
||||
type WeChatSessionList struct {
|
||||
Total int `json:"Total"`
|
||||
Rows []WeChatSession `json:"Rows"`
|
||||
}
|
||||
|
||||
type FileInfo struct {
|
||||
FileName string `json:"fileName"`
|
||||
FileSize string `json:"fileSize"`
|
||||
FilePath string `json:"filePath"`
|
||||
FileExt string `json:"fileExt"`
|
||||
}
|
||||
|
||||
type LinkInfo struct {
|
||||
Url string `json:"Url"`
|
||||
Title string `json:"Title"`
|
||||
Description string `json:"Description"`
|
||||
DisPlayName string `json:"DisPlayName"`
|
||||
}
|
||||
|
||||
type ReferInfo struct {
|
||||
Type int `json:"Type"`
|
||||
SubType int `json:"SubType"`
|
||||
Svrid int64 `json:"Svrid"`
|
||||
Displayname string `json:"Displayname"`
|
||||
Content string `json:"Content"`
|
||||
}
|
||||
|
||||
type WeChatMessage struct {
|
||||
LocalId int `json:"LocalId"`
|
||||
MsgSvrId int64 `json:"MsgSvrId"`
|
||||
Type int `json:"type"`
|
||||
SubType int `json:"SubType"`
|
||||
IsSender int `json:"IsSender"`
|
||||
CreateTime int64 `json:"createTime"`
|
||||
Talker string `json:"talker"`
|
||||
Content string `json:"content"`
|
||||
ThumbPath string `json:"ThumbPath"`
|
||||
ImagePath string `json:"ImagePath"`
|
||||
VideoPath string `json:"VideoPath"`
|
||||
FileInfo FileInfo `json:"fileInfo"`
|
||||
EmojiPath string `json:"EmojiPath"`
|
||||
VoicePath string `json:"VoicePath"`
|
||||
IsChatRoom bool `json:"isChatRoom"`
|
||||
UserInfo WeChatUserInfo `json:"userInfo"`
|
||||
LinkInfo LinkInfo `json:"LinkInfo"`
|
||||
ReferInfo ReferInfo `json:"ReferInfo"`
|
||||
compressContent []byte
|
||||
bytesExtra []byte
|
||||
}
|
||||
|
||||
type WeChatMessageList struct {
|
||||
KeyWord string `json:"KeyWord"`
|
||||
Total int `json:"Total"`
|
||||
Rows []WeChatMessage `json:"Rows"`
|
||||
}
|
||||
|
||||
type WeChatMessageDate struct {
|
||||
Date []string `json:"Date"`
|
||||
Total int `json:"Total"`
|
||||
}
|
||||
|
||||
type WeChatUserList struct {
|
||||
Users []WeChatUserInfo `json:"Users"`
|
||||
Total int `json:"Total"`
|
||||
}
|
||||
|
||||
type wechatMsgDB struct {
|
||||
path string
|
||||
db *sql.DB
|
||||
startTime int64
|
||||
endTime int64
|
||||
}
|
||||
|
||||
type WechatDataProvider struct {
|
||||
resPath string
|
||||
microMsg *sql.DB
|
||||
|
||||
msgDBs []*wechatMsgDB
|
||||
userInfoMap map[string]WeChatUserInfo
|
||||
userInfoMtx sync.Mutex
|
||||
|
||||
SelfInfo *WeChatUserInfo
|
||||
}
|
||||
|
||||
const (
|
||||
MicroMsgDB = "MicroMsg.db"
|
||||
)
|
||||
|
||||
type byTime []*wechatMsgDB
|
||||
|
||||
func (a byTime) Len() int { return len(a) }
|
||||
func (a byTime) Less(i, j int) bool { return a[i].startTime > a[j].startTime }
|
||||
func (a byTime) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
|
||||
|
||||
func CreateWechatDataProvider(resPath string) (*WechatDataProvider, error) {
|
||||
provider := &WechatDataProvider{}
|
||||
provider.resPath = resPath
|
||||
provider.msgDBs = make([]*wechatMsgDB, 0)
|
||||
log.Println(resPath)
|
||||
userName := filepath.Base(resPath)
|
||||
MicroMsgDBPath := resPath + "\\Msg\\" + MicroMsgDB
|
||||
microMsg, err := sql.Open("sqlite3", MicroMsgDBPath)
|
||||
if err != nil {
|
||||
log.Printf("open db %s error: %v", MicroMsgDBPath, err)
|
||||
return provider, err
|
||||
}
|
||||
|
||||
index := 0
|
||||
for {
|
||||
msgDBPath := fmt.Sprintf("%s\\Msg\\Multi\\MSG%d.db", provider.resPath, index)
|
||||
if _, err := os.Stat(msgDBPath); err != nil {
|
||||
log.Println("msgDBPath end", msgDBPath)
|
||||
break
|
||||
}
|
||||
|
||||
msgDB, err := wechatOpenMsgDB(msgDBPath)
|
||||
if err != nil {
|
||||
log.Printf("open db %s error: %v", msgDBPath, err)
|
||||
break
|
||||
}
|
||||
provider.msgDBs = append(provider.msgDBs, msgDB)
|
||||
log.Printf("MSG%d.db start %d - %d end\n", index, msgDB.startTime, msgDB.endTime)
|
||||
index += 1
|
||||
}
|
||||
sort.Sort(byTime(provider.msgDBs))
|
||||
for _, db := range provider.msgDBs {
|
||||
log.Printf("%s start %d - %d end\n", db.path, db.startTime, db.endTime)
|
||||
}
|
||||
provider.userInfoMap = make(map[string]WeChatUserInfo)
|
||||
provider.microMsg = microMsg
|
||||
provider.SelfInfo, err = provider.WechatGetUserInfoByName(userName)
|
||||
if err != nil {
|
||||
log.Printf("WechatGetUserInfoByName %s failed: %v", userName, err)
|
||||
return provider, err
|
||||
}
|
||||
provider.userInfoMap[userName] = *provider.SelfInfo
|
||||
log.Println("resPath:", provider.resPath)
|
||||
return provider, nil
|
||||
}
|
||||
|
||||
func (P *WechatDataProvider) WechatWechatDataProviderClose() {
|
||||
if P.microMsg != nil {
|
||||
P.microMsg.Close()
|
||||
}
|
||||
|
||||
for _, db := range P.msgDBs {
|
||||
db.db.Close()
|
||||
}
|
||||
log.Println("WechatWechatDataProviderClose")
|
||||
}
|
||||
|
||||
func (P *WechatDataProvider) WechatGetUserInfoByName(name string) (*WeChatUserInfo, error) {
|
||||
info := &WeChatUserInfo{}
|
||||
|
||||
var UserName, Alias, ReMark, NickName string
|
||||
querySql := fmt.Sprintf("select ifnull(UserName,'') as UserName, ifnull(Alias,'') as Alias, ifnull(ReMark,'') as ReMark, ifnull(NickName,'') as NickName from Contact where UserName='%s';", name)
|
||||
// log.Println(querySql)
|
||||
err := P.microMsg.QueryRow(querySql).Scan(&UserName, &Alias, &ReMark, &NickName)
|
||||
if err != nil {
|
||||
log.Println("not found User:", err)
|
||||
return info, err
|
||||
}
|
||||
|
||||
log.Printf("UserName %s, Alias %s, ReMark %s, NickName %s\n", UserName, Alias, ReMark, NickName)
|
||||
|
||||
var smallHeadImgUrl, bigHeadImgUrl string
|
||||
querySql = fmt.Sprintf("select ifnull(smallHeadImgUrl,'') as smallHeadImgUrl, ifnull(bigHeadImgUrl,'') as bigHeadImgUrl from ContactHeadImgUrl where usrName='%s';", UserName)
|
||||
// log.Println(querySql)
|
||||
err = P.microMsg.QueryRow(querySql).Scan(&smallHeadImgUrl, &bigHeadImgUrl)
|
||||
if err != nil {
|
||||
log.Println("not find headimg", err)
|
||||
}
|
||||
|
||||
info.UserName = UserName
|
||||
info.Alias = Alias
|
||||
info.ReMark = ReMark
|
||||
info.NickName = NickName
|
||||
info.SmallHeadImgUrl = smallHeadImgUrl
|
||||
info.BigHeadImgUrl = bigHeadImgUrl
|
||||
|
||||
// log.Println(info)
|
||||
return info, nil
|
||||
}
|
||||
|
||||
func (P *WechatDataProvider) WeChatGetSessionList(pageIndex int, pageSize int) (*WeChatSessionList, error) {
|
||||
List := &WeChatSessionList{}
|
||||
List.Rows = make([]WeChatSession, 0)
|
||||
|
||||
querySql := fmt.Sprintf("select ifnull(strUsrName,'') as strUsrName,ifnull(strNickName,'') as strNickName,ifnull(strContent,'') as strContent, nTime from Session order by rowid desc limit %d, %d;", pageIndex*pageSize, pageSize)
|
||||
dbRows, err := P.microMsg.Query(querySql)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return List, err
|
||||
}
|
||||
defer dbRows.Close()
|
||||
|
||||
var strUsrName, strNickName, strContent string
|
||||
var nTime uint64
|
||||
for dbRows.Next() {
|
||||
var session WeChatSession
|
||||
err = dbRows.Scan(&strUsrName, &strNickName, &strContent, &nTime)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
continue
|
||||
}
|
||||
if len(strContent) == 0 {
|
||||
log.Printf("%s cotent nil\n", strUsrName)
|
||||
continue
|
||||
}
|
||||
|
||||
session.UserName = strUsrName
|
||||
session.NickName = strNickName
|
||||
session.Content = strContent
|
||||
session.Time = nTime
|
||||
session.IsGroup = strings.HasSuffix(strUsrName, "@chatroom")
|
||||
info, err := P.WechatGetUserInfoByName(strUsrName)
|
||||
if err != nil {
|
||||
log.Printf("WechatGetUserInfoByName %s failed\n", strUsrName)
|
||||
continue
|
||||
}
|
||||
session.UserInfo = *info
|
||||
List.Rows = append(List.Rows, session)
|
||||
List.Total += 1
|
||||
}
|
||||
|
||||
return List, nil
|
||||
}
|
||||
|
||||
func (P *WechatDataProvider) WeChatGetMessageListByTime(userName string, time int64, pageSize int, direction Message_Search_Direction) (*WeChatMessageList, error) {
|
||||
|
||||
List := &WeChatMessageList{}
|
||||
List.Rows = make([]WeChatMessage, 0)
|
||||
selectTime := time
|
||||
selectpageSize := pageSize
|
||||
|
||||
if direction == Message_Search_Both {
|
||||
selectpageSize = pageSize / 2
|
||||
}
|
||||
for direction == Message_Search_Forward || direction == Message_Search_Both {
|
||||
selectList, err := P.weChatGetMessageListByTime(userName, selectTime, selectpageSize, Message_Search_Forward)
|
||||
if err != nil {
|
||||
return List, err
|
||||
}
|
||||
|
||||
if selectList.Total == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
selectTime = selectList.Rows[selectList.Total-1].CreateTime - 1
|
||||
selectpageSize -= selectList.Total
|
||||
List.Total += selectList.Total
|
||||
List.Rows = append(List.Rows, selectList.Rows...)
|
||||
if selectpageSize <= 0 {
|
||||
break
|
||||
}
|
||||
log.Printf("Forward selectTime %d, selectpageSize %d\n", selectTime, selectpageSize)
|
||||
}
|
||||
|
||||
selectTime = time
|
||||
if direction == Message_Search_Both {
|
||||
selectpageSize = pageSize / 2
|
||||
}
|
||||
for direction == Message_Search_Backward || direction == Message_Search_Both {
|
||||
selectList, err := P.weChatGetMessageListByTime(userName, selectTime, selectpageSize, Message_Search_Backward)
|
||||
if err != nil {
|
||||
return List, err
|
||||
}
|
||||
|
||||
if selectList.Total == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
selectTime = selectList.Rows[0].CreateTime + 1
|
||||
selectpageSize -= selectList.Total
|
||||
List.Total += selectList.Total
|
||||
List.Rows = append(selectList.Rows, List.Rows...)
|
||||
if selectpageSize <= 0 {
|
||||
break
|
||||
}
|
||||
log.Printf("Backward selectTime %d, selectpageSize %d\n", selectTime, selectpageSize)
|
||||
}
|
||||
|
||||
return List, nil
|
||||
}
|
||||
|
||||
func (P *WechatDataProvider) weChatGetMessageListByTime(userName string, time int64, pageSize int, direction Message_Search_Direction) (*WeChatMessageList, error) {
|
||||
List := &WeChatMessageList{}
|
||||
List.Rows = make([]WeChatMessage, 0)
|
||||
index := P.wechatFindDBIndex(userName, time, direction)
|
||||
if index == -1 {
|
||||
log.Printf("Not found %s %d data\n", userName, time)
|
||||
return List, nil
|
||||
}
|
||||
|
||||
sqlFormat := "select localId,MsgSvrID,Type,SubType,IsSender,CreateTime,ifnull(StrTalker,'') as StrTalker, ifnull(StrContent,'') as StrContent,ifnull(CompressContent,'') as CompressContent,ifnull(BytesExtra,'') as BytesExtra from MSG Where StrTalker='%s' And CreateTime<=%d order by CreateTime desc limit %d;"
|
||||
if direction == Message_Search_Backward {
|
||||
sqlFormat = "select localId,MsgSvrID,Type,SubType,IsSender,CreateTime,ifnull(StrTalker,'') as StrTalker, ifnull(StrContent,'') as StrContent,ifnull(CompressContent,'') as CompressContent,ifnull(BytesExtra,'') as BytesExtra from ( select localId, MsgSvrID, Type, SubType, IsSender, CreateTime, StrTalker, StrContent, CompressContent, BytesExtra FROM MSG Where StrTalker='%s' And CreateTime>%d order by CreateTime asc limit %d) AS SubQuery order by CreateTime desc;"
|
||||
}
|
||||
querySql := fmt.Sprintf(sqlFormat, userName, time, pageSize)
|
||||
log.Println(querySql)
|
||||
|
||||
rows, err := P.msgDBs[index].db.Query(querySql)
|
||||
if err != nil {
|
||||
log.Printf("%s failed %v\n", querySql, err)
|
||||
return List, nil
|
||||
}
|
||||
defer rows.Close()
|
||||
var localId, Type, SubType, IsSender int
|
||||
var MsgSvrID, CreateTime int64
|
||||
var StrTalker, StrContent string
|
||||
var CompressContent, BytesExtra []byte
|
||||
|
||||
for rows.Next() {
|
||||
message := WeChatMessage{}
|
||||
err = rows.Scan(&localId, &MsgSvrID, &Type, &SubType, &IsSender, &CreateTime,
|
||||
&StrTalker, &StrContent, &CompressContent, &BytesExtra)
|
||||
if err != nil {
|
||||
log.Println("rows.Scan failed", err)
|
||||
return List, err
|
||||
}
|
||||
message.LocalId = localId
|
||||
message.MsgSvrId = MsgSvrID
|
||||
message.Type = Type
|
||||
message.SubType = SubType
|
||||
message.IsSender = IsSender
|
||||
message.CreateTime = CreateTime
|
||||
message.Talker = StrTalker
|
||||
message.Content = StrContent
|
||||
message.IsChatRoom = strings.HasSuffix(StrTalker, "@chatroom")
|
||||
message.compressContent = make([]byte, len(CompressContent))
|
||||
message.bytesExtra = make([]byte, len(BytesExtra))
|
||||
copy(message.compressContent, CompressContent)
|
||||
copy(message.bytesExtra, BytesExtra)
|
||||
P.wechatMessageExtraHandle(&message)
|
||||
P.wechatMessageGetUserInfo(&message)
|
||||
P.wechatMessageEmojiHandle(&message)
|
||||
P.wechatMessageCompressContentHandle(&message)
|
||||
List.Rows = append(List.Rows, message)
|
||||
List.Total += 1
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
log.Println("rows.Scan failed", err)
|
||||
return List, err
|
||||
}
|
||||
|
||||
return List, nil
|
||||
}
|
||||
|
||||
func (P *WechatDataProvider) WeChatGetMessageListByKeyWord(userName string, time int64, keyWord string, msgType string, pageSize int) (*WeChatMessageList, error) {
|
||||
List := &WeChatMessageList{}
|
||||
List.Rows = make([]WeChatMessage, 0)
|
||||
List.KeyWord = keyWord
|
||||
_time := time
|
||||
selectPagesize := pageSize
|
||||
if keyWord != "" || msgType != "" {
|
||||
selectPagesize = 600
|
||||
}
|
||||
for {
|
||||
log.Println("time:", _time, keyWord)
|
||||
rawList, err := P.weChatGetMessageListByTime(userName, _time, selectPagesize, Message_Search_Forward)
|
||||
if err != nil {
|
||||
log.Println("weChatGetMessageListByTime failed: ", err)
|
||||
return nil, err
|
||||
}
|
||||
log.Println("rawList.Total:", rawList.Total)
|
||||
if rawList.Total == 0 {
|
||||
if List.Total == 0 {
|
||||
log.Printf("user %s not find [%s]\n", userName, keyWord)
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
for i, _ := range rawList.Rows {
|
||||
if weChatMessageTypeFilter(&rawList.Rows[i], msgType) && (len(keyWord) == 0 || weChatMessageContains(&rawList.Rows[i], keyWord)) {
|
||||
List.Rows = append(List.Rows, rawList.Rows[i])
|
||||
List.Total += 1
|
||||
if List.Total >= pageSize {
|
||||
return List, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_time = rawList.Rows[rawList.Total-1].CreateTime - 1
|
||||
}
|
||||
|
||||
return List, nil
|
||||
}
|
||||
|
||||
func (P *WechatDataProvider) WeChatGetMessageDate(userName string) (*WeChatMessageDate, error) {
|
||||
messageData := &WeChatMessageDate{}
|
||||
messageData.Date = make([]string, 0)
|
||||
messageData.Total = 0
|
||||
|
||||
_time := time.Now().Unix()
|
||||
|
||||
for {
|
||||
index := P.wechatFindDBIndex(userName, _time, Message_Search_Forward)
|
||||
if index == -1 {
|
||||
log.Println("wechat find db end")
|
||||
return messageData, nil
|
||||
}
|
||||
|
||||
sqlFormat := " SELECT DISTINCT strftime('%%Y-%%m-%%d', datetime(CreateTime+28800, 'unixepoch')) FROM MSG WHERE StrTalker='%s' order by CreateTime desc;"
|
||||
querySql := fmt.Sprintf(sqlFormat, userName)
|
||||
|
||||
rows, err := P.msgDBs[index].db.Query(querySql)
|
||||
if err != nil {
|
||||
log.Printf("%s failed %v\n", querySql, err)
|
||||
return messageData, nil
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var date string
|
||||
for rows.Next() {
|
||||
err = rows.Scan(&date)
|
||||
if err != nil {
|
||||
log.Println("rows.Scan failed", err)
|
||||
return messageData, err
|
||||
}
|
||||
|
||||
messageData.Date = append(messageData.Date, date)
|
||||
messageData.Total += 1
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
log.Println("rows.Scan failed", err)
|
||||
return messageData, err
|
||||
}
|
||||
|
||||
_time = P.wechatGetLastMessageCreateTime(userName, index)
|
||||
if -1 == _time {
|
||||
log.Println("wechatGetLastMessageCreateTime failed")
|
||||
return messageData, errors.New("wechatGetLastMessageCreateTime failed")
|
||||
}
|
||||
|
||||
_time -= 1
|
||||
}
|
||||
}
|
||||
|
||||
func (P *WechatDataProvider) WeChatGetChatRoomUserList(chatroom string) (*WeChatUserList, error) {
|
||||
userList := &WeChatUserList{}
|
||||
userList.Users = make([]WeChatUserInfo, 0)
|
||||
userList.Total = 0
|
||||
|
||||
sqlFormat := "select UserNameList from ChatRoom where ChatRoomName='%s';"
|
||||
querySql := fmt.Sprintf(sqlFormat, chatroom)
|
||||
|
||||
var userNameListStr string
|
||||
err := P.microMsg.QueryRow(querySql).Scan(&userNameListStr)
|
||||
if err != nil {
|
||||
log.Println("Scan: ", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
userNameArray := strings.Split(userNameListStr, "^G")
|
||||
log.Println("userNameArray:", userNameArray)
|
||||
|
||||
for _, userName := range userNameArray {
|
||||
pinfo, err := P.WechatGetUserInfoByNameOnCache(userName)
|
||||
if err == nil {
|
||||
userList.Users = append(userList.Users, *pinfo)
|
||||
userList.Total += 1
|
||||
}
|
||||
}
|
||||
|
||||
return userList, nil
|
||||
}
|
||||
|
||||
func (info WeChatUserInfo) String() string {
|
||||
return fmt.Sprintf("NickName:[%s] Alias:[%s], NickName:[%s], ReMark:[%s], SmallHeadImgUrl:[%s], BigHeadImgUrl[%s]",
|
||||
info.NickName, info.Alias, info.NickName, info.ReMark, info.SmallHeadImgUrl, info.BigHeadImgUrl)
|
||||
}
|
||||
|
||||
func (P *WechatDataProvider) wechatMessageExtraHandle(msg *WeChatMessage) {
|
||||
var extra MessageBytesExtra
|
||||
err := proto.Unmarshal(msg.bytesExtra, &extra)
|
||||
if err != nil {
|
||||
log.Println("proto.Unmarshal failed", err)
|
||||
return
|
||||
}
|
||||
|
||||
for _, ext := range extra.Message2 {
|
||||
switch ext.Field1 {
|
||||
case 1:
|
||||
if msg.IsChatRoom {
|
||||
msg.Talker = ext.Field2
|
||||
}
|
||||
case 3:
|
||||
if len(ext.Field2) > 0 && (msg.Type == Wechat_Message_Type_Picture || msg.Type == Wechat_Message_Type_Video || msg.Type == Wechat_Message_Type_Misc) {
|
||||
msg.ThumbPath = P.resPath + ext.Field2[len(P.SelfInfo.UserName):]
|
||||
}
|
||||
case 4:
|
||||
if len(ext.Field2) > 0 {
|
||||
if msg.Type == Wechat_Message_Type_Misc && msg.SubType == Wechat_Misc_Message_File {
|
||||
msg.FileInfo.FilePath = P.resPath + ext.Field2[len(P.SelfInfo.UserName):]
|
||||
msg.FileInfo.FileName = filepath.Base(ext.Field2)
|
||||
} else if msg.Type == Wechat_Message_Type_Picture || msg.Type == Wechat_Message_Type_Video || msg.Type == Wechat_Message_Type_Misc {
|
||||
msg.ImagePath = P.resPath + ext.Field2[len(P.SelfInfo.UserName):]
|
||||
msg.VideoPath = P.resPath + ext.Field2[len(P.SelfInfo.UserName):]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if msg.Type == Wechat_Message_Type_Voice {
|
||||
msg.VoicePath = fmt.Sprintf("%s\\FileStorage\\Voice\\%d.mp3", P.resPath, msg.MsgSvrId)
|
||||
}
|
||||
}
|
||||
|
||||
type EmojiMsg struct {
|
||||
XMLName xml.Name `xml:"msg"`
|
||||
Emoji Emoji `xml:"emoji"`
|
||||
}
|
||||
|
||||
type Emoji struct {
|
||||
XMLName xml.Name `xml:"emoji"`
|
||||
CdnURL string `xml:"cdnurl,attr"`
|
||||
Thumburl string `xml:"thumburl,attr"`
|
||||
Width string `xml:"width,attr"`
|
||||
Height string `xml:"height,attr"`
|
||||
}
|
||||
|
||||
func (P *WechatDataProvider) wechatMessageEmojiHandle(msg *WeChatMessage) {
|
||||
if msg.Type != Wechat_Message_Type_Emoji {
|
||||
return
|
||||
}
|
||||
|
||||
emojiMsg := EmojiMsg{}
|
||||
err := xml.Unmarshal([]byte(msg.Content), &emojiMsg)
|
||||
if err != nil {
|
||||
log.Println("xml.Unmarshal failed: ", err, msg.Content)
|
||||
return
|
||||
}
|
||||
|
||||
msg.EmojiPath = emojiMsg.Emoji.CdnURL
|
||||
}
|
||||
|
||||
type xmlDocument struct {
|
||||
*etree.Document
|
||||
}
|
||||
|
||||
func NewxmlDocument(e *etree.Document) *xmlDocument {
|
||||
return &xmlDocument{e}
|
||||
}
|
||||
|
||||
func (e *xmlDocument) FindElementValue(path string) string {
|
||||
item := e.FindElement(path)
|
||||
if item != nil {
|
||||
return item.Text()
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func (P *WechatDataProvider) wechatMessageCompressContentHandle(msg *WeChatMessage) {
|
||||
if len(msg.compressContent) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
unCompressContent := make([]byte, len(msg.compressContent)*10)
|
||||
ulen, err := lz4.UncompressBlock(msg.compressContent, unCompressContent)
|
||||
if err != nil {
|
||||
log.Println("UncompressBlock failed:", err, msg.MsgSvrId)
|
||||
return
|
||||
}
|
||||
|
||||
compMsg := etree.NewDocument()
|
||||
if err := compMsg.ReadFromBytes(unCompressContent[:ulen-1]); err != nil {
|
||||
// os.WriteFile("D:\\tmp\\"+string(msg.LocalId)+".xml", unCompressContent[:ulen], 0600)
|
||||
log.Println("ReadFromBytes failed:", err)
|
||||
return
|
||||
}
|
||||
|
||||
root := NewxmlDocument(compMsg)
|
||||
if msg.Type == Wechat_Message_Type_Misc && msg.SubType == Wechat_Misc_Message_CardLink {
|
||||
msg.LinkInfo.Title = root.FindElementValue("/msg/appmsg/title")
|
||||
msg.LinkInfo.Description = root.FindElementValue("/msg/appmsg/des")
|
||||
msg.LinkInfo.Url = root.FindElementValue("/msg/appmsg/url")
|
||||
msg.LinkInfo.DisPlayName = root.FindElementValue("/msg/appmsg/sourcedisplayname")
|
||||
appName := root.FindElementValue("/msg/appinfo/appname")
|
||||
if len(msg.LinkInfo.DisPlayName) == 0 && len(appName) > 0 {
|
||||
msg.LinkInfo.DisPlayName = appName
|
||||
}
|
||||
} else if msg.Type == Wechat_Message_Type_Misc && msg.SubType == Wechat_Misc_Message_Refer {
|
||||
msg.Content = root.FindElementValue("/msg/appmsg/title")
|
||||
msg.ReferInfo.Type, _ = strconv.Atoi(root.FindElementValue("/msg/appmsg/refermsg/type"))
|
||||
msg.ReferInfo.Svrid, _ = strconv.ParseInt(root.FindElementValue("/msg/appmsg/refermsg/svrid"), 10, 64)
|
||||
msg.ReferInfo.Displayname = root.FindElementValue("/msg/appmsg/refermsg/displayname")
|
||||
msg.ReferInfo.Content = root.FindElementValue("/msg/appmsg/refermsg/content")
|
||||
|
||||
if msg.ReferInfo.Type == Wechat_Message_Type_Misc {
|
||||
contentXML := etree.NewDocument()
|
||||
if err := contentXML.ReadFromString(msg.ReferInfo.Content); err != nil {
|
||||
log.Println("ReadFromString failed:", err)
|
||||
return
|
||||
}
|
||||
|
||||
root := NewxmlDocument(contentXML)
|
||||
msg.ReferInfo.Content = root.FindElementValue("/msg/appmsg/title")
|
||||
msg.ReferInfo.SubType, _ = strconv.Atoi(root.FindElementValue("/msg/appmsg/type"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (P *WechatDataProvider) wechatMessageGetUserInfo(msg *WeChatMessage) {
|
||||
who := msg.Talker
|
||||
if msg.IsSender == 1 {
|
||||
who = P.SelfInfo.UserName
|
||||
}
|
||||
|
||||
pinfo, err := P.WechatGetUserInfoByNameOnCache(who)
|
||||
if err != nil {
|
||||
log.Println("WechatGetUserInfoByNameOnCache:", err)
|
||||
return
|
||||
}
|
||||
|
||||
msg.UserInfo = *pinfo
|
||||
}
|
||||
|
||||
func (P *WechatDataProvider) wechatFindDBIndex(userName string, time int64, direction Message_Search_Direction) int {
|
||||
if direction == Message_Search_Forward {
|
||||
index := 0
|
||||
for {
|
||||
if index >= len(P.msgDBs) {
|
||||
return -1
|
||||
}
|
||||
msgDB := P.msgDBs[index]
|
||||
|
||||
if msgDB.startTime > time {
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
|
||||
rowId := 0
|
||||
querySql := fmt.Sprintf("select rowid from Name2ID where UsrName='%s';", userName)
|
||||
err := msgDB.db.QueryRow(querySql).Scan(&rowId)
|
||||
if err != nil {
|
||||
log.Printf("Scan: %v\n", err)
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
|
||||
querySql = fmt.Sprintf(" select rowid from MSG where StrTalker='%s' AND CreateTime<=%d limit 1;", userName, time)
|
||||
log.Printf("in %s, %s\n", msgDB.path, querySql)
|
||||
err = msgDB.db.QueryRow(querySql).Scan(&rowId)
|
||||
if err != nil {
|
||||
log.Printf("Scan: %v\n", err)
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
|
||||
log.Printf("Select in %d %s\n", index, msgDB.path)
|
||||
return index
|
||||
}
|
||||
} else {
|
||||
index := len(P.msgDBs) - 1
|
||||
for {
|
||||
if index < 0 {
|
||||
return -1
|
||||
}
|
||||
msgDB := P.msgDBs[index]
|
||||
|
||||
if msgDB.endTime < time {
|
||||
index -= 1
|
||||
continue
|
||||
}
|
||||
|
||||
rowId := 0
|
||||
querySql := fmt.Sprintf("select rowid from Name2ID where UsrName='%s';", userName)
|
||||
err := msgDB.db.QueryRow(querySql).Scan(&rowId)
|
||||
if err != nil {
|
||||
log.Printf("Scan: %v\n", err)
|
||||
index -= 1
|
||||
continue
|
||||
}
|
||||
|
||||
querySql = fmt.Sprintf(" select rowid from MSG where StrTalker='%s' AND CreateTime>%d limit 1;", userName, time)
|
||||
log.Printf("in %s, %s\n", msgDB.path, querySql)
|
||||
err = msgDB.db.QueryRow(querySql).Scan(&rowId)
|
||||
if err != nil {
|
||||
log.Printf("Scan: %v\n", err)
|
||||
index -= 1
|
||||
continue
|
||||
}
|
||||
|
||||
log.Printf("Select in %d %s\n", index, msgDB.path)
|
||||
return index
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (P *WechatDataProvider) wechatGetLastMessageCreateTime(userName string, index int) int64 {
|
||||
if index >= len(P.msgDBs) {
|
||||
return -1
|
||||
}
|
||||
sqlFormat := "SELECT CreateTime FROM MSG WHERE StrTalker='%s' order by CreateTime asc limit 1;"
|
||||
querySql := fmt.Sprintf(sqlFormat, userName)
|
||||
var lastTime int64
|
||||
err := P.msgDBs[index].db.QueryRow(querySql).Scan(&lastTime)
|
||||
if err != nil {
|
||||
log.Println("select DB lastTime failed:", index, ":", err)
|
||||
return -1
|
||||
}
|
||||
|
||||
return lastTime
|
||||
}
|
||||
|
||||
func weChatMessageContains(msg *WeChatMessage, chars string) bool {
|
||||
|
||||
switch msg.Type {
|
||||
case Wechat_Message_Type_Text:
|
||||
return strings.Contains(msg.Content, chars)
|
||||
case Wechat_Message_Type_Misc:
|
||||
switch msg.SubType {
|
||||
case Wechat_Misc_Message_CardLink:
|
||||
return strings.Contains(msg.LinkInfo.Title, chars) || strings.Contains(msg.LinkInfo.Description, chars)
|
||||
case Wechat_Misc_Message_Refer:
|
||||
return strings.Contains(msg.Content, chars)
|
||||
case Wechat_Misc_Message_File:
|
||||
return strings.Contains(msg.FileInfo.FileName, chars)
|
||||
default:
|
||||
return false
|
||||
}
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func weChatMessageTypeFilter(msg *WeChatMessage, msgType string) bool {
|
||||
switch msgType {
|
||||
case "":
|
||||
return true
|
||||
case "文件":
|
||||
return msg.Type == Wechat_Message_Type_Misc && msg.SubType == Wechat_Misc_Message_File
|
||||
case "图片与视频":
|
||||
return msg.Type == Wechat_Message_Type_Picture || msg.Type == Wechat_Message_Type_Video
|
||||
case "链接":
|
||||
return msg.Type == Wechat_Misc_Message_CardLink || msg.SubType == Wechat_Misc_Message_CardLink
|
||||
default:
|
||||
if strings.HasPrefix(msgType, "群成员") {
|
||||
userName := msgType[len("群成员"):]
|
||||
return msg.UserInfo.UserName == userName
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func wechatOpenMsgDB(path string) (*wechatMsgDB, error) {
|
||||
msgDB := wechatMsgDB{}
|
||||
|
||||
db, err := sql.Open("sqlite3", path)
|
||||
if err != nil {
|
||||
log.Printf("open db %s error: %v", path, err)
|
||||
return nil, err
|
||||
}
|
||||
msgDB.db = db
|
||||
msgDB.path = path
|
||||
querySql := "select CreateTime from MSG order by CreateTime asc limit 1;"
|
||||
err = msgDB.db.QueryRow(querySql).Scan(&msgDB.startTime)
|
||||
if err != nil {
|
||||
log.Println("select DB startTime failed:", path, ":", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
querySql = "select CreateTime from MSG order by CreateTime desc limit 1;"
|
||||
err = msgDB.db.QueryRow(querySql).Scan(&msgDB.endTime)
|
||||
if err != nil {
|
||||
log.Println("select DB endTime failed:", path, ":", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &msgDB, nil
|
||||
}
|
||||
|
||||
func (P *WechatDataProvider) WechatGetUserInfoByNameOnCache(name string) (*WeChatUserInfo, error) {
|
||||
|
||||
// log.Printf("who: %s", who)
|
||||
|
||||
P.userInfoMtx.Lock()
|
||||
defer P.userInfoMtx.Unlock()
|
||||
|
||||
info, ok := P.userInfoMap[name]
|
||||
if ok {
|
||||
return &info, nil
|
||||
}
|
||||
|
||||
pinfo, err := P.WechatGetUserInfoByName(name)
|
||||
if err != nil {
|
||||
log.Printf("WechatGetUserInfoByName %s failed: %v\n", name, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
P.userInfoMap[name] = *pinfo
|
||||
|
||||
return pinfo, nil
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package wechat
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
/*
|
||||
from: https://github.com/liuggchen/wechatDatDecode.git
|
||||
*/
|
||||
|
||||
var imagePrefixBtsMap = make(map[string][]byte)
|
||||
|
||||
func DecryptDatByDir(inDir, outDir string) error {
|
||||
|
||||
startTime := time.Now()
|
||||
f, er := os.Open(inDir)
|
||||
if er != nil {
|
||||
fmt.Println(er.Error())
|
||||
return er
|
||||
}
|
||||
readdir, er := f.Readdir(0)
|
||||
if er != nil {
|
||||
fmt.Println(er.Error())
|
||||
}
|
||||
|
||||
if stat, er := os.Stat(outDir); os.IsNotExist(er) {
|
||||
er := os.MkdirAll(outDir, 0755)
|
||||
if er != nil {
|
||||
return er
|
||||
}
|
||||
} else if !stat.IsDir() {
|
||||
return errors.New(outDir + "is file")
|
||||
}
|
||||
|
||||
var taskChan = make(chan os.FileInfo, 100)
|
||||
|
||||
go func() {
|
||||
for _, info := range readdir {
|
||||
taskChan <- info
|
||||
}
|
||||
close(taskChan)
|
||||
}()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 10; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for info := range taskChan {
|
||||
handlerOne(info, inDir, outDir)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
t := time.Since(startTime).Seconds()
|
||||
log.Printf("\nfinished time= %v s\n", t)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func DecryptDat(inFile string, outFile string) error {
|
||||
|
||||
sourceFile, err := os.Open(inFile)
|
||||
if err != nil {
|
||||
log.Println(err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
var preTenBts = make([]byte, 10)
|
||||
_, _ = sourceFile.Read(preTenBts)
|
||||
decodeByte, _, er := findDecodeByte(preTenBts)
|
||||
if er != nil {
|
||||
log.Println(er.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
distFile, er := os.Create(outFile)
|
||||
if er != nil {
|
||||
log.Println(er.Error())
|
||||
return err
|
||||
}
|
||||
writer := bufio.NewWriter(distFile)
|
||||
_, _ = sourceFile.Seek(0, 0)
|
||||
var rBts = make([]byte, 1024)
|
||||
for {
|
||||
n, er := sourceFile.Read(rBts)
|
||||
if er != nil {
|
||||
if er == io.EOF {
|
||||
break
|
||||
}
|
||||
log.Println("error: ", er.Error())
|
||||
return err
|
||||
}
|
||||
for i := 0; i < n; i++ {
|
||||
_ = writer.WriteByte(rBts[i] ^ decodeByte)
|
||||
}
|
||||
}
|
||||
_ = writer.Flush()
|
||||
_ = distFile.Close()
|
||||
_ = sourceFile.Close()
|
||||
// fmt.Println("output file:", distFile.Name())
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func handlerOne(info os.FileInfo, dir string, outputDir string) {
|
||||
if info.IsDir() || filepath.Ext(info.Name()) != ".dat" {
|
||||
return
|
||||
}
|
||||
fmt.Println("find file: ", info.Name())
|
||||
fPath := dir + "/" + info.Name()
|
||||
sourceFile, err := os.Open(fPath)
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
var preTenBts = make([]byte, 10)
|
||||
_, _ = sourceFile.Read(preTenBts)
|
||||
decodeByte, _, er := findDecodeByte(preTenBts)
|
||||
if er != nil {
|
||||
fmt.Println(er.Error())
|
||||
return
|
||||
}
|
||||
|
||||
distFile, er := os.Create(outputDir + "/" + info.Name())
|
||||
if er != nil {
|
||||
fmt.Println(er.Error())
|
||||
return
|
||||
}
|
||||
writer := bufio.NewWriter(distFile)
|
||||
_, _ = sourceFile.Seek(0, 0)
|
||||
var rBts = make([]byte, 1024)
|
||||
for {
|
||||
n, er := sourceFile.Read(rBts)
|
||||
if er != nil {
|
||||
if er == io.EOF {
|
||||
break
|
||||
}
|
||||
fmt.Println("error: ", er.Error())
|
||||
return
|
||||
}
|
||||
for i := 0; i < n; i++ {
|
||||
_ = writer.WriteByte(rBts[i] ^ decodeByte)
|
||||
}
|
||||
}
|
||||
_ = writer.Flush()
|
||||
_ = distFile.Close()
|
||||
|
||||
fmt.Println("output file:", distFile.Name())
|
||||
}
|
||||
|
||||
func init() {
|
||||
//JPEG (jpg),文件头:FFD8FF
|
||||
//PNG (png),文件头:89504E47
|
||||
//GIF (gif),文件头:47494638
|
||||
//TIFF (tif),文件头:49492A00
|
||||
//Windows Bitmap (bmp),文件头:424D
|
||||
const (
|
||||
Jpeg = "FFD8FF"
|
||||
Png = "89504E47"
|
||||
Gif = "47494638"
|
||||
Tif = "49492A00"
|
||||
Bmp = "424D"
|
||||
)
|
||||
JpegPrefixBytes, _ := hex.DecodeString(Jpeg)
|
||||
PngPrefixBytes, _ := hex.DecodeString(Png)
|
||||
GifPrefixBytes, _ := hex.DecodeString(Gif)
|
||||
TifPrefixBytes, _ := hex.DecodeString(Tif)
|
||||
BmpPrefixBytes, _ := hex.DecodeString(Bmp)
|
||||
|
||||
imagePrefixBtsMap = map[string][]byte{
|
||||
".jpeg": JpegPrefixBytes,
|
||||
".png": PngPrefixBytes,
|
||||
".gif": GifPrefixBytes,
|
||||
".tif": TifPrefixBytes,
|
||||
".bmp": BmpPrefixBytes,
|
||||
}
|
||||
}
|
||||
|
||||
func findDecodeByte(bts []byte) (byte, string, error) {
|
||||
for ext, prefixBytes := range imagePrefixBtsMap {
|
||||
deCodeByte, err := testPrefix(prefixBytes, bts)
|
||||
if err == nil {
|
||||
return deCodeByte, ext, err
|
||||
}
|
||||
}
|
||||
return 0, "", errors.New("decode fail")
|
||||
}
|
||||
|
||||
func testPrefix(prefixBytes []byte, bts []byte) (deCodeByte byte, error error) {
|
||||
var initDecodeByte = prefixBytes[0] ^ bts[0]
|
||||
for i, prefixByte := range prefixBytes {
|
||||
if b := prefixByte ^ bts[i]; b != initDecodeByte {
|
||||
return 0, errors.New("no")
|
||||
}
|
||||
}
|
||||
return initDecodeByte, nil
|
||||
}
|
||||
Reference in new issue
Block a user