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.

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