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.

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