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.

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