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.

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