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.

352 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. __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.Classifier.classify_product import predict
  20. def mergePages(rmm, rec):
  21. # key = u"Pr:" + rec[1].upper() + u" Vendor:" + rec[18].upper()
  22. # key = rec[23]
  23. print("----------------- Matched: " + rec[4] + "--------------------")
  24. if rec[1] == "-1": # name_vendor
  25. rec[1] = rmm[0]
  26. if rec[2] == "-1": # rating_vendor
  27. rec[2] = rmm[1]
  28. if rec[3] == "-1": # success_vendor
  29. rec[3] = rmm[2]
  30. if rec[4] == "-1": # name_item
  31. rec[4] = rmm[3]
  32. if rec[5] == "-1": # description_item
  33. rec[5] = rmm[4]
  34. if rec[6] == "-1": # cve_item
  35. rec[6] = rmm[5]
  36. if rec[7] == "-1": # ms_item
  37. rec[7] = rmm[6]
  38. if rec[8] == "-1": # category_item
  39. rec[8] = rmm[7]
  40. if rec[9] == "-1": # views_item
  41. rec[9] = rmm[8]
  42. if rec[10] == "-1": # reviews_item
  43. rec[10] = rmm[9]
  44. if rec[11] == "-1": # rating_item
  45. rec[11] = rmm[10]
  46. if rec[12] == "-1": # adddate_item
  47. rec[12] = rmm[11]
  48. if rec[13] == "-1": # btc_item
  49. rec[13] = rmm[12]
  50. if rec[14] == "-1": # usd_item
  51. rec[14] = rmm[13]
  52. if rec[15] == "-1": # euro_item
  53. rec[15] = rmm[14]
  54. if rec[16] == "-1": # quantitysold_item
  55. rec[16] = rmm[15]
  56. if rec[17] == "-1": # quantityleft_item
  57. rec[17] = rmm[16]
  58. if rec[18] == "-1": # shippedfrom_item
  59. rec[18] = rmm[17]
  60. if rec[19] == "-1": # shippedto_item
  61. rec[19] = rmm[18]
  62. return rec
  63. def persist_data(url, row, cur):
  64. marketPlace = create_marketPlace(cur, row, url)
  65. vendor = create_vendor(cur, row, marketPlace)
  66. create_items(cur, row, marketPlace, vendor)
  67. def new_parse(marketPlace, url, createLog):
  68. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  69. print("Parsing the " + marketPlace + " marketplace and conduct data classification to store the information in the database.")
  70. # ini = time.time()
  71. # Connecting to the database
  72. con = connectDataBase()
  73. cur = con.cursor()
  74. # Creating the tables (The database should be created manually)
  75. create_database(cur, con)
  76. nError = 0
  77. lines = [] # listing pages
  78. lns = [] # description pages
  79. detPage = {}
  80. #Creating the log file for each Market Place
  81. if createLog:
  82. if not os.path.exists("./" + marketPlace + "/Logs/" + marketPlace + "_" + CURRENT_DATE + ".log"):
  83. logFile = open("./" + marketPlace + "/Logs/" + marketPlace + "_" + CURRENT_DATE + ".log", "w")
  84. else:
  85. print("Files of the date " + CURRENT_DATE + " from the Market Place " + marketPlace +
  86. " were already read. Delete the referent information in the Data Base and also delete the log file"
  87. " in the _Logs folder to read files from this Market Place of this date again.")
  88. raise SystemExit
  89. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + marketPlace + "/HTML_Pages")
  90. # Reading the Listing Html Pages
  91. for fileListing in glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Listing", '*.html')):
  92. lines.append(fileListing)
  93. # Reading the Description Html Pages
  94. for fileDescription in glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Description", '*.html')):
  95. lns.append(fileDescription)
  96. # Parsing the Description Pages and put the tag's content into a dictionary (Hash table)
  97. for index, line2 in enumerate(lns):
  98. print("Reading description folder of '" + marketPlace + "', file '" + os.path.basename(line2) + "', index= " + str(index + 1) + " ... " + str(len(lns)))
  99. try:
  100. html = codecs.open(line2.strip('\n'), encoding='utf8')
  101. soup = BeautifulSoup(html, "html.parser")
  102. html.close()
  103. except:
  104. try:
  105. html = open(line2.strip('\n'))
  106. soup = BeautifulSoup(html, "html.parser")
  107. html.close()
  108. except:
  109. nError += 1
  110. print("There was a problem to read the file " + line2 + " in the Description section!")
  111. if createLog:
  112. logFile.write(str(nError) + ". There was a problem to read the file " + line2 + " in the Description section.\n")
  113. continue
  114. try:
  115. if marketPlace == "DarkFox":
  116. rmm = darkfox_description_parser(soup)
  117. elif marketPlace == "Tor2door":
  118. rmm = tor2door_description_parser(soup)
  119. elif marketPlace == "Apocalypse":
  120. rmm = apocalypse_description_parser(soup)
  121. elif marketPlace == "ThiefWorld":
  122. rmm = thiefWorld_description_parser(soup)
  123. elif marketPlace =="AnonymousMarketplace":
  124. rmm = anonymousMarketplace_description_parser(soup)
  125. elif marketPlace == "ViceCity":
  126. rmm = vicecity_description_parser(soup)
  127. elif marketPlace == "TorBay":
  128. rmm = torbay_description_parser(soup)
  129. elif marketPlace == "M00nkeyMarket":
  130. rmm = m00nkey_description_parser(soup)
  131. elif marketPlace == "DarkMatter":
  132. rmm = darkmatter_description_parser(soup)
  133. elif marketPlace == "DigitalThriftShop":
  134. rmm = digitalThriftShop_description_parser(soup)
  135. elif marketPlace == "LionMarketplace":
  136. rmm = lionmarketplace_description_parser(soup)
  137. elif marketPlace == "TorMarket":
  138. rmm = tormarket_description_parser(soup)
  139. # key = u"Pr:" + rmm[0].upper()[:desc_lim1] + u" Vendor:" + rmm[13].upper()[:desc_lim2]
  140. key = u"Url:" + os.path.basename(line2).replace(".html", "")
  141. # save file address with description record in memory
  142. detPage[key] = {'rmm': rmm, 'filename': os.path.basename(line2)}
  143. except Exception as e:
  144. raise e
  145. nError += 1
  146. print("There was a problem to parse the file " + line2 + " in the Description section!")
  147. if createLog:
  148. logFile.write(str(nError) + ". There was a problem to parse the file " + line2 + " in the Description section.\n")
  149. # Parsing the Listing Pages and put the tag's content into a list
  150. for index, line1 in enumerate(lines):
  151. print("Reading listing folder of '" + marketPlace + "', file '" + os.path.basename(line1) + "', index= " + str(index + 1) + " ... " + str(len(lines)))
  152. readError = False
  153. try:
  154. html = codecs.open(line1.strip('\n'), encoding='utf8')
  155. soup = BeautifulSoup(html, "html.parser")
  156. html.close()
  157. except:
  158. try:
  159. html = open(line1.strip('\n'))
  160. soup = BeautifulSoup(html, "html.parser")
  161. html.close()
  162. except Exception as e:
  163. raise e
  164. nError += 1
  165. print("There was a problem to read the file " + line1 + " in the Listing section!")
  166. if createLog:
  167. logFile.write(str(nError) + ". There was a problem to read the file " + line1 + " in the Listing section.\n")
  168. readError = True
  169. if not readError:
  170. parseError = False
  171. try:
  172. if marketPlace == "DarkFox":
  173. rw = darkfox_listing_parser(soup)
  174. elif marketPlace == "Tor2door":
  175. rw = tor2door_listing_parser(soup)
  176. elif marketPlace == "Apocalypse":
  177. rw = apocalypse_listing_parser(soup)
  178. elif marketPlace == "ThiefWorld":
  179. rw = thiefWorld_listing_parser(soup)
  180. elif marketPlace == "AnonymousMarketplace":
  181. rw = anonymousMarketplace_listing_parser(soup)
  182. elif marketPlace == "ViceCity":
  183. rw = vicecity_listing_parser(soup)
  184. elif marketPlace == "TorBay":
  185. rw = torbay_listing_parser(soup)
  186. elif marketPlace == "M00nkeyMarket":
  187. rw = m00nkey_listing_parser(soup)
  188. elif marketPlace == "DarkMatter":
  189. rw = darkmatter_listing_parser(soup)
  190. elif marketPlace == "DigitalThriftShop":
  191. rw = digitalThriftShop_listing_parser(soup)
  192. elif marketPlace == "LionMarketplace":
  193. rw = lionmarketplace_listing_parser(soup)
  194. elif marketPlace == "TorMarket":
  195. rw = tormarket_listing_parser(soup)
  196. else:
  197. parseError = True
  198. except Exception as e:
  199. nError += 1
  200. print("There was a problem to parse the file " + line1 + " in the listing section!")
  201. print("I am here for some reason!")
  202. raise e
  203. if createLog:
  204. logFile.write(
  205. str(nError) + ". There was a problem to parse the file " + line1 + " in the Listing section.\n")
  206. parseError = True
  207. if not parseError:
  208. persistError = False
  209. moveError = False
  210. num_in_db = 0
  211. num_persisted_moved = 0
  212. for rec in rw:
  213. rec = rec.split(',')
  214. # if len(detPage) > 0: #It was created here just because Zeroday Market does not have Description Pages
  215. # key = rec[23]
  216. # key = u"Pr:" + rec[1].upper()[:list_lim1] + u" Vendor:" + rec[18].upper()[:list_lim2]
  217. key = u"Url:" + cleanLink(rec[20])
  218. # if the associated description page is parsed
  219. if key in detPage:
  220. # rec = mergePages(detPage, rec)
  221. # Combining the information from Listing and Description Pages
  222. rmm = detPage[key]['rmm']
  223. rec = mergePages(rmm, rec)
  224. # Append to the list the classification of the product
  225. # rec.append(str(predict(rec[1], rec[5], language='markets')))
  226. rec.append(str(predict(rec[4], rec[5], language='sup_english')))
  227. # Persisting the information in the database
  228. try:
  229. persist_data(url, tuple(rec), cur)
  230. con.commit()
  231. except:
  232. trace = traceback.format_exc()
  233. if trace.find("already exists") == -1:
  234. nError += 1
  235. print("There was a problem to persist the file " + detPage[key]['filename'] + " in the database!")
  236. if createLog:
  237. logFile.write(
  238. str(nError) + ". There was a problem to persist the file " + detPage[key]['filename'] + " in the database.\n")
  239. persistError = True
  240. con.rollback()
  241. if not persistError:
  242. # move description files of completed folder
  243. source = line2.replace(os.path.basename(line2), "") + detPage[key]['filename']
  244. destination = line2.replace(os.path.basename(line2), "") + r'Read/'
  245. try:
  246. shutil.move(source, destination)
  247. num_persisted_moved += 1
  248. except:
  249. print("There was a problem to move the file " + detPage[key]['filename'] + " in the Description section!")
  250. nError += 1
  251. if createLog:
  252. logFile.write(
  253. str(nError) + ". There was a problem to move the file " + detPage[key]['filename'] + " in the Description section!.\n")
  254. moveError = True
  255. # if the associated description page is not read or not parsed
  256. else:
  257. # query database
  258. # if the product already exists:
  259. # num_in_db += 1
  260. pass
  261. # if number of products on listing page is equal to
  262. # the number of merged, persisted, and moved products plus
  263. # the number of products already in the database
  264. if not persistError and not moveError and len(rw) == (num_persisted_moved + num_in_db):
  265. # move listing file to completed folder
  266. source = line1
  267. destination = line1.replace(os.path.basename(line1), "") + r'Read/'
  268. try:
  269. shutil.move(source, destination)
  270. except:
  271. nError += 1
  272. print("There was a problem to move the file " + line1 + " in the Listing section!")
  273. if createLog:
  274. logFile.write(str(nError) + ". There was a problem to move the file " + line1 + " in the Listing section!.\n")
  275. # g.close ()
  276. if createLog:
  277. logFile.close()
  278. # end = time.time()
  279. # finalTime = float(end-ini)
  280. # print (marketPlace + " Parsing Perfomed Succesfully in %.2f" %finalTime + "!")
  281. input("Parsing the " + marketPlace + " marketplace and data classification done successfully. Press ENTER to continue\n")