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.

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