提交 fa4dc1dc 编写于 作者: L LittleCoder

Update file uploading protocol

上级 35277aaf
build/* build/*
dist/* dist/*
test/*
itchat.egg-info/* itchat.egg-info/*
*.pyc *.pyc
*.swp *.swp
......
# itchat # itchat
[![Gitter][gitter-picture]][gitter] ![py27][py27] ![py35][py35] [English version][english-version] [![Gitter][gitter-picture]][gitter] ![py27][py27] ![py35][py35]
itchat是一个开源的微信个人号接口,使用python调用微信从未如此简单。 itchat是一个开源的微信个人号接口,使用python调用微信从未如此简单。
......
import os, time, re import os, time, re, io
import json, copy import json, copy
import traceback, logging import traceback, logging
......
import os, time, re, io import os, time, re, io
import json import json
import mimetypes import mimetypes, hashlib
import traceback, logging import traceback, logging
import requests import requests
...@@ -235,39 +235,59 @@ def send_msg(self, msg='Test Message', toUserName=None): ...@@ -235,39 +235,59 @@ def send_msg(self, msg='Test Message', toUserName=None):
r = self.send_raw_msg(1, msg, toUserName) r = self.send_raw_msg(1, msg, toUserName)
return r return r
def upload_file(self, fileDir, isPicture=False, isVideo=False): def upload_file(self, fileDir, isPicture=False, isVideo=False,
toUserName='filehelper'):
logger.debug('Request to upload a %s: %s' % ( logger.debug('Request to upload a %s: %s' % (
'picture' if isPicture else 'video' if isVideo else 'file', fileDir)) 'picture' if isPicture else 'video' if isVideo else 'file', fileDir))
if not utils.check_file(fileDir): if not utils.check_file(fileDir):
return ReturnValue({'BaseResponse': { return ReturnValue({'BaseResponse': {
'ErrMsg': 'No file found in specific dir', 'ErrMsg': 'No file found in specific dir',
'Ret': -1002, }}) 'Ret': -1002, }})
url = self.loginInfo.get('fileUrl', self.loginInfo['url']) + \ fileSize = os.path.getsize(fileDir)
fileSymbol = 'pic' if isPicture else 'video' if isVideo else'doc'
with open(fileDir, 'rb') as f: fileMd5 = hashlib.md5(f.read()).hexdigest()
file = open(fileDir, 'rb')
chunks = int(fileSize / 524288) + 1
for chunk in range(chunks):
r = upload_chunk_file(self, fileDir, fileSymbol, fileSize,
fileMd5, file, toUserName, chunk, chunks)
file.close()
self.loginInfo['msgid'] += 1
return ReturnValue(rawResponse=r)
def upload_chunk_file(core, fileDir, fileSymbol, fileSize,
fileMd5, file, toUserName, chunk, chunks):
url = core.loginInfo.get('fileUrl', core.loginInfo['url']) + \
'/webwxuploadmedia?f=json' '/webwxuploadmedia?f=json'
# save it on server # save it on server
fileSize = str(os.path.getsize(fileDir)) cookiesList = {name:data for name,data in core.s.cookies.items()}
cookiesList = {name:data for name,data in self.s.cookies.items()}
fileType = mimetypes.guess_type(fileDir)[0] or 'application/octet-stream' fileType = mimetypes.guess_type(fileDir)[0] or 'application/octet-stream'
files = { files = {
'id': (None, 'WU_FILE_0'), 'id': (None, 'WU_FILE_0'),
'name': (None, os.path.basename(fileDir)), 'name': (None, os.path.basename(fileDir)),
'type': (None, fileType), 'type': (None, fileType),
'lastModifiedDate': (None, time.strftime('%a %b %d %Y %H:%M:%S GMT+0800 (CST)')), 'lastModifiedDate': (None, time.strftime('%a %b %d %Y %H:%M:%S GMT+0800 (CST)')),
'size': (None, fileSize), 'size': (None, str(fileSize)),
'mediatype': (None, 'pic' if isPicture else 'video' if isVideo else'doc'), 'mediatype': (None, fileSymbol),
'uploadmediarequest': (None, json.dumps({ 'uploadmediarequest': (None, json.dumps({
'BaseRequest': self.loginInfo['BaseRequest'], 'UploadType': (None, 2),
'ClientMediaId': int(time.time()), 'BaseRequest': core.loginInfo['BaseRequest'],
'ClientMediaId': core.loginInfo['msgid'],
'TotalLen': fileSize, 'TotalLen': fileSize,
'StartPos': 0, 'StartPos': 0,
'DataLen': fileSize, 'DataLen': fileSize,
'MediaType': 4, }, separators = (',', ':'))), 'MediaType': 4,
'FromUserName': core.storageClass.userName,
'ToUserName': toUserName,
'FileMd5': fileMd5,
}, separators = (',', ':'))),
'webwx_data_ticket': (None, cookiesList['webwx_data_ticket']), 'webwx_data_ticket': (None, cookiesList['webwx_data_ticket']),
'pass_ticket': (None, 'undefined'), 'pass_ticket': (None, core.loginInfo['pass_ticket']),
'filename' : (os.path.basename(fileDir), open(fileDir, 'rb'), fileType), } 'filename' : (os.path.basename(fileDir), file.read(524288), fileType), }
if chunks != 1:
files['chunk'], files['chunks'] = (None, str(chunk)), (None, str(chunks))
headers = { 'User-Agent' : config.USER_AGENT } headers = { 'User-Agent' : config.USER_AGENT }
r = self.s.post(url, files=files, headers=headers) return core.s.post(url, files=files, headers=headers)
return ReturnValue(rawResponse=r)
def send_file(self, fileDir, toUserName=None, mediaId=None): def send_file(self, fileDir, toUserName=None, mediaId=None):
logger.debug('Request to send a file(mediaId: %s) to %s: %s' % ( logger.debug('Request to send a file(mediaId: %s) to %s: %s' % (
......
import os, platform import os, platform
VERSION = '1.2.11' VERSION = '1.2.12'
BASE_URL = 'https://login.weixin.qq.com' BASE_URL = 'https://login.weixin.qq.com'
OS = platform.system() #Windows, Linux, Darwin OS = platform.system() #Windows, Linux, Darwin
DIR = os.getcwd() DIR = os.getcwd()
......
...@@ -311,7 +311,8 @@ class Core(object): ...@@ -311,7 +311,8 @@ class Core(object):
it is defined in components/messages.py it is defined in components/messages.py
''' '''
raise NotImplementedError() raise NotImplementedError()
def upload_file(self, fileDir, isPicture=False, isVideo=False): def upload_file(self, fileDir, isPicture=False, isVideo=False,
toUserName='filehelper'):
''' upload file to server and get mediaId ''' upload file to server and get mediaId
for options for options
- fileDir: dir for file ready for upload - fileDir: dir for file ready for upload
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册