-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
tools.py
199 lines (170 loc) · 5.92 KB
/
tools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import os
from .constants import YowConstants
import codecs, sys
import logging
import tempfile
import base64
import hashlib
import os.path, mimetypes
import uuid
from consonance.structs.keypair import KeyPair
from appdirs import user_config_dir
from .optionalmodules import PILOptionalModule, FFVideoOptionalModule
logger = logging.getLogger(__name__)
class Jid:
@staticmethod
def normalize(number):
if '@' in number:
return number
elif "-" in number:
return "%s@%s" % (number, YowConstants.WHATSAPP_GROUP_SERVER)
return "%s@%s" % (number, YowConstants.WHATSAPP_SERVER)
class HexTools:
decode_hex = codecs.getdecoder("hex_codec")
@staticmethod
def decodeHex(hexString):
result = HexTools.decode_hex(hexString)[0]
if sys.version_info >= (3,0):
result = result.decode('latin-1')
return result
class WATools:
@staticmethod
def generateIdentity():
return os.urandom(20)
@classmethod
def generatePhoneId(cls):
"""
:return:
:rtype: str
"""
return str(cls.generateUUID())
@classmethod
def generateDeviceId(cls):
"""
:return:
:rtype: bytes
"""
return cls.generateUUID().bytes
@classmethod
def generateUUID(cls):
"""
:return:
:rtype: uuid.UUID
"""
return uuid.uuid4()
@classmethod
def generateKeyPair(cls):
"""
:return:
:rtype: KeyPair
"""
return KeyPair.generate()
@staticmethod
def getFileHashForUpload(filePath):
sha1 = hashlib.sha256()
f = open(filePath, 'rb')
try:
sha1.update(f.read())
finally:
f.close()
b64Hash = base64.b64encode(sha1.digest())
return b64Hash if type(b64Hash) is str else b64Hash.decode()
class StorageTools:
NAME_CONFIG = "config.json"
@staticmethod
def constructPath(*path):
path = os.path.join(*path)
fullPath = os.path.join(user_config_dir(YowConstants.YOWSUP), path)
if not os.path.exists(os.path.dirname(fullPath)):
os.makedirs(os.path.dirname(fullPath))
return fullPath
@staticmethod
def getStorageForProfile(profile_name):
if type(profile_name) is not str:
profile_name = str(profile_name)
return StorageTools.constructPath(profile_name + '/')
@staticmethod
def writeProfileData(profile_name, name, val):
logger.debug("writeProfileData(profile_name=%s, name=%s, val=[omitted])" % (profile_name, name))
path = os.path.join(StorageTools.getStorageForProfile(profile_name), name)
logger.debug("Writing %s" % path)
with open(path, 'w' if type(val) is str else 'wb') as attrFile:
attrFile.write(val)
@staticmethod
def readProfileData(profile_name, name, default=None):
logger.debug("readProfileData(profile_name=%s, name=%s)" % (profile_name, name))
path = StorageTools.getStorageForProfile(profile_name)
dataFilePath = os.path.join(path, name)
if os.path.isfile(dataFilePath):
logger.debug("Reading %s" % dataFilePath)
with open(dataFilePath, 'rb') as attrFile:
return attrFile.read()
else:
logger.debug("%s does not exist" % dataFilePath)
return default
@classmethod
def writeProfileConfig(cls, profile_name, config):
cls.writeProfileData(profile_name, cls.NAME_CONFIG, config)
@classmethod
def readProfileConfig(cls, profile_name, config):
return cls.readProfileData(profile_name, cls.NAME_CONFIG)
class ImageTools:
@staticmethod
def scaleImage(infile, outfile, imageFormat, width, height):
with PILOptionalModule() as imp:
Image = imp("Image")
im = Image.open(infile)
#Convert P mode images
if im.mode != "RGB":
im = im.convert("RGB")
im.thumbnail((width, height))
im.save(outfile, imageFormat)
return True
return False
@staticmethod
def getImageDimensions(imageFile):
with PILOptionalModule() as imp:
Image = imp("Image")
im = Image.open(imageFile)
return im.size
@staticmethod
def generatePreviewFromImage(image):
fd, path = tempfile.mkstemp()
preview = None
if ImageTools.scaleImage(image, path, "JPEG", YowConstants.PREVIEW_WIDTH, YowConstants.PREVIEW_HEIGHT):
fileObj = os.fdopen(fd, "rb+")
fileObj.seek(0)
preview = fileObj.read()
fileObj.close()
os.remove(path)
return preview
class MimeTools:
MIME_FILE = os.path.join(os.path.dirname(__file__), 'mime.types')
mimetypes.init() # Load default mime.types
try:
mimetypes.init([MIME_FILE]) # Append whatsapp mime.types
except exception as e:
logger.warning("Mime types supported can't be read. System mimes will be used. Cause: " + e.message)
@staticmethod
def getMIME(filepath):
mimeType = mimetypes.guess_type(filepath)[0]
if mimeType is None:
raise Exception("Unsupported/unrecognized file type for: "+filepath);
return mimeType
class VideoTools:
@staticmethod
def getVideoProperties(videoFile):
with FFVideoOptionalModule() as imp:
VideoStream = imp("VideoStream")
s = VideoStream(videoFile)
return s.width, s.height, s.bitrate, s.duration #, s.codec_name
@staticmethod
def generatePreviewFromVideo(videoFile):
with FFVideoOptionalModule() as imp:
VideoStream = imp("VideoStream")
fd, path = tempfile.mkstemp('.jpg')
stream = VideoStream(videoFile)
stream.get_frame_at_sec(0).image().save(path)
preview = ImageTools.generatePreviewFromImage(path)
os.remove(path)
return preview