Beispiel #1
0
	def __init__(self,jid,message_id,url,mediaType_id,mediaId,account,resize=False):
		
		WADebug.attach(self);
		path = self.getSavePath(mediaType_id);
		
		filename = url.split('/')[-1]
		
		if path is None:
			raise Exception("Unknown media type")
		
		if not os.path.exists(path):
			os.makedirs(path)
		
		
		self.uploadHandler = MediaUploader(jid, account, self.onUploadSuccess, self.onError, self.onProgressUpdated)
		self.downloadHandler = MediaDownloader(self.onDownloadSuccess, self.onError, self.onProgressUpdated)

		self.url = url
		self._path = path+"/"+filename

		ext = os.path.splitext(filename)[1]

		self.downloadPath = Utilities.getUniqueFilename(path + "/" + self.getFilenamePrefix(mediaType_id) + ext)

		self.resize = resize
		self.mediaId = mediaId
		self.message_id = message_id
		self.jid = jid

		super(WAMediaHandler,self).__init__();
Beispiel #2
0
	def onUploadRequestSuccess(self, _hash, url, removeFrom):
		self._d("Upload Request success")
		self._d("The url is %s" %url)
		self._d("The hash is %s" %_hash)
		asset = self.s.query(Asset).filter_by(asset_hash=_hash).order_by(desc(Asset.id)).first()
		asset.mms_url = url
		self.s.commit()

		path = self.getImageFile(asset)

		self._d("To upload %s" %path)
		self._d("To %s" %self.username)

		MU = MediaUploader(self.username + "@s.whatsapp.net", self.username + "@s.whatsapp.net", self.onUploadSucccess, self.onUploadError, self.onUploadProgress)
		
		self._d("Path %s" %path)
		self._d("Url %s" %url)
		
		MU.upload(path, url, asset.id)
Beispiel #3
0
    def onUploadRequestSuccess(self, _hash, url, removeFrom):
        self._d("Upload Request success")
        self._d("The url is %s" % url)
        self._d("The hash is %s" % _hash)
        asset = self.s.query(Asset).filter_by(asset_hash=_hash).order_by(
            desc(Asset.id)).first()
        asset.mms_url = url
        self.s.commit()

        path = self.getImageFile(asset)

        self._d("To upload %s" % path)
        self._d("To %s" % self.username)

        MU = MediaUploader(self.username + "@s.whatsapp.net",
                           self.username + "@s.whatsapp.net",
                           self.onUploadSucccess, self.onUploadError,
                           self.onUploadProgress)

        self._d("Path %s" % path)
        self._d("Url %s" % url)

        MU.upload(path, url, asset.id)
Beispiel #4
0
 def __init__(self, from_jid, to_jid, img_fp, wac):
     self.__log = logging.getLogger(__name__)
     self.from_jid = from_jid
     self.to_jid = to_jid
     self.img_fp = img_fp
     self.img_path = img_fp.name
     self.img_name = os.path.basename(img_fp.name)
     self.methods_interface = wac.methodInterface
     self.fp_dict = dict()
     self.message_id = None
     self.wac = wac
     
     wac.signalInterface.registerListener("media_uploadRequestSuccess", self.upload_request_success)
     wac.signalInterface.registerListener("media_uploadRequestFailed", self.upload_request_failed)
     wac.signalInterface.registerListener("media_uploadRequestDuplicate", self.upload_request_duplicate)
     wac.signalInterface.registerListener("receipt_messageSent", self.receipt_message_sent)
     
     self.mtype = "image"
     self.uploader = MediaUploader(from_jid, to_jid, self.on_upload_success, self.on_error, self.on_progress_updated)
Beispiel #5
0
 def uploadImage(self, url):
     uploader = MediaUploader(self.jid, self.username, self.onUploadSuccess,
                              self.onUploadError, self.onProgressUpdated)
     uploader.upload(self.path, url)
Beispiel #6
0
class WhatsAppImageUploader(object):
    def __init__(self, from_jid, to_jid, img_fp, wac):
        self.__log = logging.getLogger(__name__)
        self.from_jid = from_jid
        self.to_jid = to_jid
        self.img_fp = img_fp
        self.img_path = img_fp.name
        self.img_name = os.path.basename(img_fp.name)
        self.methods_interface = wac.methodInterface
        self.fp_dict = dict()
        self.message_id = None
        self.wac = wac
        
        wac.signalInterface.registerListener("media_uploadRequestSuccess", self.upload_request_success)
        wac.signalInterface.registerListener("media_uploadRequestFailed", self.upload_request_failed)
        wac.signalInterface.registerListener("media_uploadRequestDuplicate", self.upload_request_duplicate)
        wac.signalInterface.registerListener("receipt_messageSent", self.receipt_message_sent)
        
        self.mtype = "image"
        self.uploader = MediaUploader(from_jid, to_jid, self.on_upload_success, self.on_error, self.on_progress_updated)
        
    def cleanup(self):
        self.__log.error("6) Cleanup for " + self.img_path)
        self.img_fp.close()
        os.remove(self.img_path)
        self.wac.signalInterface.unregisterListener("media_uploadRequestSuccess", self.upload_request_success)
        self.wac.signalInterface.unregisterListener("media_uploadRequestFailed", self.upload_request_failed)
        self.wac.signalInterface.unregisterListener("media_uploadRequestDuplicate", self.upload_request_duplicate)
        self.wac.signalInterface.unregisterListener("receipt_messageSent", self.receipt_message_sent)
        self.lock.unlock()
        self.__log.debug("7) Lock: " + str(self.lock.locked()))
        
    def upload(self, lock):
        self.__log.debug("1) calling upload() for " + self.img_path)
        self.lock = lock
        
        sha256 = hashlib.sha256()
        fp = open(self.img_path, 'rb')

        try:
            im = Image.open(self.img_path)
            im.thumbnail((128, 128), Image.ANTIALIAS)
            output = BytesIO()
            im.convert("RGB")
            im.save(output, format='JPEG')
            output.seek(0)
            self.b64preview = base64.b64encode(output.read())
            
            sha256.update(fp.read())
            _hash = base64.b64encode(sha256.digest())
            self.size = os.path.getsize(self.img_path)
            self.methods_interface.call("media_requestUpload", (_hash, self.mtype, self.size))
            fp.close()
        except IOError:
            self.__log.error("Caught an IOError. cancelling upload...")
            self.cleanup()
        except:
            self.__log.error("Caught a generic error in file upload...")
            self.cleanup()
            
    def deliverMessage(self, url):
        self.__log.debug("4) Trying to deliver message for url:" + url)
        message_id = self.methods_interface.call("message_imageSend", (self.to_jid, url, self.img_name, str(self.size), self.b64preview))
        
        #self.img_fp.close()
        if self.message_id is not None:
            self.__log.error("4) Invalid message ID: It is already set: " + self.message_id + "; new: " + message_id)
        self.message_id = message_id
        
    def receipt_message_sent(self, jid, message_id):
        self.__log.debug("5) receipt_message_sent for message_id: " + message_id)
        
        self.__log.error("5) Closing and removing fP: " + self.img_path)
        self.cleanup()

    def upload_request_success(self, _hash, url, resume_from):
        self.__log.debug("2) Upload request succes for file:" + self.img_path)
        self.__log.debug(_hash)
        self.__log.debug(url)
        self.__log.debug(resume_from)
        self.uploader.upload(self.img_path, url)

    def upload_request_failed(self, _hash):
        self.__log.debug("2) Upload request failed:")
        self.__log.debug(_hash)

    def upload_request_duplicate(self, _hash, url):
        self.__log.debug("2) Duplicate request: ")
        self.__log.debug(_hash)
        self.__log.debug(url)
        self.deliverMessage(url)

    def on_upload_success(self, url):
        self.__log.debug("3) Successful upload: " + url + "(" + self.img_path + ")")
        self.deliverMessage(url)

    def on_error(self):
        self.__log.error("3) Failed to upload, closing file: " + self.img_fp.name)
        self.cleanup()

    def on_progress_updated(self, progress):
        pass
Beispiel #7
0
	def uploadImage(self, url):
		uploader = MediaUploader(self.jid, self.username, self.onUploadSuccess, self.onError, self.onProgressUpdated)
		uploader.upload(self.path,url)
Beispiel #8
0
class WAMediaHandler(QObject):
	progressUpdated = QtCore.Signal(int,int) #%,progress,mediaid
	error = QtCore.Signal(str,int)
	success = QtCore.Signal(str,int,str,str, str)
	
	def __init__(self,jid,message_id,url,mediaType_id,mediaId,account,resize=False):
		
		WADebug.attach(self);
		path = self.getSavePath(mediaType_id);
		
		filename = url.split('/')[-1]
		
		if path is None:
			raise Exception("Unknown media type")
		
		if not os.path.exists(path):
			os.makedirs(path)
		
		
		self.uploadHandler = MediaUploader(jid, account, self.onUploadSuccess, self.onError, self.onProgressUpdated)
		self.downloadHandler = MediaDownloader(self.onDownloadSuccess, self.onError, self.onProgressUpdated)

		self.url = url
		self._path = path+"/"+filename

		ext = os.path.splitext(filename)[1]

		self.downloadPath = Utilities.getUniqueFilename(path + "/" + self.getFilenamePrefix(mediaType_id) + ext)

		self.resize = resize
		self.mediaId = mediaId
		self.message_id = message_id
		self.jid = jid

		super(WAMediaHandler,self).__init__();
	

	def onError(self):
		self.error.emit(self.jid,self.message_id)
	
	def onUploadSuccess(self, url):

		#filename = os.path.basename(self._path)
		#filesize = os.path.getsize(self._path)
		#data = url + "," + filename + "," + str(filesize);
		self.success.emit(self.jid,self.message_id, self._path, "upload", url)

	def onDownloadSuccess(self, path):
		try:
			shutil.copyfile(path, self.downloadPath)
			os.remove(path)
			self.success.emit(self.jid, self.message_id, self.downloadPath, "download", "")
		except:
			print("Error occured at transfer %s"%sys.exc_info()[1])
			self.error.emit(self.jid, self.message_id)

	def onProgressUpdated(self,progress):
		self.progressUpdated.emit(progress, self.mediaId);

	@async
	def pull(self):
		self.action = "download"
		self.downloadHandler.download(self.url)

	@async
	def push(self, uploadUrl):
		self.action = "upload"

		path = self.url.replace("file://","")

		filename = os.path.basename(path)
		filetype = mimetypes.guess_type(filename)[0]
		
		self._path = path
		self.uploadHandler.upload(path, uploadUrl)
	
	def getFilenamePrefix(self, mediatype_id):
		if mediatype_id == WAConstants.MEDIA_TYPE_IMAGE:
			return strftime("owhatsapp_image_%Y%m%d_%H%M%S", gmtime())
		
		if mediatype_id == WAConstants.MEDIA_TYPE_AUDIO:
			return strftime("owhatsapp_audio_%Y%m%d_%H%M%S", gmtime())
		
		if mediatype_id == WAConstants.MEDIA_TYPE_VIDEO:
			return strftime("owhatsapp_video_%Y%m%d_%H%M%S", gmtime())

		if mediatype_id == WAConstants.MEDIA_TYPE_VCARD:
			return strftime("owhatsapp_vcard_%Y%m%d_%H%M%S", gmtime())
			
		return ""
	
	def getSavePath(self,mediatype_id):
		
		if mediatype_id == WAConstants.MEDIA_TYPE_IMAGE:
			return WAConstants.IMAGE_PATH
		
		if mediatype_id == WAConstants.MEDIA_TYPE_AUDIO:
			return WAConstants.AUDIO_PATH
		
		if mediatype_id == WAConstants.MEDIA_TYPE_VIDEO:
			return WAConstants.VIDEO_PATH

		if mediatype_id == WAConstants.MEDIA_TYPE_VCARD:
			return WAConstants.VCARD_PATH
			
		return None
Beispiel #9
0
def onUploadRequestSuccess(self, _hash, url, resumeFrom):
    #Die jid's vom sender und Empfänger, müsste man mal noch ordentlich wegkapseln 
    sender_jid = "*****@*****.**"
    receiver_jid = "*****@*****.**"
    MU = MediaUploader(receiver_jid,sender_jid, self.onUploadSuccess, self.onError, self.onProgressUpdated)
    MU.upload(self.local_path, url)    
def uploadImage(url):
	global jid,pathtoimage
	uploader = MediaUploader(jid, bot.username, onUploadSuccess, onError, onProgressUpdated)
	print "going to upload",pathtoimage
	uploader.upload(pathtoimage,url)