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.

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