this is based on calsyslab project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

307 lines
12 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. __author__ = 'Helium'
  2. import glob
  3. import os
  4. import codecs
  5. import shutil
  6. from MarketPlaces.DB_Connection.db_connection import *
  7. from MarketPlaces.DarkFox.parser import *
  8. from MarketPlaces.Tor2door.parser import *
  9. from MarketPlaces.Apocalypse.parser import *
  10. from MarketPlaces.Classifier.classify_product import predict
  11. def mergePages(rmm, rec):
  12. # key = u"Pr:" + rec[1].upper() + u" Vendor:" + rec[18].upper()
  13. # key = rec[23]
  14. print("----------------- Matched: " + rec[1] + "--------------------")
  15. if rec[1] == "-1": # name_vendor
  16. rec[1] = rmm[0]
  17. if rec[2] == "-1": # rating_vendor
  18. rec[2] = rmm[1]
  19. if rec[3] == "-1": # success_vendor
  20. rec[3] = rmm[2]
  21. if rec[4] == "-1": # name_item
  22. rec[4] = rmm[3]
  23. if rec[5] == "-1": # description_item
  24. rec[5] = rmm[4]
  25. if rec[6] == "-1": # cve_item
  26. rec[6] = rmm[5]
  27. if rec[7] == "-1": # ms_item
  28. rec[7] = rmm[6]
  29. if rec[8] == "-1": # category_item
  30. rec[8] = rmm[7]
  31. if rec[9] == "-1": # views_item
  32. rec[9] = rmm[8]
  33. if rec[10] == "-1": # reviews_item
  34. rec[10] = rmm[9]
  35. if rec[11] == "-1": # rating_item
  36. rec[11] = rmm[10]
  37. if rec[12] == "-1": # adddate_item
  38. rec[12] = rmm[11]
  39. if rec[13] == "-1": # btc_item
  40. rec[13] = rmm[12]
  41. if rec[14] == "-1": # usd_item
  42. rec[14] = rmm[13]
  43. if rec[15] == "-1": # euro_item
  44. rec[15] = rmm[14]
  45. if rec[16] == "-1": # quantitysold_item
  46. rec[16] = rmm[15]
  47. if rec[17] == "-1": # quantityleft_item
  48. rec[17] = rmm[16]
  49. if rec[18] == "-1": # shippedfrom_item
  50. rec[18] = rmm[17]
  51. if rec[19] == "-1": # shippedto_item
  52. rec[19] = rmm[18]
  53. return rec
  54. def persist_data(url, row, cur):
  55. marketPlace = create_marketPlace(cur, row, url)
  56. vendor = create_vendor(cur, row, marketPlace)
  57. create_items(cur, row, marketPlace, vendor)
  58. def new_parse(marketPlace, url, createLog):
  59. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  60. print("Parsing the " + marketPlace + " marketplace and conduct data classification to store the information in the database.")
  61. # ini = time.time()
  62. # Connecting to the database
  63. con = connectDataBase()
  64. cur = con.cursor()
  65. # Creating the tables (The database should be created manually)
  66. create_database(cur, con)
  67. nError = 0
  68. lines = [] # listing pages
  69. lns = [] # description pages
  70. detPage = {}
  71. #Creating the log file for each Market Place
  72. if createLog:
  73. if not os.path.exists("./" + marketPlace + "/Logs/" + marketPlace + "_" + CURRENT_DATE + ".log"):
  74. logFile = open("./" + marketPlace + "/Logs/" + marketPlace + "_" + CURRENT_DATE + ".log", "w")
  75. else:
  76. print("Files of the date " + CURRENT_DATE + " from the Market Place " + marketPlace +
  77. " were already read. Delete the referent information in the Data Base and also delete the log file"
  78. " in the _Logs folder to read files from this Market Place of this date again.")
  79. raise SystemExit
  80. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + marketPlace + "/HTML_Pages")
  81. # Reading the Listing Html Pages
  82. for fileListing in glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Listing", '*.html')):
  83. lines.append(fileListing)
  84. # Reading the Description Html Pages
  85. for fileDescription in glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Description", '*.html')):
  86. lns.append(fileDescription)
  87. # Parsing the Description Pages and put the tag's content into a dictionary (Hash table)
  88. for index, line2 in enumerate(lns):
  89. print("Reading description folder of '" + marketPlace + "', file '" + os.path.basename(line2) + "', index= " + str(index + 1) + " ... " + str(len(lns)))
  90. try:
  91. html = codecs.open(line2.strip('\n'), encoding='utf8')
  92. soup = BeautifulSoup(html, "html.parser")
  93. html.close()
  94. except:
  95. try:
  96. html = open(line2.strip('\n'))
  97. soup = BeautifulSoup(html, "html.parser")
  98. html.close()
  99. except:
  100. nError += 1
  101. print("There was a problem to read the file " + line2 + " in the Description section!")
  102. if createLog:
  103. logFile.write(str(nError) + ". There was a problem to read the file " + line2 + " in the Description section.\n")
  104. continue
  105. try:
  106. if marketPlace == "DarkFox":
  107. rmm = darkfox_description_parser(soup)
  108. elif marketPlace == "Tor2door":
  109. rmm = tor2door_description_parser(soup)
  110. elif marketPlace == "Apocalypse":
  111. rmm = apocalypse_description_parser(soup)
  112. # key = u"Pr:" + rmm[0].upper()[:desc_lim1] + u" Vendor:" + rmm[13].upper()[:desc_lim2]
  113. key = u"Url:" + os.path.basename(line2).replace(".html", "")
  114. # save file address with description record in memory
  115. detPage[key] = {'rmm': rmm, 'filename': os.path.basename(line2)}
  116. except:
  117. nError += 1
  118. print("There was a problem to parse the file " + line2 + " in the Description section!")
  119. if createLog:
  120. logFile.write(str(nError) + ". There was a problem to parse the file " + line2 + " in the Description section.\n")
  121. # Parsing the Listing Pages and put the tag's content into a list
  122. for index, line1 in enumerate(lines):
  123. print("Reading listing folder of '" + marketPlace + "', file '" + os.path.basename(line1) + "', index= " + str(index + 1) + " ... " + str(len(lines)))
  124. readError = False
  125. try:
  126. html = codecs.open(line1.strip('\n'), encoding='utf8')
  127. soup = BeautifulSoup(html, "html.parser")
  128. html.close()
  129. except:
  130. try:
  131. html = open(line1.strip('\n'))
  132. soup = BeautifulSoup(html, "html.parser")
  133. html.close()
  134. except:
  135. nError += 1
  136. print("There was a problem to read the file " + line1 + " in the Listing section!")
  137. if createLog:
  138. logFile.write(str(nError) + ". There was a problem to read the file " + line1 + " in the Listing section.\n")
  139. readError = True
  140. if not readError:
  141. parseError = False
  142. try:
  143. if marketPlace == "DarkFox":
  144. rw = darkfox_listing_parser(soup)
  145. elif marketPlace == "Tor2door":
  146. rw = tor2door_listing_parser(soup)
  147. elif marketPlace == "Apocalypse":
  148. rw = apocalypse_listing_parser(soup)
  149. else:
  150. parseError = True
  151. except:
  152. nError += 1
  153. print("There was a problem to parse the file " + line1 + " in the listing section!")
  154. if createLog:
  155. logFile.write(
  156. str(nError) + ". There was a problem to parse the file " + line1 + " in the Listing section.\n")
  157. parseError = True
  158. if not parseError:
  159. persistError = False
  160. moveError = False
  161. num_in_db = 0
  162. num_persisted_moved = 0
  163. for rec in rw:
  164. rec = rec.split(',')
  165. # if len(detPage) > 0: #It was created here just because Zeroday Market does not have Description Pages
  166. # key = rec[23]
  167. # key = u"Pr:" + rec[1].upper()[:list_lim1] + u" Vendor:" + rec[18].upper()[:list_lim2]
  168. key = u"Url:" + cleanLink(rec[20])
  169. # if the associated description page is parsed
  170. if key in detPage:
  171. # rec = mergePages(detPage, rec)
  172. # Combining the information from Listing and Description Pages
  173. rmm = detPage[key]['rmm']
  174. rec = mergePages(rmm, rec)
  175. # Append to the list the classification of the product
  176. # rec.append(str(predict(rec[1], rec[5], language='markets')))
  177. rec.append(str(predict(rec[4], rec[5], language='sup_english')))
  178. # Persisting the information in the database
  179. try:
  180. persist_data(url, tuple(rec), cur)
  181. con.commit()
  182. except:
  183. trace = traceback.format_exc()
  184. if trace.find("already exists") == -1:
  185. nError += 1
  186. print("There was a problem to persist the file " + detPage[key]['filename'] + " in the database!")
  187. if createLog:
  188. logFile.write(
  189. str(nError) + ". There was a problem to persist the file " + detPage[key]['filename'] + " in the database.\n")
  190. persistError = True
  191. con.rollback()
  192. if not persistError:
  193. # move description files of completed folder
  194. source = line2.replace(os.path.basename(line2), "") + detPage[key]['filename']
  195. destination = line2.replace(os.path.basename(line2), "") + r'Read/'
  196. try:
  197. shutil.move(source, destination)
  198. num_persisted_moved += 1
  199. except:
  200. print("There was a problem to move the file " + detPage[key]['filename'] + " in the Description section!")
  201. nError += 1
  202. if createLog:
  203. logFile.write(
  204. str(nError) + ". There was a problem to move the file " + detPage[key]['filename'] + " in the Description section!.\n")
  205. moveError = True
  206. # if the associated description page is not read or not parsed
  207. else:
  208. # query database
  209. # if the product already exists:
  210. # num_in_db += 1
  211. pass
  212. # if number of products on listing page is equal to
  213. # the number of merged, persisted, and moved products plus
  214. # the number of products already in the database
  215. if not persistError and not moveError and len(rw) == (num_persisted_moved + num_in_db):
  216. # move listing file to completed folder
  217. source = line1
  218. destination = line1.replace(os.path.basename(line1), "") + r'Read/'
  219. try:
  220. shutil.move(source, destination)
  221. except:
  222. nError += 1
  223. print("There was a problem to move the file " + line1 + " in the Listing section!")
  224. if createLog:
  225. logFile.write(str(nError) + ". There was a problem to move the file " + line1 + " in the Listing section!.\n")
  226. # g.close ()
  227. if createLog:
  228. logFile.close()
  229. # end = time.time()
  230. # finalTime = float(end-ini)
  231. # print (marketPlace + " Parsing Perfomed Succesfully in %.2f" %finalTime + "!")
  232. input("Parsing the " + marketPlace + " marketplace and data classification done successfully. Press ENTER to continue\n")