Skip to content

Commit fa4dc1d

Browse files
committed
Update file uploading protocol
1 parent 35277aa commit fa4dc1d

File tree

6 files changed

+40
-18
lines changed

6 files changed

+40
-18
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
build/*
22
dist/*
3+
test/*
34
itchat.egg-info/*
45
*.pyc
56
*.swp

docs/index.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# itchat
22

3-
[![Gitter][gitter-picture]][gitter] ![py27][py27] ![py35][py35] [English version][english-version]
3+
[![Gitter][gitter-picture]][gitter] ![py27][py27] ![py35][py35]
44

55
itchat是一个开源的微信个人号接口,使用python调用微信从未如此简单。
66

itchat/components/contact.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import os, time, re
1+
import os, time, re, io
22
import json, copy
33
import traceback, logging
44

itchat/components/messages.py

+34-14
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import os, time, re, io
22
import json
3-
import mimetypes
3+
import mimetypes, hashlib
44
import traceback, logging
55

66
import requests
@@ -235,39 +235,59 @@ def send_msg(self, msg='Test Message', toUserName=None):
235235
r = self.send_raw_msg(1, msg, toUserName)
236236
return r
237237

238-
def upload_file(self, fileDir, isPicture=False, isVideo=False):
238+
def upload_file(self, fileDir, isPicture=False, isVideo=False,
239+
toUserName='filehelper'):
239240
logger.debug('Request to upload a %s: %s' % (
240241
'picture' if isPicture else 'video' if isVideo else 'file', fileDir))
241242
if not utils.check_file(fileDir):
242243
return ReturnValue({'BaseResponse': {
243244
'ErrMsg': 'No file found in specific dir',
244245
'Ret': -1002, }})
245-
url = self.loginInfo.get('fileUrl', self.loginInfo['url']) + \
246+
fileSize = os.path.getsize(fileDir)
247+
fileSymbol = 'pic' if isPicture else 'video' if isVideo else'doc'
248+
with open(fileDir, 'rb') as f: fileMd5 = hashlib.md5(f.read()).hexdigest()
249+
file = open(fileDir, 'rb')
250+
chunks = int(fileSize / 524288) + 1
251+
for chunk in range(chunks):
252+
r = upload_chunk_file(self, fileDir, fileSymbol, fileSize,
253+
fileMd5, file, toUserName, chunk, chunks)
254+
file.close()
255+
self.loginInfo['msgid'] += 1
256+
return ReturnValue(rawResponse=r)
257+
258+
def upload_chunk_file(core, fileDir, fileSymbol, fileSize,
259+
fileMd5, file, toUserName, chunk, chunks):
260+
url = core.loginInfo.get('fileUrl', core.loginInfo['url']) + \
246261
'/webwxuploadmedia?f=json'
247262
# save it on server
248-
fileSize = str(os.path.getsize(fileDir))
249-
cookiesList = {name:data for name,data in self.s.cookies.items()}
263+
cookiesList = {name:data for name,data in core.s.cookies.items()}
250264
fileType = mimetypes.guess_type(fileDir)[0] or 'application/octet-stream'
251265
files = {
252266
'id': (None, 'WU_FILE_0'),
253267
'name': (None, os.path.basename(fileDir)),
254268
'type': (None, fileType),
255269
'lastModifiedDate': (None, time.strftime('%a %b %d %Y %H:%M:%S GMT+0800 (CST)')),
256-
'size': (None, fileSize),
257-
'mediatype': (None, 'pic' if isPicture else 'video' if isVideo else'doc'),
270+
'size': (None, str(fileSize)),
271+
'mediatype': (None, fileSymbol),
258272
'uploadmediarequest': (None, json.dumps({
259-
'BaseRequest': self.loginInfo['BaseRequest'],
260-
'ClientMediaId': int(time.time()),
273+
'UploadType': (None, 2),
274+
'BaseRequest': core.loginInfo['BaseRequest'],
275+
'ClientMediaId': core.loginInfo['msgid'],
261276
'TotalLen': fileSize,
262277
'StartPos': 0,
263278
'DataLen': fileSize,
264-
'MediaType': 4, }, separators = (',', ':'))),
279+
'MediaType': 4,
280+
'FromUserName': core.storageClass.userName,
281+
'ToUserName': toUserName,
282+
'FileMd5': fileMd5,
283+
}, separators = (',', ':'))),
265284
'webwx_data_ticket': (None, cookiesList['webwx_data_ticket']),
266-
'pass_ticket': (None, 'undefined'),
267-
'filename' : (os.path.basename(fileDir), open(fileDir, 'rb'), fileType), }
285+
'pass_ticket': (None, core.loginInfo['pass_ticket']),
286+
'filename' : (os.path.basename(fileDir), file.read(524288), fileType), }
287+
if chunks != 1:
288+
files['chunk'], files['chunks'] = (None, str(chunk)), (None, str(chunks))
268289
headers = { 'User-Agent' : config.USER_AGENT }
269-
r = self.s.post(url, files=files, headers=headers)
270-
return ReturnValue(rawResponse=r)
290+
return core.s.post(url, files=files, headers=headers)
271291

272292
def send_file(self, fileDir, toUserName=None, mediaId=None):
273293
logger.debug('Request to send a file(mediaId: %s) to %s: %s' % (

itchat/config.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import os, platform
22

3-
VERSION = '1.2.11'
3+
VERSION = '1.2.12'
44
BASE_URL = 'https://login.weixin.qq.com'
55
OS = platform.system() #Windows, Linux, Darwin
66
DIR = os.getcwd()

itchat/core.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,8 @@ def send_msg(self, msg='Test Message', toUserName=None):
311311
it is defined in components/messages.py
312312
'''
313313
raise NotImplementedError()
314-
def upload_file(self, fileDir, isPicture=False, isVideo=False):
314+
def upload_file(self, fileDir, isPicture=False, isVideo=False,
315+
toUserName='filehelper'):
315316
''' upload file to server and get mediaId
316317
for options
317318
- fileDir: dir for file ready for upload

0 commit comments

Comments
 (0)