Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.15 KB | None | 0 0
  1. import win32com.client
  2. import pythoncom
  3. import re
  4. import os
  5. import bptRelease
  6. import readExcel
  7. import generateHtml
  8. #import sshConnection
  9.  
  10. class Handler_Class(object):
  11. def OnNewMailEx(self, receivedItemsIDs):
  12. # RecrivedItemIDs е колекция от ID-та мейли, разделени със запетая, тъй като понякога може да получим повече от един имейл едновременно
  13.  
  14. for ID in receivedItemsIDs.split(","):
  15. mail = outlook.Session.GetItemFromID(ID)
  16. subject = mail.Subject # заглавие на мейла
  17. has_bpt_match = re.match(r"^([\s&,]*BPT\d{4}\.\d{2}\.\d{2}-HF\d{3}[\s&,]*)+$", subject, re.M|re.I) # От заглавието на мейла вади build, номер на hotfix и цялото име на hotfix
  18. print(has_bpt_match)
  19. mail_answer = outlook.CreateItem(0)
  20. if has_bpt_match:
  21. print("PROCESSING BPT RELEASE...")
  22. release_details = bptRelease.read_mail(mail) #build_id, hotfix_id, full hotfix name
  23. hotfix_names = []
  24. builds = []
  25. print(release_details)
  26. for hotfix in release_details:
  27. hotfix_names.append(hotfix[0])
  28. if hotfix[1] not in builds:
  29. builds.append(hotfix[1])
  30. for hotfix in release_details:
  31. correct_version = bptRelease.read_json_hf(hotfix[1], hotfix[2]) #проверява в своеобразната базичка дали всичко е наред с версиите и след това записва hotfixa в нея
  32. if not correct_version:
  33. print("Something wrong with hotfix version")
  34. #Изпраща отговор в зависимост от това какво не е наред
  35. return
  36. #sshConnection.ssh_connection(hotfix_names, "BPT1003.10.50")
  37. excel_filename = bptRelease.connect_bpt_upload()[0]
  38. version = bptRelease.connect_bpt_upload()[1]
  39. hotfixes_info = readExcel.read_xlsx_file(excel_filename, release_details)
  40. html_body = generateHtml.generate_html_file(hotfixes_info, builds, version)
  41. mail_answer.Subject = 'HFs on Top of build '
  42. for build in builds:
  43. mail_answer.Subject += 'BPT' + build + ' '
  44. mail_answer.To = 'Borislav_Stankulov@a1.bg'
  45. #mail_answer.GetInspector
  46. mail_answer.HTMLBody = html_body
  47. attachment = r"C:\BPTWorkingFolder\\" + excel_filename
  48. mail_answer.Attachments.Add(attachment)
  49. mail_answer.Display(True)
  50. #mail_answer.Send()
  51. print('Listening for new emails.....')
  52.  
  53. outlook = win32com.client.DispatchWithEvents("Outlook.Application", Handler_Class)
  54. print("LISTENING FOR EMAILS")
  55. #and then an infinite loop that waits for events.
  56. pythoncom.PumpMessages()
  57.  
  58.  
  59.  
  60.  
  61.  
  62. import os
  63. import sys
  64. import json
  65. import re
  66. import datetime
  67. import paramiko
  68. from ftplib import FTP
  69.  
  70. name = 'b_stankulov'
  71.  
  72. json_path = r'\\192.168.121.112\bobi-test' # must be mapped as network drive
  73.  
  74. '''
  75. S0 : After we received a mail, which is handled by an event listener which uses the current script's functions.
  76. The very first thing this script does is it reads the Subject and the Body of the mail, and since there is a problem
  77. with the excel file and bunch of libraries, such as openpyxl, xlrd(i have tried converting the .xlsx to .xls) and so on,
  78. won't read the color background of the cells,so through this scrip just accept the hotfixes, defined in the mail body. Thus, the script
  79. makes some additional verifications: Does the version of the RN increments with one from the previous; Does the hotfix id
  80. increment with one from the previous of the current build (E.g. Build 08.50 has prev hf with id 011, so this one must have 012) and
  81. if it is first one, is the id 001? (We check this through connecting to the shared machine, which contains a .json file, where we store
  82. all the previously accepted releases and compare them to the ones in the mail body); Lastly, it compares the ID-s in the excel and the ones
  83. in the mail body. If there are changes on top of old hf, described in the body, sry bro but handle that manually :( . Also after there is
  84. match in the defect id between the mail body and the RN manually check it in QC, SharePoint or Remedy if WO, REQ, etc.
  85. '''
  86.  
  87. def rollback(hotfix_details):
  88. print("rollback")
  89.  
  90. def read_mail(mail):
  91. all_matches = re.findall('(BPT(\d{4}\.\d{2}\.\d{2})-HF(\d{3}))', mail.Subject)
  92. return all_matches
  93.  
  94. def write_json_hf(data):
  95. with open('log.json', 'w') as json_file:
  96. json.dump(data, json_file, indent=4) #допълнителните опции са за 'разкрасяването' на json файла
  97.  
  98. #it also checks if the hf hasnt already been taken
  99. def read_json_hf(build_id, hf_id):
  100. print('Connecting to Version/HF Database...') #build id is for eg 08.50, hf_id is the id for each hotfixb given in the mail
  101. os.chdir(json_path)
  102. data = ''
  103. num_id = int(hf_id)
  104.  
  105. with open('log.json', 'r') as json_file:
  106. data = json.load(json_file)
  107.  
  108. if build_id not in data:
  109. print('Build does not exists!')
  110. return False
  111.  
  112. prev_hf = int(data[build_id][-1]["id"]) #we take the last id in the current build
  113.  
  114. if prev_hf + 1 != num_id:
  115. print('HF id is not incremented right! Somebody may have already taken it or there is discrepancy in the mail!')
  116. return False
  117. else:
  118. print('all good')
  119. data[build_id].append({'id': hf_id, 'author': name, 'date_acceptance': 1})
  120. write_json_hf(data)
  121. return True
  122.  
  123. #we will check if there is a xlsx file in the bpt_upload (RN) which version increments the last one
  124. def get_prev_RNversion():
  125. print('Retrieving last RN version...')
  126. os.chdir(json_path)
  127.  
  128. with open('versionsBPT.json', 'r') as jsonFile:
  129. data = json.load(jsonFile)
  130. prev_version = int(data[-1]) #we take the last RN verson
  131. return prev_version
  132.  
  133. '''
  134. S1 : in the end BPT files with xlxs extension have
  135. current date in this particular format -
  136. {current year of delivery}{current month of delivery}{current day of delivery}
  137. with padding zeros on the left, so we format time now it to check it later when retrieving files
  138. '''
  139. def get_date():
  140. now = datetime.datetime.now()
  141. current_year = str(now.year)
  142. current_month = str(now.month).zfill(2)
  143. current_day = str(now.day).zfill(2)
  144. date_format = current_year + current_month + current_day
  145. return date_format
  146.  
  147. '''
  148. #S2 : we connect to the ftp using ip address as login() method can contain two params: user and pass
  149. '''
  150. def connect_bpt_upload():
  151. prev_version = get_prev_RNversion() + 1
  152. date_format = get_date()
  153. os.chdir(r"C:\BPTWorkingFolder")
  154. username = "bptupload"
  155. password = "BPTMast@r"
  156. ip="192.168.121.6"
  157. directory = "/BPT_UPLOAD" #the directory, where hotfixes+RN are uploaded, sometimes RN are inside of the HF-s, we shouldnt put the RN on the install foler
  158. tp = FTP(ip)
  159. tp.login(username,password) #you can login without passing params, but you won't be able to delete the RN or move them if they are inside the release folder
  160. tp.cwd(directory)
  161. xlsx_files = tp.nlst('*xlsx')
  162.  
  163. if len(xlsx_files) == 0:
  164. print('The RN may be inside the hotfix directory. Please check it!')
  165. return False
  166.  
  167. #iterate over all files with .xlsx extension in BPT_UPLOAD
  168. for filename in xlsx_files:
  169. mk = re.match(r'(A1\sBPT_Releases_V'+ re.escape(str(prev_version)) + r'_%s.xlsx)' % date_format, filename)
  170. if mk:
  171. fhandle = open(filename, 'wb')
  172. print('Retrieving ' + filename + '...')
  173. tp.retrbinary('RETR ' + filename, fhandle.write)
  174. '''
  175. if ФАЙЛЪТ Е ВЪВ ТЕКУЩА ПАПКА:
  176. tp.delete(filename)
  177. '''
  178. fhandle.close()
  179. return (filename, prev_version)
  180.  
  181. #proverka za golemina na sql scripta - stat --printf="%s\n" *.sql // (/1048576) za MB
  182.  
  183.  
  184.  
  185.  
  186.  
  187. import os
  188. import openpyxl
  189.  
  190. def read_xlsx_file(file, hotfix_details):
  191. os.chdir(r"C:\BPTWorkingFolder")
  192. wb = openpyxl.load_workbook(file, read_only=True)
  193. sheets = wb.sheetnames
  194. versions = wb[sheets[1]]
  195. bpt = wb[sheets[2]]
  196. max_row=bpt.max_row #last changed row and last changed column in the excel sheet
  197. addedBPTs = []
  198. while bpt.cell(row = max_row, column = 2).fill.start_color.index == "FFFF0000":
  199. #проверка дали фонът е червен, green - 92d050; red - ff0000 по hexadecimal
  200. strRow = str(max_row)
  201. bptId = bpt["B"+ strRow].value
  202.  
  203. if bptId == bpt["M"+ strRow].value and bptId in bpt["L"+ strRow].value:
  204. addedBPTs.append({
  205. "name" : bptId,
  206. "apl" : bpt["D"+ strRow].value,
  207. "fixType" : bpt["E"+ strRow].value,
  208. "idDefect" : bpt["H"+ strRow].value,
  209. "description" : bpt["I"+ strRow].value,
  210. "notes" : bpt["L"+ strRow].value,
  211. "location" : bpt["M"+ strRow].value #"/install/BPT/BPT1003.11.00/HF/" + bptId
  212. })
  213. else:
  214. print("none") #трябва да хвърли подходяща грешка
  215. max_row-=1
  216. #print(addedBPTs)
  217.  
  218. versions_max_row = str(versions.max_row)
  219. bpt_versions = versions["I" + versions_max_row].value #онази втората таблица
  220. #print(bpt_versions)
  221. bpt_versions = bpt_versions.replace('\n', "<br />") #за html-а, който пращаме по мейла
  222. return (bpt_versions, addedBPTs)
  223.  
  224.  
  225. from yattag import Doc
  226.  
  227. def generate_html_file(data, builds, version):
  228. print(builds)
  229. print(version)
  230. doc, tag, text = Doc().tagtext()
  231.  
  232. style = '''<html><style>
  233. div { padding-left: 50px; }
  234. table, th, td { border-collapse: collapse; }
  235. td, th { padding-top:10px;padding-bottom:10px;text-align: center;border:1px solid black;}
  236. tr td:last-child { width:1%; white-space:nowrap; }</style><body>
  237. <p>Dear All,</p><p>Please be informed that the BPT team has sent new Release Notes (<span><strong>v.'''+ str(version) +'''</strong></span>), and the following deliverables have been accepted by the RBD team:</p>
  238. <div>
  239. <p style="font-size:110%;">
  240. <b>New HFs on Top of build '''+ builds[0] +''':</b>
  241. </p>'''
  242.  
  243. with tag('table', style = "width: 100%;"):
  244. with tag('tr', ):
  245. with tag('th'):
  246. text('HF ID')
  247. with tag('th'):
  248. text('Appl.')
  249. with tag('th'):
  250. text('Fix Type')
  251. with tag('th'):
  252. text('ID / Defect')
  253. with tag('th'):
  254. text('Description')
  255. with tag('th'):
  256. text('Notes')
  257. with tag('th'):
  258. text('Location')
  259. for hotfix in reversed(data[1]):
  260. with tag('tr'):
  261. with tag('td'):
  262. text(hotfix['name'])
  263. with tag('td'):
  264. text(hotfix['apl'])
  265. with tag('td'):
  266. text(hotfix['fixType'])
  267. with tag('td'):
  268. text(hotfix['idDefect'])
  269. with tag('td'):
  270. text(hotfix['description'])
  271. with tag('td'):
  272. text(hotfix['notes'])
  273. with tag('td'):
  274. text(hotfix['location'])
  275. doc.stag('br')
  276. with tag('p', style = "white-space: pre-line"):
  277. text('\n')
  278. doc.asis(data[0])
  279.  
  280.  
  281.  
  282. table = str(doc.getvalue())
  283. return style + table + "\n</body></html>"
  284.  
  285. #print(generate_html_file(readExcel.read_xlsx_file("A1 BPT_Releases_V4197_20181213.xlsx",1)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement