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.

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