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.

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