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.

399 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. __author__ = 'Helium'
  2. import glob
  3. import os
  4. import codecs
  5. import shutil
  6. from MarketPlaces.DB_Connection.db_connection import *
  7. from MarketPlaces.DarkFox.parser import *
  8. from MarketPlaces.Tor2door.parser import *
  9. from MarketPlaces.Apocalypse.parser import *
  10. from MarketPlaces.ThiefWorld.parser import *
  11. from MarketPlaces.AnonymousMarketplace.parser import *
  12. from MarketPlaces.ViceCity.parser import *
  13. from MarketPlaces.TorBay.parser import *
  14. from MarketPlaces.M00nkeyMarket.parser import *
  15. from MarketPlaces.DarkMatter.parser import *
  16. from MarketPlaces.DigitalThriftShop.parser import *
  17. from MarketPlaces.LionMarketplace.parser import *
  18. from MarketPlaces.TorMarket.parser import *
  19. from MarketPlaces.HiddenMarket.parser import *
  20. from MarketPlaces.RobinhoodMarket.parser import *
  21. from MarketPlaces.Nexus.parser import *
  22. from MarketPlaces.MikesGrandStore.parser import *
  23. from MarketPlaces.Classifier.classify_product import predict
  24. nError = 0
  25. def mergePages(rmm, rec):
  26. # key = u"Pr:" + rec[1].upper() + u" Vendor:" + rec[18].upper()
  27. # key = rec[23]
  28. print("----------------- Matched: " + rec[4] + "--------------------")
  29. if rec[1] == "-1": # name_vendor
  30. rec[1] = rmm[0]
  31. if rec[2] == "-1": # rating_vendor
  32. rec[2] = rmm[1]
  33. if rec[3] == "-1": # success_vendor
  34. rec[3] = rmm[2]
  35. if rec[4] == "-1": # name_item
  36. rec[4] = rmm[3]
  37. if rec[5] == "-1": # description_item
  38. rec[5] = rmm[4]
  39. if rec[6] == "-1": # cve_item
  40. rec[6] = rmm[5]
  41. if rec[7] == "-1": # ms_item
  42. rec[7] = rmm[6]
  43. if rec[8] == "-1": # category_item
  44. rec[8] = rmm[7]
  45. if rec[9] == "-1": # views_item
  46. rec[9] = rmm[8]
  47. if rec[10] == "-1": # reviews_item
  48. rec[10] = rmm[9]
  49. if rec[11] == "-1": # rating_item
  50. rec[11] = rmm[10]
  51. if rec[12] == "-1": # adddate_item
  52. rec[12] = rmm[11]
  53. if rec[13] == "-1": # btc_item
  54. rec[13] = rmm[12]
  55. if rec[14] == "-1": # usd_item
  56. rec[14] = rmm[13]
  57. if rec[15] == "-1": # euro_item
  58. rec[15] = rmm[14]
  59. if rec[16] == "-1": # quantitysold_item
  60. rec[16] = rmm[15]
  61. if rec[17] == "-1": # quantityleft_item
  62. rec[17] = rmm[16]
  63. if rec[18] == "-1": # shippedfrom_item
  64. rec[18] = rmm[17]
  65. if rec[19] == "-1": # shippedto_item
  66. rec[19] = rmm[18]
  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. return soup
  81. except:
  82. try:
  83. html = open(filePath.strip('\n'))
  84. soup = BeautifulSoup(html, "html.parser")
  85. html.close()
  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")
  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 == "Tor2door":
  99. rw = tor2door_listing_parser(soup)
  100. elif marketPlace == "Apocalypse":
  101. rw = apocalypse_listing_parser(soup)
  102. elif marketPlace == "ThiefWorld":
  103. rw = thiefWorld_listing_parser(soup)
  104. elif marketPlace == "AnonymousMarketplace":
  105. rw = anonymousMarketplace_listing_parser(soup)
  106. elif marketPlace == "ViceCity":
  107. rw = vicecity_listing_parser(soup)
  108. elif marketPlace == "TorBay":
  109. rw = torbay_listing_parser(soup)
  110. elif marketPlace == "M00nkeyMarket":
  111. rw = m00nkey_listing_parser(soup)
  112. elif marketPlace == "HiddenMarket":
  113. rw = hiddenmarket_listing_parser(soup)
  114. elif marketPlace == "DarkMatter":
  115. rw = darkmatter_listing_parser(soup)
  116. elif marketPlace == "DigitalThriftShop":
  117. rw = digitalThriftShop_listing_parser(soup)
  118. elif marketPlace == "LionMarketplace":
  119. rw = lionmarketplace_listing_parser(soup)
  120. elif marketPlace == "TorMarket":
  121. rw = tormarket_listing_parser(soup)
  122. elif marketPlace == "RobinhoodMarket":
  123. rw = Robinhood_listing_parser(soup)
  124. elif marketPlace == "Nexus":
  125. rw = nexus_listing_parser(soup)
  126. elif marketPlace == "MikesGrandStore":
  127. rw = mikesGrandStore_listing_parser(soup)
  128. else:
  129. print("MISSING CALL TO LISTING PARSER IN PREPARE_PARSER.PY!")
  130. raise Exception
  131. return rw
  132. except:
  133. incrementError()
  134. print("There was a problem to parse the file " + listingFile + " in the listing section!")
  135. traceback.print_exc()
  136. if createLog:
  137. logFile.write(
  138. str(nError) + ". There was a problem to parse the file " + listingFile + " in the Listing section.\n")
  139. return None
  140. def parse_description(marketPlace, descriptionFile, soup, createLog, logFile):
  141. try:
  142. if marketPlace == "DarkFox":
  143. rmm = darkfox_description_parser(soup)
  144. elif marketPlace == "Tor2door":
  145. rmm = tor2door_description_parser(soup)
  146. elif marketPlace == "Apocalypse":
  147. rmm = apocalypse_description_parser(soup)
  148. elif marketPlace == "ThiefWorld":
  149. rmm = thiefWorld_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 == "TorBay":
  155. rmm = torbay_description_parser(soup)
  156. elif marketPlace == "M00nkeyMarket":
  157. rmm = m00nkey_description_parser(soup)
  158. elif marketPlace == "HiddenMarket":
  159. rmm = hiddenmarket_description_parser(soup)
  160. elif marketPlace == "DarkMatter":
  161. rmm = darkmatter_description_parser(soup)
  162. elif marketPlace == "DigitalThriftShop":
  163. rmm = digitalThriftShop_description_parser(soup)
  164. elif marketPlace == "LionMarketplace":
  165. rmm = lionmarketplace_description_parser(soup)
  166. elif marketPlace == "TorMarket":
  167. rmm = tormarket_description_parser(soup)
  168. elif marketPlace == "RobinhoodMarket":
  169. rmm = Robinhood_description_parser(soup)
  170. elif marketPlace == "Nexus":
  171. rmm = nexus_description_parser(soup)
  172. elif marketPlace == "MikesGrandStore":
  173. rmm = mikesGrandStore_description_parser(soup)
  174. else:
  175. print("MISSING CALL TO DESCRIPTION PARSER IN PREPARE_PARSER.PY!")
  176. raise Exception
  177. return rmm
  178. except:
  179. incrementError()
  180. print("There was a problem to parse the file " + descriptionFile + " in the Description section!")
  181. traceback.print_exc()
  182. if createLog:
  183. logFile.write(
  184. str(nError) + ". There was a problem to parse the file " + descriptionFile + " in the Description section.\n")
  185. return None
  186. def persist_record(url, rec, cur, con, createLog, logFile, listingFile, descriptionFile):
  187. try:
  188. persist_data(url, tuple(rec), cur)
  189. con.commit()
  190. return True
  191. except:
  192. con.rollback()
  193. trace = traceback.format_exc()
  194. if trace.find("already exists") == -1:
  195. incrementError()
  196. print(f"There was a problem to persist the files ({listingFile} + {descriptionFile}) in the database!")
  197. traceback.print_exc()
  198. if createLog:
  199. logFile.write(
  200. str(nError) + f". There was a problem to persist the files ({listingFile} + {descriptionFile}) in the database!\n")
  201. return False
  202. else:
  203. return True
  204. def move_file(filePath, createLog, logFile):
  205. # source = line2.replace(os.path.basename(line2), "") + filename
  206. source = filePath
  207. destination = filePath.replace(os.path.basename(filePath), "") + r'Read/'
  208. try:
  209. shutil.move(source, destination)
  210. return True
  211. except:
  212. print("There was a problem to move the file " + filePath)
  213. incrementError()
  214. if createLog:
  215. logFile.write(
  216. str(nError) + ". There was a problem to move the file " + filePath + "\n")
  217. return False
  218. def new_parse(marketPlace, url, createLog):
  219. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  220. print("Parsing the " + marketPlace + " market and conduct data classification to store the information in the database.")
  221. # Connecting to the database
  222. con = connectDataBase()
  223. cur = con.cursor()
  224. # Creating the tables (The database should be created manually)
  225. create_database(cur, con)
  226. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + marketPlace + "/HTML_Pages")
  227. # Creating the log file for each Forum
  228. if createLog:
  229. try:
  230. logFile = open(mainDir + f"/{CURRENT_DATE}/" + marketPlace + "_" + CURRENT_DATE + ".log", "w")
  231. except:
  232. print("Could not open log file!")
  233. createLog = False
  234. logFile = None
  235. # raise SystemExit
  236. else:
  237. logFile = None
  238. # Reading the Listing Html Pages
  239. listings = glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Listing", '*.html'))
  240. for listingIndex, listingFile in enumerate(listings):
  241. print("Reading listing folder of '" + marketPlace + "', file '" + os.path.basename(listingFile) + "', index= " + str(
  242. listingIndex + 1) + " ... " + str(len(listings)))
  243. listingSoup = read_file(listingFile, createLog, logFile)
  244. # listing flags
  245. doParseListing = listingSoup is not None
  246. doDescription = False
  247. readDescriptionError = False
  248. parseDescriptionError = False
  249. persistDescriptionError = False
  250. moveDescriptionError = False
  251. findDescriptionError = False
  252. rw = []
  253. if doParseListing:
  254. rw = parse_listing(marketPlace, listingFile, listingSoup, createLog, logFile)
  255. doDescription = rw is not None
  256. if doDescription:
  257. nFound = 0
  258. for rec in rw:
  259. rec = rec.split(',')
  260. descriptionPattern = cleanLink(rec[20]) + ".html"
  261. # Reading the associated description Html Pages
  262. descriptions = glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Description", descriptionPattern))
  263. nFound += len(descriptions)
  264. for descriptionIndex, descriptionFile in enumerate(descriptions):
  265. print("Reading description folder of '" + marketPlace + "', file '" + os.path.basename(
  266. descriptionFile) + "', index= " + str(descriptionIndex + 1) + " ... " + str(len(descriptions)))
  267. descriptionSoup = read_file(descriptionFile, createLog, logFile)
  268. # description flags
  269. doParseDescription = descriptionSoup is not None
  270. doPersistRecord = False
  271. doMoveDescription = False
  272. rmm = []
  273. if doParseDescription:
  274. rmm = parse_description(marketPlace, descriptionFile, descriptionSoup, createLog, logFile)
  275. doPersistRecord = rmm is not None
  276. else:
  277. readDescriptionError = True
  278. parseDescriptionError = True
  279. if doPersistRecord:
  280. # Combining the information from Listing and Description Pages
  281. rec = mergePages(rmm, rec)
  282. # Append to the list the classification of the topic
  283. rec.append(str(predict(rec[4], rec[5], language='sup_english')))
  284. # Persisting the information in the database
  285. persistSuccess = persist_record(url, rec, cur, con, createLog, logFile, listingFile,
  286. descriptionFile)
  287. doMoveDescription = persistSuccess
  288. else:
  289. parseDescriptionError = True
  290. if doMoveDescription:
  291. # move description files of completed folder
  292. moveSuccess = move_file(descriptionFile, createLog, logFile)
  293. if not moveSuccess:
  294. moveDescriptionError = True
  295. else:
  296. moveDescriptionError = True
  297. if not (nFound > 0):
  298. findDescriptionError = True
  299. incrementError()
  300. print(f"There was a problem to locate the file(s) for {listingFile} in the Description section!")
  301. if createLog:
  302. logFile.write(
  303. str(nError) + f". There was a problem to locate the file(s) for {listingFile}"
  304. f" in the Description section!\n")
  305. if not (readDescriptionError or parseDescriptionError or persistDescriptionError
  306. or moveDescriptionError or findDescriptionError):
  307. # move listing files of completed folder
  308. move_file(listingFile, createLog, logFile)
  309. if createLog:
  310. logFile.close()
  311. print("Parsing the " + marketPlace + " market and data classification done.")