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.

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