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.

486 lines
17 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 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__ = 'DarkWeb'
  2. import glob
  3. import os
  4. import codecs
  5. import shutil
  6. import traceback
  7. from psycopg2.extras import RealDictCursor
  8. from MarketPlaces.DB_Connection.db_connection import *
  9. from MarketPlaces.DarkFox.parser import *
  10. from MarketPlaces.AnonymousMarketplace.parser import *
  11. from MarketPlaces.TheDarkMarket.parser import *
  12. from MarketPlaces.ViceCity.parser import *
  13. from MarketPlaces.M00nkeyMarket.parser import *
  14. from MarketPlaces.MikesGrandStore.parser import *
  15. from MarketPlaces.PabloEscobarMarket.parser import *
  16. from MarketPlaces.CityMarket.parser import *
  17. from MarketPlaces.DarkBazar.parser import *
  18. from MarketPlaces.Sonanza.parser import *
  19. from MarketPlaces.Kingdom.parser import *
  20. from MarketPlaces.BlackPyramid.parser import *
  21. from MarketPlaces.Quest.parser import *
  22. from MarketPlaces.Ares.parser import *
  23. from MarketPlaces.CypherMarketplace.parser import *
  24. from MarketPlaces.WeTheNorth.parser import *
  25. from MarketPlaces.Torzon.parser import *
  26. from MarketPlaces.GoFish.parser import *
  27. from MarketPlaces.ZeroDay.parser import *
  28. from MarketPlaces.DarkMarket.parser import *
  29. from MarketPlaces.DarkDock.parser import *
  30. from MarketPlaces.SilkRoad4.parser import *
  31. from MarketPlaces.Classifier.classify_product import predict
  32. from Translator.translate import translate
  33. nError = 0
  34. def mergePages(rmm, rec):
  35. # key = u"Pr:" + rec[1].upper() + u" Vendor:" + rec[18].upper()
  36. # key = rec[23]
  37. print("----------------- Matched: " + rec[4] + "--------------------")
  38. if rec[1] == "-1": # name_vendor
  39. rec[1] = rmm[0]
  40. if rec[2] == "-1": # rating_vendor
  41. rec[2] = rmm[1]
  42. if rec[3] == "-1": # success_vendor
  43. rec[3] = rmm[2]
  44. if rec[4] == "-1": # name_item
  45. rec[4] = rmm[3]
  46. if rec[5] == "-1": # description_item
  47. rec[5] = rmm[4]
  48. if rec[6] == "-1": # cve_item
  49. rec[6] = rmm[5]
  50. if rec[7] == "-1": # ms_item
  51. rec[7] = rmm[6]
  52. if rec[8] == "-1": # category_item
  53. rec[8] = rmm[7]
  54. if rec[9] == "-1": # views_item
  55. rec[9] = rmm[8]
  56. if rec[10] == "-1": # reviews_item
  57. rec[10] = rmm[9]
  58. if rec[11] == "-1": # rating_item
  59. rec[11] = rmm[10]
  60. if rec[12] == "-1": # adddate_item
  61. rec[12] = rmm[11]
  62. if rec[13] == "-1": # btc_item
  63. rec[13] = rmm[12]
  64. if rec[14] == "-1": # usd_item
  65. rec[14] = rmm[13]
  66. if rec[15] == "-1": # euro_item
  67. rec[15] = rmm[14]
  68. if rec[16] == "-1": # quantitysold_item
  69. rec[16] = rmm[15]
  70. if rec[17] == "-1": # quantityleft_item
  71. rec[17] = rmm[16]
  72. if rec[18] == "-1": # shippedfrom_item
  73. rec[18] = rmm[17]
  74. if rec[19] == "-1": # shippedto_item
  75. rec[19] = rmm[18]
  76. if rmm[19] != "-1": # image
  77. rec[20] = rmm[19]
  78. if rmm[20] != "-1": # image_vendor
  79. rec[21] = rmm[20]
  80. return rec
  81. def persist_data(url, row, cur):
  82. marketPlace = create_marketPlace(cur, row, url)
  83. vendor = create_vendor(cur, row, marketPlace)
  84. create_items(cur, row, marketPlace, vendor)
  85. def incrementError():
  86. global nError
  87. nError += 1
  88. def read_file(filePath, createLog, logFile):
  89. try:
  90. html = codecs.open(filePath.strip('\n'), encoding='utf8')
  91. soup = BeautifulSoup(html, "html.parser")
  92. html.close()
  93. time.sleep(0.01) # making sure the file is closed before returning soup object
  94. return soup
  95. except:
  96. try:
  97. html = open(filePath.strip('\n'))
  98. soup = BeautifulSoup(html, "html.parser")
  99. html.close()
  100. time.sleep(0.01) # making sure the file is closed before returning soup object
  101. return soup
  102. except:
  103. incrementError()
  104. print("There was a problem to read the file " + filePath)
  105. if createLog:
  106. logFile.write(
  107. str(nError) + ". There was a problem to read the file " + filePath + "\n" + traceback.format_exc() + "\n")
  108. return None
  109. def parse_listing(marketPlace, listingFile, soup, createLog, logFile):
  110. try:
  111. if marketPlace == "DarkFox":
  112. rw = darkfox_listing_parser(soup)
  113. elif marketPlace == "AnonymousMarketplace":
  114. rw = anonymousMarketplace_listing_parser(soup)
  115. elif marketPlace == "ViceCity":
  116. rw = vicecity_listing_parser(soup)
  117. elif marketPlace == "M00nkeyMarket":
  118. rw = m00nkey_listing_parser(soup)
  119. elif marketPlace == "MikesGrandStore":
  120. rw = MikesGrandStore_listing_parser(soup)
  121. elif marketPlace == "PabloEscobarMarket":
  122. rw = pabloescobarmarket_listing_parser(soup)
  123. elif marketPlace == "CityMarket":
  124. rw = city_listing_parser(soup)
  125. elif marketPlace == "Ares":
  126. rw = ares_listing_parser(soup)
  127. elif marketPlace == "DarkBazar":
  128. rw = darkbazar_listing_parser(soup)
  129. elif marketPlace == "Sonanza":
  130. rw = sonanza_listing_parser(soup)
  131. elif marketPlace == "Kingdom":
  132. rw = kingdom_listing_parser(soup)
  133. elif marketPlace == "BlackPyramid":
  134. rw = blackpyramid_listing_parser(soup)
  135. elif marketPlace == "Quest":
  136. rw = quest_listing_parser(soup)
  137. elif marketPlace == "CypherMarketplace":
  138. rw = cyphermarketplace_listing_parser(soup)
  139. elif marketPlace == "TheDarkMarket":
  140. rw = thedarkmarket_listing_parser(soup)
  141. elif marketPlace == "WeTheNorth":
  142. rw = wethenorth_listing_parser(soup)
  143. elif marketPlace == "GoFish":
  144. rw = gofish_listing_parser(soup)
  145. elif marketPlace == "ZeroDay":
  146. rw = zeroday_listing_parser(soup)
  147. elif marketPlace == "Torzon":
  148. rw = torzon_listing_parser(soup)
  149. elif marketPlace == "DarkMarket":
  150. rw = darkmarket_listing_parser(soup)
  151. elif marketPlace == "DarkDock":
  152. rw = darkdock_listing_parser()
  153. elif marketPlace == "SilkRoad4":
  154. rw = silkroad4_listing_parser()
  155. else:
  156. print("MISSING CALL TO LISTING PARSER IN PREPARE_PARSER.PY!")
  157. raise Exception
  158. return rw
  159. except:
  160. incrementError()
  161. print("There was a problem to parse the file " + listingFile + " in the listing section!")
  162. traceback.print_exc()
  163. if createLog:
  164. logFile.write(
  165. str(nError) + ". There was a problem to parse the file " + listingFile + " in the Listing section.\n"
  166. + traceback.format_exc() + "\n")
  167. return None
  168. def parse_description(marketPlace, descriptionFile, soup, createLog, logFile):
  169. try:
  170. if marketPlace == "DarkFox":
  171. rmm = darkfox_description_parser(soup)
  172. elif marketPlace == "AnonymousMarketplace":
  173. rmm = anonymousMarketplace_description_parser(soup)
  174. elif marketPlace == "ViceCity":
  175. rmm = vicecity_description_parser(soup)
  176. elif marketPlace == "M00nkeyMarket":
  177. rmm = m00nkey_description_parser(soup)
  178. elif marketPlace == "MikesGrandStore":
  179. rmm = MikesGrandStore_description_parser(soup)
  180. elif marketPlace == "PabloEscobarMarket":
  181. rmm = pabloescobarmarket_description_parser(soup)
  182. elif marketPlace == "CityMarket":
  183. rmm = city_description_parser(soup)
  184. elif marketPlace == "Ares":
  185. rmm = ares_description_parser(soup)
  186. elif marketPlace == "DarkBazar":
  187. rmm = darkbazar_description_parser(soup)
  188. elif marketPlace == "Sonanza":
  189. rmm = sonanza_description_parser(soup)
  190. elif marketPlace == "Kingdom":
  191. rmm = kingdom_description_parser(soup)
  192. elif marketPlace == "BlackPyramid":
  193. rmm = blackpyramid_description_parser(soup)
  194. elif marketPlace == "Quest":
  195. rmm = quest_description_parser(soup)
  196. elif marketPlace == "CypherMarketplace":
  197. rmm = cyphermarketplace_description_parser(soup)
  198. elif marketPlace == "TheDarkMarket":
  199. rmm = thedarkmarket_description_parser(soup)
  200. elif marketPlace == "WeTheNorth":
  201. rmm = wethenorth_description_parser(soup)
  202. elif marketPlace == "GoFish":
  203. rmm = gofish_description_parser(soup)
  204. elif marketPlace == "ZeroDay":
  205. rmm = zeroday_description_parser(soup)
  206. elif marketPlace == "Torzon":
  207. rmm = torzon_description_parser(soup)
  208. elif marketPlace == "DarkMarket":
  209. rmm = darkmarket_description_parser(soup)
  210. elif marketPlace == "DarkDock":
  211. rmm = darkdock_description_parser(soup)
  212. elif marketPlace == "SilkRoad4":
  213. rmm = silkroad4_description_parser()
  214. else:
  215. print("MISSING CALL TO DESCRIPTION PARSER IN PREPARE_PARSER.PY!")
  216. raise Exception
  217. return rmm
  218. except:
  219. incrementError()
  220. print("There was a problem to parse the file " + descriptionFile + " in the Description section!")
  221. traceback.print_exc()
  222. if createLog:
  223. logFile.write(
  224. str(nError) + ". There was a problem to parse the file " + descriptionFile + " in the Description section.\n"
  225. + traceback.format_exc() + "\n")
  226. return None
  227. def get_source_language(marketPlace):
  228. if marketPlace == "BestCardingWorld":
  229. lang = 'english'
  230. elif marketPlace == "CryptBB":
  231. lang = 'english'
  232. elif marketPlace == "Incogsnoo":
  233. lang = 'english'
  234. elif marketPlace == "CityMarket":
  235. lang = 'english'
  236. elif marketPlace == "DarkMarket":
  237. lang = 'english'
  238. else:
  239. print("MISSING CALL TO GET LANGUAGE IN PREPARE_PARSER.PY!")
  240. lang = 'auto'
  241. return lang
  242. def persist_record(url, rec, cur, con, createLog, logFile, listingFile, descriptionFile):
  243. try:
  244. persist_data(url, tuple(rec), cur)
  245. con.commit()
  246. return True
  247. except:
  248. con.rollback()
  249. incrementError()
  250. print(f"There was a problem to persist the files ({listingFile} + {descriptionFile}) in the database!")
  251. traceback.print_exc()
  252. if createLog:
  253. logFile.write(
  254. str(nError) + f". There was a problem to persist the files ({listingFile} + {descriptionFile}) in the database!\n"
  255. + traceback.format_exc() + "\n")
  256. return False
  257. def move_file(filePath, createLog, logFile):
  258. source = filePath
  259. destination = filePath.replace(os.path.basename(filePath), "") + 'Read\\' + os.path.basename(filePath)
  260. try:
  261. shutil.move(source, destination, shutil.copy2)
  262. return True
  263. except:
  264. try:
  265. shutil.move(source, destination, shutil.copytree)
  266. return True
  267. except:
  268. incrementError()
  269. print("There was a problem to move the file " + filePath)
  270. traceback.print_exc()
  271. if createLog:
  272. logFile.write(
  273. str(nError) + ". There was a problem to move the file " + filePath + "\n" + traceback.format_exc() + "\n")
  274. return False
  275. def new_parse(marketPlace, url, createLog):
  276. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  277. global nError
  278. nError = 0
  279. print("Parsing the " + marketPlace + " market and conduct data classification to store the information in the database.")
  280. # Connecting to the database
  281. con = connectDataBase()
  282. cur = con.cursor(cursor_factory=RealDictCursor)
  283. # Creating the tables (The database should be created manually)
  284. create_database(cur, con)
  285. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces\\" + marketPlace + "\\HTML_Pages")
  286. # Creating the log file for each Forum
  287. if createLog:
  288. try:
  289. logFile = open(mainDir + f"/{CURRENT_DATE}/" + marketPlace + "_" + CURRENT_DATE + ".log", "w")
  290. except:
  291. print("Could not open log file!")
  292. createLog = False
  293. logFile = None
  294. # raise SystemExit
  295. else:
  296. logFile = None
  297. source_lang = get_source_language(marketPlace)
  298. # Reading the Listing Html Pages
  299. listings = glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Listing", '*.html'))
  300. listings.sort(key=os.path.getmtime)
  301. for listingIndex, listingFile in enumerate(listings):
  302. print("Reading listing folder of '" + marketPlace + "', file '" + os.path.basename(listingFile) + "', index= " + str(
  303. listingIndex + 1) + " ... " + str(len(listings)))
  304. listingSoup = read_file(listingFile, createLog, logFile)
  305. # listing flags
  306. doParseListing = listingSoup is not None
  307. doDescription = False
  308. readDescriptionError = False
  309. parseDescriptionError = False
  310. persistDescriptionError = False
  311. moveDescriptionError = False
  312. findDescriptionError = False
  313. rw = []
  314. if doParseListing:
  315. rw = parse_listing(marketPlace, listingFile, listingSoup, createLog, logFile)
  316. doDescription = rw is not None
  317. if doDescription:
  318. nFound = 0
  319. for rec in rw:
  320. rec = rec.split(',')
  321. descriptionPattern = cleanLink(rec[22]) + ".html"
  322. # Reading the associated description Html Pages
  323. descriptions = glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Description", descriptionPattern))
  324. descriptions.sort(key=os.path.getmtime)
  325. nFound += len(descriptions)
  326. for descriptionIndex, descriptionFile in enumerate(descriptions):
  327. print("Reading description folder of '" + marketPlace + "', file '" + os.path.basename(
  328. descriptionFile) + "', index= " + str(descriptionIndex + 1) + " ... " + str(len(descriptions)))
  329. descriptionSoup = read_file(descriptionFile, createLog, logFile)
  330. # description flags
  331. doParseDescription = descriptionSoup is not None
  332. doPersistRecord = False
  333. doMoveDescription = False
  334. rmm = []
  335. if doParseDescription:
  336. rmm = parse_description(marketPlace, descriptionFile, descriptionSoup, createLog, logFile)
  337. doPersistRecord = rmm is not None
  338. else:
  339. readDescriptionError = True
  340. parseDescriptionError = True
  341. if doPersistRecord:
  342. # Combining the information from Listing and Description Pages
  343. rec = mergePages(rmm, rec)
  344. title = translate(rec[4], source_lang)
  345. content = translate(rec[5], source_lang)
  346. # Append to the list the classification of the topic
  347. rec.append(str(predict(title, content, language='sup_english')))
  348. # Persisting the information in the database
  349. persistSuccess = persist_record(url, rec, cur, con, createLog, logFile, listingFile,
  350. descriptionFile)
  351. doMoveDescription = persistSuccess
  352. else:
  353. parseDescriptionError = True
  354. if doMoveDescription:
  355. # move description files of completed folder
  356. moveSuccess = move_file(descriptionFile, createLog, logFile)
  357. if not moveSuccess:
  358. moveDescriptionError = True
  359. else:
  360. moveDescriptionError = True
  361. if not (nFound > 0):
  362. findDescriptionError = True
  363. incrementError()
  364. print(f"There was a problem to locate the file(s) for {listingFile} in the Description section!")
  365. if createLog:
  366. logFile.write(
  367. str(nError) + f". There was a problem to locate the file(s) for {listingFile}"
  368. f" in the Description section!\n\n")
  369. if not (readDescriptionError or parseDescriptionError or persistDescriptionError
  370. or moveDescriptionError or findDescriptionError):
  371. # move listing files of completed folder
  372. move_file(listingFile, createLog, logFile)
  373. # registering the current forum status (up/down) and the number of scraped pages in the database
  374. marketId = verifyMarketPlace(cur, marketPlace)
  375. if (marketId > 0):
  376. readListings = glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Listing\\read", '*.html'))
  377. readDescriptions = glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Description\\read", '*.html'))
  378. create_status(cur, marketId, CURRENT_DATE, len(readListings), len(readDescriptions), '1' if len(listings) > 0 else '0')
  379. con.commit()
  380. if createLog:
  381. logFile.close()
  382. cur.close()
  383. con.close()
  384. print("Parsing the " + marketPlace + " market and data classification done.")