Skip to content

Instantly share code, notes, and snippets.

@mhanoglu
Created January 7, 2016 12:11
Show Gist options
  • Save mhanoglu/d5db5ae581ebb96ced71 to your computer and use it in GitHub Desktop.
Save mhanoglu/d5db5ae581ebb96ced71 to your computer and use it in GitHub Desktop.
Kişi adını içeren özel mesaj oluşturma ve gönderme (Android)
# encoding: utf-8
''' Project Name : SMS Engine for Android
Author : by MeHMeT a.k.a MaRZoCHi (Mehmet Hanoğlu)
Copyright : www.mehmethanoglu.com.tr
License : GNU License
Date : 03.11.2012 15:10
Update :
'''
__doc__ = 'SMS Engine for Android'
__author__ = 'by MeHMeT a.k.a MaRZoCHi'
__name__ = 'aSMSEngine'
__version__ = '0.1'
class Logger(object) :
def __init__(self, name, args = {}) :
from time import strftime
self._time = strftime ; del strftime
self.sett = args ; del args
self.file = open("/sdcard/external_sd/Python/" + name + ".log", 'a')
def wr(self, data) :
self.file.write( self._get_data(data) )
if self.sett['debug'] :
print data
def curr(self, name) :
self.name = name
def _get_data(self, data) :
return self.name + '() :: ' + self._time("%d-%m-%y %H:%M:%S") + "\n" + "-" * 45 + "\n" + data + "\n\n"
def close(self, ) :
try :
self.file.close()
del self.sett,self.name,self.file
except :
pass
class SMSEngine(Logger) :
def __init__(self, settings = None) :
self.ready = [0,0,0,0]
self._finish = False
self._devmod = False
self.log = Logger("SMSEngine",
args = {
'debug' : True,
'continuous' : True,
}
)
self._imports( )
if settings :
self.sett = settings ; del settings
self.sett['watch'] = 0
self.sett['type'] = "normal"
self._readsets( )
def _readsets( self ) :
self.log.curr("_readsets")
if self.sett['type'] == "normal" :
self._nmsg = self._droid.smsS
self.ready[1] = 1
def create_list(self, path = None) :
self.log.curr("create_list")
self._droid.dialogCreateSpinnerProgress("Bilgilendirme","içerik hazırlanıyor")
self._droid.dialogShow()
if path == None : path = self.sett['cnt_file']
cdb = self._droid.queryContent('content://com.android.contacts/data/phones',['display_name','data1'],None,None,None).result
self._count = 0
_ftemp = open(path, 'w')
for x in cdb :
mnum = [x['data1']]
if mnum :
for t in range(len(mnum)) :
cname = self._dec(x['display_name']).encode('u8')
number = (mnum[t]).replace('+9', '')
allow = [0, 0, 0]
if number != '' : allow[0] = True
for n in self.sett['gsm'] :
if number.startswith(n) : allow[1] = True
for i in self.sett['ignored'] :
if not number.startswith(i) : allow[2] = True
if allow[0] and allow[1] and allow[2] :
_ftemp.write(cname)
_ftemp.write(':' + number + '\n')
self._count += 1
_ftemp.close( )
self._droid.dialogDismiss()
def prepare(self, path = None) :
self.log.curr("prepare")
if path == None : path = self.sett['cnt_file']
_ftemp = open(path, 'r')
_fdata = _ftemp.read( ) ; _ftemp.close( )
def str2list(x) : return x.split(":")
if _fdata :
sorted = _fdata.split('\n')
sorted.sort( )
self.contacts = [str2list(x) for x in sorted]
del sorted,_fdata,_ftemp
self.ready[2] = 1
self._createmsgs()
def get_data(self) :
self.log.curr("get_data")
if self.ready[3] and not self._finish :
return "Total : %d\nCreated : %d\nExpected : %d\nInvalid : %d" %(len(self.contacts), self._count, len(self._expect), len(self._invalid))
elif self._finish :
return "Total sent : (%d/%d)\nTotal not sent : %d" %(self._count, self._sent, self._notsent)
def send(self, paused, arg = []) :
self.log.curr("send")
self._notsent, self._sent = 0, 0
dcount = 0
if not 0 in self.ready :
if self.sett['watch'] :
self.watch.start_listening('')
messages = self._readmessages()
if paused and self._get_lastsent() :
pause = messages.index(self.sett['msg_dir'] + "tmp/" + self._get_lastsent())
else :
pause = 0
for x in range(pause, len(messages)) :
_c = self._fname(messages[x])
_f = open(messages[x], 'r')
message = _f.read() ; _f.close()
name = _c.split("_")[0]
number = _c.split("_")[1]
if name and number and message :
mcont = self._sendmsg(name, number, message)
if mcont == True :
self._lastsent(_c)
self._sent += 1
print "[+]", number
try :
self._delete(messages[x])
except Exception, error :
self.log.wr(str(error))
pass
else :
self._notsent += 1
print "[-]", number
self._sleep(self.sett['delay'])
else :
self._notsent += 1
print "[-]", number
dcount += 1
if (self.sett['limit'] != 0) and (self._sent == self.sett['limit']) :
break
print "[!] Limit is full"
if len(arg) == 2 and dcount == arg[0] :
self._sleep(arg[1])
dcount = 0
self._finish = True
if self.sett['watch'] :
self.watch.stop_listening()
else :
print self.ready.index(0)
def _sendmsg(self, name, num, msg) :
self.log.curr("_sendmsg")
if not self._devmod :
if self.sett['type'] == "normal" :
print self._nmsg(unicode(num,"utf-8"), msg).result
return 1
def _readmessages(self) :
self.log.curr("_readmessages")
return [self.sett['msg_dir'] + "tmp/" + x for x in self._listdir(self.sett['msg_dir'] + "tmp/") if x.endswith(".msg")]
def _createmsgs(self, args = [None, None]) :
self.log.curr("_createmsgs")
self._count = 0
self._expect = []
self._invalid = []
path = self.sett['msg_dir']
msgs = [(path+m) for m in self._listdir(path) if self._isfile(path+m)]
lenmsgs = len(msgs)
for contact in self.contacts :
if len(contact) == 2 :
name = contact[0]
number = contact[1]
data = self._getcontent(msgs[self._rand(lenmsgs)], name)
if data :
self._printmess(data, args = {'name' : name, 'number' : number})
self.ready[3] = 1
def _printmess(self, data, args = {}) :
self.log.curr("_printmess")
try :
_f = open(self.sett['msg_dir'] + "tmp/" + self._latincon(self._enc(args['name'])) + '_' + self._enc(args['number']) + '.msg', 'w')
_f.write(self._latincon(data))
_f.close()
except Exception, error :
self.log.wr(str(error))
def _getcontent(self, path, name) :
self.log.curr("_getcontent")
_f = open(path, 'r')
msg = _f.read().replace("\xff\xfe",'') ; _f.close()
try :
msg = msg.replace("{from}", self.sett['from'])
if msg.find("{to0}") != -1 :
msg = msg.replace("{to0}", self._detectname(self._dec(name), 0) )
if msg.find("{to1}") != -1 :
msg = msg.replace("{to1}", self._detectname(self._dec(name), 1) )
if msg.find("{to2}") != -1 :
msg = msg.replace("{to2}", self._detectname(self._dec(name), 2) )
except : pass
if msg :
self._count += 1
return msg
else :
return None
def _lastsent(self, name) :
self.log.curr("_lastsent")
try :
_f = open("/sdcard/_lastsent.log", 'w')
_f.write(self._enc(name) + " :: " + self._stime("%H.%M.%S"))
_f.close()
except Exception, error :
self.log.wr(str(error))
def _get_lastsent(self) :
self.log.curr("_get_lastsent")
try :
_f = open("/sdcard/_lastsent.log", 'r')
return _f.read().split(" :: ")[0]
except Exception, error :
self.log.wr(str(error))
return None
def _detectname(self, name, mtype) :
self._expect = [] #for single usage
self.log.curr("_detectname")
LCHR = 2
if name.find(" ") != -1 :
add = self._latincon(self._enc((name.split(" ")[-1]).lower()))[-LCHR:]
else :
add = self._latincon(self._enc(name))[-LCHR:]
if len(add) != 2 :
self._invalid.append(name)
return None
else :
suffix = 0
if True :
if add.find('a') != -1 :
if add[-1] == 'a' :
if mtype == 1 : suffix = "nın"
elif mtype == 2 : suffix = "ya"
elif mtype == 0 : suffix = ""
else :
if mtype == 1 : suffix = "ın"
elif mtype == 2 : suffix = "a"
elif mtype == 0 : suffix = ""
else : pass
if add.find('e') != -1 :
if add[-1] == 'e' :
if mtype == 1 : suffix = "nin"
elif mtype == 2 : suffix = "ye"
elif mtype == 0 : suffix = ""
else :
if mtype == 1 : suffix = "in"
elif mtype == 2 : suffix = "e"
elif mtype == 0 : suffix = ""
else : pass
if add.find('o') != -1 :
if add[-1] == 'o' :
if mtype == 1 : suffix = "nun"
elif mtype == 2 : suffix = "ya"
elif mtype == 0 : suffix = ""
else :
if mtype == 1 : suffix = "un"
elif mtype == 2 : suffix = "a"
elif mtype == 0 : suffix = ""
else : pass
if add.find('u') != -1 :
if add[-1] == 'u' :
if mtype == 1 : suffix = "nun"
elif mtype == 2 : suffix = "ya"
elif mtype == 0 : suffix = ""
else :
if mtype == 1 : suffix = "un"
elif mtype == 2 : suffix = "a"
elif mtype == 0 : suffix = ""
else : pass
if add.find('i') != -1 :
if add[-1] == 'i' :
if mtype == 1 : suffix = "nin"
elif mtype == 2 : suffix = "ye"
elif mtype == 0 : suffix = ""
else :
if mtype == 1 : suffix = "in"
elif mtype == 2 : suffix = "e"
elif mtype == 0 : suffix = ""
else : pass
""" ### Turkish Characters ###
if add.find('\xf6') != -1 :
if add[-1] == '\xf6' :
if mtype == 1 : suffix = "nin"
elif mtype == 2 : suffix = "ye"
elif mtype == 0 : suffix = ""
else :
if mtype == 1 : suffix = "ün"
elif mtype == 2 : suffix = "e"
elif mtype == 0 : suffix = ""
else : pass
if add.find('\xfc') != -1 :
if add[-1] == '\xfc' :
if mtype == 1 : suffix = "nün"
elif mtype == 2 : suffix = "ye"
elif mtype == 0 : suffix = ""
else :
if mtype == 1 : suffix = "ün"
elif mtype == 2 : suffix = "e"
elif mtype == 0 : suffix = ""
else : pass
if add.find('\xb1n') != -1 :
if add[-1] == '\xb1n' :
if mtype == 1 : suffix = "nın"
elif mtype == 2 : suffix = "ya"
elif mtype == 0 : suffix = ""
else :
if mtype == 1 : suffix = "ın"
elif mtype == 2 : suffix = "a"
elif mtype == 0 : suffix = ""
else : pass"""
if suffix != 0 :
if mtype == 0 :
return (self._enc(name))
else :
return (self._enc(name) + "'" + suffix)
else :
self._expect.append(name)
return None
print "Unknown coding format for : ", [add], name
def _dec(self, txt) :
try :
t = txt.decode("u8") ; del t
txt = txt.decode("u8")
finally :
return txt
def _enc(self, txt) :
try :
t = txt.encode("u8") ; del t
txt = txt.encode("u8")
finally :
return txt
def _latincon(self, text) :
chrlist = ["ı","i","ş","s","ç","c","ğ","g","ü","u","ö","o",
"İ","i","Ş","S","Ç","C","Ğ","G","Ü","U","Ö","O"]
for x in xrange(0, len(chrlist), 2) :
text = text.replace(chrlist[x], chrlist[x+1])
return text
def _imports(self) :
import android, random
from time import strftime, sleep, clock
from os import listdir,remove
from os.path import isfile, basename
self._droid, self._sleep = android.Android(), sleep
self._stime, self._clock, self._rand = strftime, clock, random.randrange
self._isfile, self._listdir, self._fname, self._delete = isfile, listdir, basename, remove
try :
del sleep, strftime, clock, randrange, isfile, listdir, basename, remove
except : pass
self.ready[0] = 1
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment