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.

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