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.

377 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 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__ = 'DarkWeb'
  2. import codecs
  3. import glob
  4. import os, re
  5. import shutil
  6. from Forums.DB_Connection.db_connection import *
  7. from Forums.BestCardingWorld.parser import *
  8. from Forums.Cardingleaks.parser import *
  9. from Forums.CryptBB.parser import *
  10. from Forums.OnniForums.parser import *
  11. from Forums.Altenens.parser import *
  12. from Forums.Procrax.parser import *
  13. from Forums.Libre.parser import *
  14. from Forums.HiddenAnswers.parser import *
  15. from Forums.Classifier.classify_product import predict
  16. # from DarkWebMining_Sample.Forums.Classifier.classify_product import predict_semi
  17. # controls the log id
  18. nError = 0
  19. # determines if forum is russian, not really used now but maybe later
  20. def isRussianForum(forum):
  21. with open('russian_forums.txt') as f:
  22. forums = f.readlines()
  23. result = False
  24. for iforum in forums:
  25. iforum = iforum.replace('\n','')
  26. if iforum == forum:
  27. result = True
  28. break
  29. return result
  30. #tries to match description pages to listing pages by using a key made for every description page and every link in listing page
  31. #once verified and matched, the info is merged into a 'rec', which is returned
  32. #@param: detPage is a list of keys of valid pages, rec is the row of data of an instance
  33. #return: rec, row of data, that may have additional data added on after matching description to listing page
  34. def mergePages(rmm, rec):
  35. # key = u"Top:" + rec[1].upper().strip() + u" User:" + rec[5].upper().strip()
  36. # key = rec[16]
  37. print ("----------------- Matched: " + rec[3] + "--------------------")
  38. if rmm[9] != "-1": # image_user
  39. rec[9] = rmm[9]
  40. rec[10] = rmm[1]
  41. rec[11] = rmm[2]
  42. rec[12] = rmm[3]
  43. rec[13] = rmm[4]
  44. rec[14] = rmm[5]
  45. rec[15] = rmm[6]
  46. rec[16] = rmm[7]
  47. rec[17] = rmm[8]
  48. rec[18] = rmm[10]
  49. return rec
  50. #gets a string of posts and joins them together into one string to be put in the database as one string of text
  51. #@param: list of strings (the posts of a thread)
  52. #return: string containing the concatenation of all the strings
  53. def getPosts(posts):
  54. strPosts = ' '.join(posts)
  55. return strPosts.strip()
  56. #uses db connection , another program, methods to persists values to the correct categories
  57. #@param: row is the list of entries for this instance, cur is the db connection object
  58. def persist_data(url, row, cur):
  59. forum = create_forum(cur, row, url)
  60. author = create_author(cur, row, forum)
  61. topic = create_topic(cur, forum, row, author)
  62. create_posts(cur, row, forum, topic)
  63. def incrementError():
  64. global nError
  65. nError += 1
  66. def read_file(filePath, createLog, logFile):
  67. try:
  68. html = codecs.open(filePath.strip('\n'), encoding='utf8')
  69. soup = BeautifulSoup(html, "html.parser")
  70. html.close()
  71. return soup
  72. except:
  73. try:
  74. html = open(filePath.strip('\n'))
  75. soup = BeautifulSoup(html, "html.parser")
  76. html.close()
  77. return soup
  78. except:
  79. incrementError()
  80. print("There was a problem to read the file " + filePath)
  81. if createLog:
  82. logFile.write(
  83. str(nError) + ". There was a problem to read the file " + filePath + "\n" + traceback.format_exc() + "\n")
  84. return None
  85. def parse_listing(forum, listingFile, soup, createLog, logFile):
  86. try:
  87. if forum == "BestCardingWorld":
  88. rw = bestcardingworld_listing_parser(soup)
  89. elif forum == "Cardingleaks":
  90. rw = cardingleaks_listing_parser(soup)
  91. elif forum == "CryptBB":
  92. rw = cryptBB_listing_parser(soup)
  93. elif forum == "OnniForums":
  94. rw = onniForums_listing_parser(soup)
  95. elif forum == "Altenens":
  96. rw = altenens_listing_parser(soup)
  97. elif forum == "Procrax":
  98. rw = procrax_listing_parser(soup)
  99. elif forum == "Libre":
  100. rw = libre_listing_parser(soup)
  101. elif forum == "HiddenAnswers":
  102. rw = HiddenAnswers_listing_parser(soup)
  103. else:
  104. print("MISSING CALL TO LISTING PARSER IN PREPARE_PARSER.PY!")
  105. raise Exception
  106. return rw
  107. except:
  108. incrementError()
  109. print("There was a problem to parse the file " + listingFile + " in the listing section!")
  110. traceback.print_exc()
  111. if createLog:
  112. logFile.write(
  113. str(nError) + ". There was a problem to parse the file " + listingFile + " in the Listing section.\n"
  114. + traceback.format_exc() + "\n")
  115. return None
  116. def parse_description(forum, descriptionFile, soup, createLog, logFile):
  117. try:
  118. if forum == "BestCardingWorld":
  119. rmm = bestcardingworld_description_parser(soup)
  120. elif forum == "Cardingleaks":
  121. rmm = cardingleaks_description_parser(soup)
  122. elif forum == "CryptBB":
  123. rmm = cryptBB_description_parser(soup)
  124. elif forum == "OnniForums":
  125. rmm = onniForums_description_parser(soup)
  126. elif forum == "Altenens":
  127. rmm = altenens_description_parser(soup)
  128. elif forum == "Procrax":
  129. rmm = procrax_description_parser(soup)
  130. elif forum == "Libre":
  131. rmm = libre_description_parser(soup)
  132. elif forum == "HiddenAnswers":
  133. rmm = HiddenAnswers_description_parser(soup)
  134. else:
  135. print("MISSING CALL TO DESCRIPTION PARSER IN PREPARE_PARSER.PY!")
  136. raise Exception
  137. return rmm
  138. except:
  139. incrementError()
  140. print("There was a problem to parse the file " + descriptionFile + " in the Description section!")
  141. traceback.print_exc()
  142. if createLog:
  143. logFile.write(
  144. str(nError) + ". There was a problem to parse the file " + descriptionFile + " in the Description section.\n"
  145. + traceback.format_exc() + "\n")
  146. return None
  147. def persist_record(url, rec, cur, con, createLog, logFile, listingFile, descriptionFile):
  148. try:
  149. persist_data(url, tuple(rec), cur)
  150. con.commit()
  151. return True
  152. except:
  153. con.rollback()
  154. incrementError()
  155. print(f"There was a problem to persist the files ({listingFile} + {descriptionFile}) in the database!")
  156. traceback.print_exc()
  157. if createLog:
  158. logFile.write(
  159. str(nError) + f". There was a problem to persist the files ({listingFile} + {descriptionFile}) in the database!\n"
  160. + traceback.format_exc() + "\n")
  161. return False
  162. def move_file(filePath, createLog, logFile):
  163. source = filePath
  164. destination = filePath.replace(os.path.basename(filePath), "") + r'Read/'
  165. try:
  166. shutil.move(source, destination, shutil.copy2)
  167. return True
  168. except:
  169. try:
  170. shutil.move(source, destination, shutil.copytree)
  171. return True
  172. except:
  173. incrementError()
  174. print("There was a problem to move the file " + filePath)
  175. traceback.print_exc()
  176. if createLog:
  177. logFile.write(
  178. str(nError) + ". There was a problem to move the file " + filePath + "\n" + traceback.format_exc() + "\n")
  179. return False
  180. #main method for this program, what actually gets the parsed info from the parser, and persists them into the db
  181. #calls the different parser methods here depending on the type of html page
  182. def new_parse(forum, url, createLog):
  183. from Forums.Initialization.forums_mining import config, CURRENT_DATE
  184. print("Parsing the " + forum + " forum and conduct data classification to store the information in the database.")
  185. # Connecting to the database
  186. con = connectDataBase()
  187. cur = con.cursor()
  188. # Creating the tables (The database should be created manually)
  189. create_database(cur, con)
  190. mainDir = os.path.join(config.get('Project', 'shared_folder'), "Forums/" + forum + "/HTML_Pages")
  191. # Creating the log file for each Forum
  192. if createLog:
  193. try:
  194. logFile = open(mainDir + f"/{CURRENT_DATE}/" + forum + "_" + CURRENT_DATE + ".log", "w")
  195. except:
  196. print("Could not open log file!")
  197. createLog = False
  198. logFile = None
  199. # raise SystemExit
  200. else:
  201. logFile = None
  202. # Reading the Listing Html Pages
  203. listings = glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Listing", '*.html'))
  204. for listingIndex, listingFile in enumerate(listings):
  205. print("Reading listing folder of '" + forum + "', file '" + os.path.basename(listingFile) + "', index= " + str(
  206. listingIndex + 1) + " ... " + str(len(listings)))
  207. listingSoup = read_file(listingFile, createLog, logFile)
  208. # listing flags
  209. doParseListing = listingSoup is not None
  210. doDescription = False
  211. readDescriptionError = False
  212. parseDescriptionError = False
  213. persistDescriptionError = False
  214. moveDescriptionError = False
  215. findDescriptionError = False
  216. rw = []
  217. if doParseListing:
  218. rw = parse_listing(forum, listingFile, listingSoup, createLog, logFile)
  219. doDescription = rw is not None
  220. if doDescription:
  221. nFound = 0
  222. for rec in rw:
  223. rec = rec.split(',')
  224. descriptionPattern = cleanLink(rec[6]) + "page[0-9]*.html"
  225. # Reading the associated description Html Pages
  226. descriptions = glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Description", descriptionPattern))
  227. nFound += len(descriptions)
  228. for descriptionIndex, descriptionFile in enumerate(descriptions):
  229. print("Reading description folder of '" + forum + "', file '" + os.path.basename(
  230. descriptionFile) + "', index= " + str(descriptionIndex + 1) + " ... " + str(len(descriptions)))
  231. descriptionSoup = read_file(descriptionFile, createLog, logFile)
  232. # description flags
  233. doParseDescription = descriptionSoup is not None
  234. doPersistRecord = False
  235. doMoveDescription = False
  236. rmm = []
  237. if doParseDescription:
  238. rmm = parse_description(forum, descriptionFile, descriptionSoup, createLog, logFile)
  239. doPersistRecord = rmm is not None
  240. else:
  241. readDescriptionError = True
  242. parseDescriptionError = True
  243. if doPersistRecord:
  244. # Combining the information from Listing and Description Pages
  245. rec = mergePages(rmm, rec)
  246. # Append to the list the classification of the topic
  247. rec.append(str(predict(rec[3], getPosts(rec[15]), language='sup_english')))
  248. # Persisting the information in the database
  249. persistSuccess = persist_record(url, rec, cur, con, createLog, logFile, listingFile, descriptionFile)
  250. doMoveDescription = persistSuccess
  251. else:
  252. parseDescriptionError = True
  253. if doMoveDescription:
  254. # move description files of completed folder
  255. moveSuccess = move_file(descriptionFile, createLog, logFile)
  256. if not moveSuccess:
  257. moveDescriptionError = True
  258. else:
  259. moveDescriptionError = True
  260. if not (nFound > 0):
  261. findDescriptionError = True
  262. incrementError()
  263. print(f"There was a problem to locate the file(s) for {listingFile} in the Description section!")
  264. if createLog:
  265. logFile.write(
  266. str(nError) + f". There was a problem to locate the file(s) for {listingFile}"
  267. f" in the Description section!\n\n")
  268. if not (readDescriptionError or parseDescriptionError or persistDescriptionError
  269. or moveDescriptionError or findDescriptionError):
  270. # move listing files of completed folder
  271. move_file(listingFile, createLog, logFile)
  272. if createLog:
  273. logFile.close()
  274. print("Parsing the " + forum + " forum and data classification done.")