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.

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