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.

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