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.

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