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.

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