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.

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