def Schedule(self, sec=5 * 60, start_count=None): # This is the Scheduing evnet Which calls Send Mail event from using data source import time # start the scheduler if start_count: self.count = start_count #pdb.set_trace() if self.DATA_SOURCE == None: print '>>> ERORR No data source found.' if self.TEMPLATE_NAME == None: print '>>> ERROR - No Tempalte assigned' print '>>> INFO: Loading state...' if start_count: self.count = start_count print '>>> INFO: Resetting count to ', start_count else: try: with open('.save_state.pkl', 'rb') as handle: b = pickle.load(handle) if b.get('count') != None: self.count = b.get('count') print '>>> INFO: State Recovered, staring from index ', self.count, '...' self.count = b.get('count') except Exception, e: Log(e) print '>>> Error: no save state found...', str(e)
def ajax_keystore(request,path): # TODO SUPPORT JSON WILL TAKJE CARE BY POST>?>>>> if not KEYSTORE: return CustomHttpResponse(BuildError('KEYSTORE object canot be null',help="Did you start mongodb server ?")); # Please remve this chek in prod res= {} path = processPath(path) try: if True: #request.is_ajax(): data ={} #pdb.set_trace() if 'application/json' in request.META.get('CONTENT_TYPE'): data = json.loads(request.body) else: if request.method == 'GET': data = dict([ (k,v[0])for k,v in dict(request.GET).items()]) if request.method == 'POST': data = dict([ (k,v[0])for k,v in dict(request.POST).items()]) if request.method == 'GET': # get res = KEYSTORE.getOrSearch(path,data) if request.method == 'POST': # Create res = KEYSTORE.creteOrUpdate(path,data) if request.method == 'DELETE': # Create res = KEYSTORE.deleteEntryOrTable(path,data) else: return utils.CustomHttpResponse(utils.BuildError('This request must send by ajax',help="write a ajax call from JavaScript")); except Exception,e: d = Log(e) res ={'status':'error','fname':str(e),'stack':d};
def SendMail(self, sender='*****@*****.**', recipient="*****@*****.**", subject="test mail", body="Sample Body"): try: #pdb.set_trace() recipient = buildList(recipient) print '>>> Start Sending mail.....' headers = [ "From: " + sender, "Subject: " + subject, "To: " + str(recipient), "MIME-Version: 1.0", "Content-Type: text/html" ] headers = "\r\n".join(headers) #pdb.set_trace() session = smtplib.SMTP(self.SMTP_SERVER, self.SMTP_PORT) session.ehlo() session.starttls() session.ehlo() session.login(self.UNAME, self.PASSWD) session.sendmail(sender, recipient, headers + "\r\n\r\n" + body) session.quit() print '>>> Email Send Successfully to', recipient return { 'status': 'success', 'msg': 'mail sent to ' + str(recipient) } except Exception, e: print '>>> ERROR:SendMail ', e Log(e) return {'status': 'error', 'msg': str(e)}
def ajax_auth(request,path): # TODO SUPPORT JSON WILL TAKJE CARE BY POST>?>>>> if not KEYSTORE: return CustomHttpResponse(BuildError('KEYSTORE object canot be null',help="Did you start mongodb server ?")); # Please remve this chek in prod res= {} try: if request.method == 'POST': # We alows have a post method for this. if 'application/json' in request.META.get('CONTENT_TYPE'): data = json.loads(request.body) else: data = dict([ (k,v[0])for k,v in dict(request.POST).items()]) #pdb.set_trace() if not data.get('email'): return CustomHttpResponse(BuildError('Request must contian email',help="use {'email':'something'}")); if path == 'auths': res = SocialAuth.createOrAuthUserBySocial(data,request) elif path == 'authp': pass elif path == 'send_activate': res = SocialAuth.sendMailToActivateUser(data,request) elif path == 'activate': res = SocialAuth.activateUser(data,request) elif path == 'authp': pass else: return CustomHttpResponse(BuildError('Unknown path. see the code. ',help="use /auths or /authp ?")); else: return utils.CustomHttpResponse(utils.BuildError('Auth only Accept POST',help="Use POST METHOD")); except Exception,e: d = Log(e) res ={'status':'error','fname':str(e),'stack':d};
def DownloadAndResolveJar(jars): " We willd ownlad the jar in /tmp/ and put it dr." try: NUP = NameURLLocalPath(jars) # << <name, url,path >> alreay_have = os.listdir(BASE_PATH) succ_list = [] k = None for j in NUP: if j[0] not in alreay_have: print '>>> Downloading jar/zip ... ', j k = j testfile = urllib.URLopener() testfile.retrieve(j[1], j[2]) if (j[2].endswith('.zip')): print 'Unzipping ', j[2], '....' os.system('unzip ' + j[2] + ' -d /tmp/') else: print '\n[INFO] Skipping Download for Jar file as already exist', j[ 0] # Let Recheck and Very fy... for j in NUP: if j[0] in alreay_have: succ_list.append(j[0]) return (OK, 'Successfully Ported:\n...' + '\n...'.join(succ_list)) except Exception, e: Log(e) return (ERROR, 'Not able to resove dependency\n...For File:' + str(k) + '\n...Due to:' + str(e))
def ajax_send_email(request): # TODO SUPPORT JSON WILL TAKJE CARE BY POST>?>>>> res= {} #pdb.set_trace() try: if request.method == 'POST' :# in case of POST, We have Json Request.. data = json.loads(request.body) recipient = data['recipient'] subject = data['subject'] template = data['template'] data = data['data'] elif request.method == 'GET': recipient = request.GET['recipient'] subject = request.GET['subject'] template = request.GET['template'] data = RequestGetToDict(request.GET) data['time'] = time.ctime() else: res ={'status':'error','msg':'Operation Not supported '}; return HttpResponse(decodeUnicodeDirectory(res), content_type = 'application/json') recipient_list= utils.buildList(recipient) m = MailEngine.MailEngine() sender = '*****@*****.**' res = m.SendMailUsingTemplate(sender,recipient_list,subject,template,data) except Exception,e: d = Log(e) res ={'status':'error','fname':str(e),'stack':d};
def run(self, name=None): #pdb.set_trace() res = {} print "Launching command: " + self.run_cmd sp = subprocess.Popen(self.run_cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) fcntl.fcntl(sp.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) fcntl.fcntl(sp.stderr.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) print '>>>>> Running ith Input:<', self.input, '>' sp.stdin.flush() sp.stdin.write(self.input) sp.stdin.flush() #out= sp.communicate(input=self.input) if TimeOutByPolling(sp): res['stdout'] = '' res['stderr'] = '' res['msg'] = 'TimeOut: review your code :\n Q1. is your program contins a infinite loop?\n Q2 did you provide all the necessary inputs ?\n Q3. is your program can run in 5 sec ?\n ' res['can_run'] = 'no' res['output'] = res['msg'] return res try: res['stdout'] = sp.stdout.read() res['stderr'] = sp.stderr.read() except Exception, e: print 'Errr: Not able to read' res['callstack'] = Log(e)
def AttachTempalte(self, file): try: # Verify file is present.. f = open(file) self.TEMPLATE_NAME = file f.close() except Exception, e: Log(e) print '>>> ERROR: File Doent Exist. ', e
def decodeUnicodeDirectory(res): try: return json.dumps(res,default=json_util.default) except UnicodeDecodeError: return json.dumps(res, encoding='latin1') except Exception ,e: x = Log(e) return json.dumps({'status':'error','msg':'Your output contains a non-decodable unicode','callstack':x}, encoding='latin1')
def BuildError( msg, e=None, help="Some unknown error! Please contact the developer to fix it"): Log(e) return { 'status': 'error', 'msg': msg, 'sys_msg': str(e), 'help': help, 'res': None }
def SendMailUsingTemplate(self, sender, recipient, subject, template, data): try: from jinja2 import Template mypath = os.path.dirname(__file__) f = open(mypath + '/' + template) template = Template(f.read()) body = template.render(data) return self.SendMail(sender, recipient, subject, body) except Exception, e: Log(e) print '>>> ERROR#BuildMailTemplate: ', e return {'status': 'error', 'msg': str(e)}
def buildBooklet(request): res= {} if request.method == 'GET': config = request.GET['config'] try: config = eval(config) fout = buildBookWrapper(config) #pdb.set_trace() res ={'status':'success','fname':fout}; except Exception,e: d = Log(e) res ={'status':'error','fname':str(e),'stack':d}; return HttpResponse(decodeUnicodeDirectory(res), content_type = 'application/json')
def GCC_FORMETTED_ERROR(a): #pdb.set_trace() try: a1 = [x.split(':') for x in a.split('\n') if ('warning' in x)] #waring then Error a2 = [x.split(':') for x in a.split('\n') if ('error' in x)] a = a1 + a2 # filter valid data a = [x for x in a if x[1].isdigit()] # Modify common error message for i in a: j = i[4] if j.find('(') != -1: j = j[:j.find('(')] if j.find('{') != -1: j = j[:j.find('{')] if j.find('[') != -1: j = j[:j.find('[')] i[4] = j return a except Exception, e: Log(e) print 'Error: Not able to generated formated Error', e return []
def AttachDataSource(self, pklFile): """ Attach a Data Source which is return a a dict, whcih is used to build a message return an Iterator.. Save : a=[{'a':'a'},{'b':'b'}] f = open("data.pkl","wb") pickle.dump(a,f) f.close() """ import pickle try: f = open(pklFile, 'rb') obj = pickle.load(f) f.close() if isinstance(obj, list): self.DATA_SOURCE = obj else: print '>>> ERROR: dataSource must be a list ' except Exception, e: print '>>> ERROR: NOt able to attach data source ', e Log(e)
def ajax_github(request): res= {} try: if request.method == 'POST': # We alows have a post method for this. if 'application/json' in request.META.get('CONTENT_TYPE'): data = json.loads(request.body) else: data = dict([ (k,v[0])for k,v in dict(request.POST).items()]) if data.get('action') == 'pull': g = GitHub(repo=data.get('repo'),uname=data.get('uname'),passwd=data.get('passwd')) res = g.getFile(path=data.get('path')) elif data.get('action')== 'push': g = GitHub(repo=data.get('repo'),uname=data.get('uname'),passwd=data.get('passwd')) res = g.saveFile(path=data.get('path'),data=data.get('data'),cname=data.get('cname'),cemail=data.get('cemail'),cmsg=data.get('cmsg')); else: return CustomHttpResponse(BuildError('You must have [action=pull | push ]',help="use {'action':'pull|push'}")); else: return utils.CustomHttpResponse(utils.BuildError('gitHub only Accept POST',help="Use POST METHOD")); except Exception,e: d = Log(e) res ={'status':'error','fname':str(e),'stack':d};
body = self.BuildMailTemplate(self.TEMPLATE_NAME, data1) subj = 'Puzzle #%s: %s....' % ( self.count, data1['q'][:50] ) # MUST BE CHNAGEED IF YOUR DATA CHNAGE body = body.encode('utf-8') subj = subj.encode('utf-8') res = self.SendMail(subject=subj, body=body) if res == True: #Increment count Saving the State... self.count = self.count + 1 with open('.save_state.pkl', 'wb') as handle: pickle.dump({'count': self.count}, handle) except Exception, e: print '>>>ERROR: Some Issue while sending some message', e Log(e) print '>>>INFO: Let"s Sleep for next Evnet....', sec, 'Secons' time.sleep(sec) def AttachTempalte(self, file): try: # Verify file is present.. f = open(file) self.TEMPLATE_NAME = file f.close() except Exception, e: Log(e) print '>>> ERROR: File Doent Exist. ', e def BuildMailTemplate(self, file, data={'name': 'Dipankar'}): " Build HTML Email template and fillup with data - Return HTML mail" try: