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.

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