Skip to content

Commit

Permalink
add StatusLayer
Browse files Browse the repository at this point in the history
  • Loading branch information
3mora2 committed Feb 9, 2024
1 parent 573d4cc commit b425818
Show file tree
Hide file tree
Showing 5 changed files with 240 additions and 45 deletions.
42 changes: 22 additions & 20 deletions WPP_Whatsapp/PlaywrightSafeThread/browser/threadsafe_browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,26 +281,28 @@ async def first_page(self):
return page

def check_profile(self, path):
path_old = dict()
for proc in psutil.process_iter():
if "chrome.exe" in proc.name():
cmd = proc.cmdline()
user = list(filter(lambda x: "--user-data-dir" in x, cmd))
if user:
_path = os.path.normpath(user[0].split("=")[-1])
if _path not in path_old:
path_old[_path] = []
path_old[_path].append(proc)

elif "firefox.exe" in proc.name():
cmd = proc.cmdline()
user = list(filter(lambda x: "-profile" in x, cmd))
if user:
_path = os.path.normpath(cmd[cmd.index(user[0]) + 1])
if _path not in path_old:
path_old[_path] = []
path_old[_path].append(proc)

try:
path_old = dict()
for proc in psutil.process_iter():
if "chrome.exe" in proc.name():
cmd = proc.cmdline()
user = list(filter(lambda x: "--user-data-dir" in x, cmd))
if user:
_path = os.path.normpath(user[0].split("=")[-1])
if _path not in path_old:
path_old[_path] = []
path_old[_path].append(proc)

elif "firefox.exe" in proc.name():
cmd = proc.cmdline()
user = list(filter(lambda x: "-profile" in x, cmd))
if user:
_path = os.path.normpath(cmd[cmd.index(user[0]) + 1])
if _path not in path_old:
path_old[_path] = []
path_old[_path].append(proc)
except:
pass
if os.path.normpath(path) in path_old:
if self.__close_already_profile:
for proc in path_old[os.path.normpath(path)]:
Expand Down
39 changes: 39 additions & 0 deletions WPP_Whatsapp/api/layers/HostLayer.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import asyncio
import logging
import base64 as base64_model
import mimetypes
import os
import re
import threading
import time
from time import sleep
Expand Down Expand Up @@ -531,3 +534,39 @@ def valid_chatId(chatId):

def close(self):
self.ThreadsafeBrowser.sync_close()

@staticmethod
def convert_to_base64(path):
mimetypes_add = {"webp": "image/webp"}
# mime = magic.Magic(mime=True)
# content_type = mime.from_file(path)
content_type = mimetypes.guess_type(path)[0]
if not content_type:
content_type = mimetypes_add.get(path.split(".")[-1], None)
if not content_type:
content_type = 'application/octet-stream'
# filename = os.path.basename(path)
with open(path, "rb") as image_file:
archive = base64_model.b64encode(image_file.read())
archive = archive.decode("utf-8")
print(content_type)
return "data:" + content_type + ";base64," + archive

def fileToBase64(self, path):
return self.convert_to_base64(path)
@staticmethod
def base64MimeType(encoded):
result = encoded.split(";base64")[0].split(":")[-1]
return result

@staticmethod
def base64MimeTypeV2(encoded: str):
result = None
if not isinstance(encoded, str):
return result

mime = re.match(r'data:([a-zA-Z0-9]+/[a-zA-Z0-9-.+]+).*,.*', encoded)
if mime and mime.group(1):
result = mime.group(1)

return result
24 changes: 1 addition & 23 deletions WPP_Whatsapp/api/layers/SenderLayer.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import base64 as base64_model
import mimetypes

import os
from WPP_Whatsapp.api.layers.ListenerLayer import ListenerLayer
from WPP_Whatsapp.api.helpers.download_file import downloadFileToBase64
Expand Down Expand Up @@ -487,24 +486,3 @@ async def setChatState_(self, chatId, chatState):
WAPI.sendChatstate(chatState, chatId);
}""", {"chatState": chatState, "chatId": chatId})

@staticmethod
def convert_to_base64(path):
mimetypes_add = {"webp": "image/webp"}
# mime = magic.Magic(mime=True)
# content_type = mime.from_file(path)
content_type = mimetypes.guess_type(path)[0]
if not content_type:
content_type = mimetypes_add.get(path.split(".")[-1], None)
if not content_type:
content_type = 'application/octet-stream'
# filename = os.path.basename(path)
with open(path, "rb") as image_file:
archive = base64_model.b64encode(image_file.read())
archive = archive.decode("utf-8")
print(content_type)
return "data:" + content_type + ";base64," + archive

@staticmethod
def base64MimeType(encoded):
result = encoded.split(";base64")[0].split(":")[-1]
return result
178 changes: 177 additions & 1 deletion WPP_Whatsapp/api/layers/StatusLayer.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,181 @@
from WPP_Whatsapp.api.layers.LabelsLayer import LabelsLayer
from WPP_Whatsapp.api.helpers.download_file import downloadFileToBase64


class StatusLayer(LabelsLayer):
pass
def sendImageStatus(self, pathOrBase64: str, timeout=60):
"""
/**
* Send a image message to status stories
* @category Status
*
* @example
* ```javascript
* client.sendImageStatus('data:image/jpeg;base64,<a long base64 file...>');
* ```
* @param pathOrBase64 Path or base 64 image
*/
"""
return self.ThreadsafeBrowser.run_threadsafe(
self.sendImageStatus_, pathOrBase64, timeout_=timeout)

def sendVideoStatus(self, pathOrBase64: str, timeout=60):
"""
/**
* Send a video message to status stories
* @category Status
*
* @example
* ```javascript
* client.sendVideoStatus('data:video/mp4;base64,<a long base64 file...>');
* ```
* @param pathOrBase64 Path or base 64 image
*/
"""
return self.ThreadsafeBrowser.run_threadsafe(
self.sendVideoStatus_, pathOrBase64, timeout_=timeout)

def sendTextStatus(self, text: str, options: dict = {}, timeout=60):
"""
/**
* Send a text to status stories
* @category Status
*
* @example
* ```javascript
* client.sendTextStatus(`Bootstrap primary color: #0275d8`, { backgroundColor: '#0275d8', font: 2});
* ```
* @param pathOrBase64 Path or base 64 image
*/
"""
return self.ThreadsafeBrowser.run_threadsafe(
self.sendTextStatus_, text, options, timeout_=timeout)

def sendReadStatus(self, chatId: str, statusId: str, timeout=60):
"""/**
* Mark status as read/seen
* @category Status
*
* @example
* ```javascript
* client.sendReadStatus('[phone_number]@c.us', 'false_status@broadcast_3A169E0FD4BC6E92212F_[]@c.us');
* ```
* @param chatId Chat ID of contact
* @param statusId ID of status msg
*/"""
return self.ThreadsafeBrowser.run_threadsafe(
self.sendReadStatus_, chatId, statusId, timeout_=timeout)

##########################################################################
async def sendImageStatus_(self, pathOrBase64: str):
"""
/**
* Send a image message to status stories
* @category Status
*
* @example
* ```javascript
* client.sendImageStatus('data:image/jpeg;base64,<a long base64 file...>');
* ```
* @param pathOrBase64 Path or base 64 image
*/
"""
base64 = ''
if pathOrBase64.startswith('data:'):
base64 = pathOrBase64
else:
file_content = await downloadFileToBase64(pathOrBase64, [
'image/gif',
'image/png',
'image/jpg',
'image/jpeg',
'image/webp',
])
if not file_content:
file_content = self.fileToBase64(pathOrBase64)
if file_content:
base64 = file_content

if not base64:
error = ValueError('Empty or invalid file or base64')
error.code = 'empty_file'
raise error

mime_info = self.base64MimeTypeV2(base64)
if not mime_info or 'image' not in mime_info:
error = ValueError('Not an image, allowed formats png, jpeg and webp')
error.code = 'invalid_image'
raise error

return await self.ThreadsafeBrowser.page_evaluate(
"""({base64}) => WPP.status.sendImageStatus(base64);""",
{"base64": base64}
)

async def sendVideoStatus_(self, pathOrBase64: str):
"""
/**
* Send a video message to status stories
* @category Status
*
* @example
* ```javascript
* client.sendVideoStatus('data:video/mp4;base64,<a long base64 file...>');
* ```
* @param pathOrBase64 Path or base 64 image
*/
"""
base64 = ''
if pathOrBase64.startswith('data:'):
base64 = pathOrBase64
else:
file_content = await downloadFileToBase64(pathOrBase64)
if not file_content:
file_content = self.fileToBase64(pathOrBase64)
if file_content:
base64 = file_content

if not base64:
error = ValueError('Empty or invalid file or base64')
error.code = 'empty_file'
raise error

return await self.ThreadsafeBrowser.page_evaluate(
"""({base64}) => WPP.status.sendVideoStatus(base64);""",
{"base64": base64}
)

async def sendTextStatus_(self, text: str, options: str):
"""
/**
* Send a text to status stories
* @category Status
*
* @example
* ```javascript
* client.sendTextStatus(`Bootstrap primary color: #0275d8`, { backgroundColor: '#0275d8', font: 2});
* ```
* @param pathOrBase64 Path or base 64 image
*/
"""
return await self.ThreadsafeBrowser.page_evaluate(
"""({text, options}) => WPP.status.sendTextStatus(text, options);""",
{"text": text, "options": options}
)

async def sendReadStatus_(self, chatId: str, statusId: str):
"""/**
* Mark status as read/seen
* @category Status
*
* @example
* ```javascript
* client.sendReadStatus('[phone_number]@c.us', 'false_status@broadcast_3A169E0FD4BC6E92212F_[]@c.us');
* ```
* @param chatId Chat ID of contact
* @param statusId ID of status msg
*/"""
return await self.ThreadsafeBrowser.page_evaluate(
"""({ chatId, statusId }) => WPP.status.sendReadStatus(chatId, statusId);""",
{"chatId": chatId, "statusId": statusId}
)
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"the creation of any interaction, such as customer service, media sending, intelligence recognition "
"based on phrases artificial and many other things, use your imagination")

version = "0.1.6.2"
version = "0.1.7"

setup(
name="WPP_Whatsapp",
Expand Down

0 comments on commit b425818

Please sign in to comment.