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.

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