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.

373 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" + traceback.format_exc() + "\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. + traceback.format_exc() + "\n")
  112. return None
  113. def parse_description(forum, descriptionFile, soup, createLog, logFile):
  114. try:
  115. if forum == "BestCardingWorld":
  116. rmm = bestcardingworld_description_parser(soup)
  117. elif forum == "Cardingleaks":
  118. rmm = cardingleaks_description_parser(soup)
  119. elif forum == "CryptBB":
  120. rmm = cryptBB_description_parser(soup)
  121. elif forum == "OnniForums":
  122. rmm = onniForums_description_parser(soup)
  123. elif forum == "Altenens":
  124. rmm = altenens_description_parser(soup)
  125. elif forum == "Procrax":
  126. rmm = procrax_description_parser(soup)
  127. elif forum == "Libre":
  128. rmm = libre_description_parser(soup)
  129. elif forum == "HiddenAnswers":
  130. rmm = HiddenAnswers_description_parser(soup)
  131. else:
  132. print("MISSING CALL TO DESCRIPTION PARSER IN PREPARE_PARSER.PY!")
  133. raise Exception
  134. return rmm
  135. except:
  136. incrementError()
  137. print("There was a problem to parse the file " + descriptionFile + " in the Description section!")
  138. traceback.print_exc()
  139. if createLog:
  140. logFile.write(
  141. str(nError) + ". There was a problem to parse the file " + descriptionFile + " in the Description section.\n"
  142. + traceback.format_exc() + "\n")
  143. return None
  144. def persist_record(url, rec, cur, con, createLog, logFile, listingFile, descriptionFile):
  145. try:
  146. persist_data(url, tuple(rec), cur)
  147. con.commit()
  148. return True
  149. except:
  150. con.rollback()
  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(
  156. str(nError) + f". There was a problem to persist the files ({listingFile} + {descriptionFile}) in the database!\n"
  157. + traceback.format_exc() + "\n")
  158. return False
  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.copy2)
  164. return True
  165. except:
  166. try:
  167. shutil.move(source, destination, shutil.copytree)
  168. return True
  169. except:
  170. incrementError()
  171. print("There was a problem to move the file " + filePath)
  172. traceback.print_exc()
  173. if createLog:
  174. logFile.write(
  175. str(nError) + ". There was a problem to move the file " + filePath + "\n" + traceback.format_exc() + "\n")
  176. return False
  177. #main method for this program, what actually gets the parsed info from the parser, and persists them into the db
  178. #calls the different parser methods here depending on the type of html page
  179. def new_parse(forum, url, createLog):
  180. from Forums.Initialization.forums_mining import config, CURRENT_DATE
  181. print("Parsing the " + forum + " forum and conduct data classification to store the information in the database.")
  182. # Connecting to the database
  183. con = connectDataBase()
  184. cur = con.cursor()
  185. # Creating the tables (The database should be created manually)
  186. create_database(cur, con)
  187. mainDir = os.path.join(config.get('Project', 'shared_folder'), "Forums/" + forum + "/HTML_Pages")
  188. # Creating the log file for each Forum
  189. if createLog:
  190. try:
  191. logFile = open(mainDir + f"/{CURRENT_DATE}/" + forum + "_" + CURRENT_DATE + ".log", "w")
  192. except:
  193. print("Could not open log file!")
  194. createLog = False
  195. logFile = None
  196. # raise SystemExit
  197. else:
  198. logFile = None
  199. # Reading the Listing Html Pages
  200. listings = glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Listing", '*.html'))
  201. for listingIndex, listingFile in enumerate(listings):
  202. print("Reading listing folder of '" + forum + "', file '" + os.path.basename(listingFile) + "', index= " + str(
  203. listingIndex + 1) + " ... " + str(len(listings)))
  204. listingSoup = read_file(listingFile, createLog, logFile)
  205. # listing flags
  206. doParseListing = listingSoup is not None
  207. doDescription = False
  208. readDescriptionError = False
  209. parseDescriptionError = False
  210. persistDescriptionError = False
  211. moveDescriptionError = False
  212. findDescriptionError = False
  213. rw = []
  214. if doParseListing:
  215. rw = parse_listing(forum, listingFile, listingSoup, createLog, logFile)
  216. doDescription = rw is not None
  217. if doDescription:
  218. nFound = 0
  219. for rec in rw:
  220. rec = rec.split(',')
  221. descriptionPattern = cleanLink(rec[6]) + "page[0-9]*.html"
  222. # Reading the associated description Html Pages
  223. descriptions = glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Description", descriptionPattern))
  224. nFound += len(descriptions)
  225. for descriptionIndex, descriptionFile in enumerate(descriptions):
  226. print("Reading description folder of '" + forum + "', file '" + os.path.basename(
  227. descriptionFile) + "', index= " + str(descriptionIndex + 1) + " ... " + str(len(descriptions)))
  228. descriptionSoup = read_file(descriptionFile, createLog, logFile)
  229. # description flags
  230. doParseDescription = descriptionSoup is not None
  231. doPersistRecord = False
  232. doMoveDescription = False
  233. rmm = []
  234. if doParseDescription:
  235. rmm = parse_description(forum, descriptionFile, descriptionSoup, createLog, logFile)
  236. doPersistRecord = rmm is not None
  237. else:
  238. readDescriptionError = True
  239. parseDescriptionError = True
  240. if doPersistRecord:
  241. # Combining the information from Listing and Description Pages
  242. rec = mergePages(rmm, rec)
  243. # Append to the list the classification of the topic
  244. rec.append(str(predict(rec[3], getPosts(rec[14]), language='sup_english')))
  245. # Persisting the information in the database
  246. persistSuccess = persist_record(url, rec, cur, con, createLog, logFile, listingFile, descriptionFile)
  247. doMoveDescription = persistSuccess
  248. else:
  249. parseDescriptionError = True
  250. if doMoveDescription:
  251. # move description files of completed folder
  252. moveSuccess = move_file(descriptionFile, createLog, logFile)
  253. if not moveSuccess:
  254. moveDescriptionError = True
  255. else:
  256. moveDescriptionError = True
  257. if not (nFound > 0):
  258. findDescriptionError = True
  259. incrementError()
  260. print(f"There was a problem to locate the file(s) for {listingFile} in the Description section!")
  261. if createLog:
  262. logFile.write(
  263. str(nError) + f". There was a problem to locate the file(s) for {listingFile}"
  264. f" in the Description section!\n")
  265. if not (readDescriptionError or parseDescriptionError or persistDescriptionError
  266. or moveDescriptionError or findDescriptionError):
  267. # move listing files of completed folder
  268. move_file(listingFile, createLog, logFile)
  269. if createLog:
  270. logFile.close()
  271. print("Parsing the " + forum + " forum and data classification done.")