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.

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