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.

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