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.

344 lines
11 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. board = create_board(cur, row, forum)
  57. author = create_user(cur, row, forum, 0)
  58. topic = create_topic(cur, row, forum, board, author)
  59. create_posts(cur, row, forum, board, 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. rw = []
  85. if forum == "BestCardingWorld":
  86. rw = bestcardingworld_listing_parser(soup)
  87. elif forum == "Cardingleaks":
  88. rw = cardingleaks_listing_parser(soup)
  89. elif forum == "CryptBB":
  90. rw = cryptBB_listing_parser(soup)
  91. elif forum == "OnniForums":
  92. rw = onniForums_listing_parser(soup)
  93. elif forum == "Altenens":
  94. rw = altenens_listing_parser(soup)
  95. elif forum == "Procrax":
  96. rw = procrax_listing_parser(soup)
  97. elif forum == "Libre":
  98. rw = libre_listing_parser(soup)
  99. return rw
  100. except:
  101. incrementError()
  102. print("There was a problem to read the file " + listingFile + " in the listing section!")
  103. traceback.print_exc()
  104. if createLog:
  105. logFile.write(
  106. str(nError) + ". There was a problem to read the file " + listingFile + " in the Listing section.\n")
  107. return None
  108. def parse_description(forum, descriptionFile, soup, createLog, logFile):
  109. try:
  110. rmm = []
  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. return rmm
  126. except:
  127. incrementError()
  128. print("There was a problem to parse the file " + descriptionFile + " in the Description section!")
  129. traceback.print_exc()
  130. if createLog:
  131. logFile.write(
  132. str(nError) + ". There was a problem to parse the file " + descriptionFile + " in the Description section.\n")
  133. return None
  134. def persist_record(url, rec, cur, con, createLog, logFile, listingFile, descriptionFile):
  135. try:
  136. persist_data(url, tuple(rec), cur)
  137. con.commit()
  138. return True
  139. except:
  140. con.rollback()
  141. trace = traceback.format_exc()
  142. if trace.find("already exists") == -1:
  143. incrementError()
  144. print(f"There was a problem to persist the files ({listingFile} + {descriptionFile}) in the database!")
  145. if createLog:
  146. logFile.write(str(nError) + f"There was a problem to persist the files ({listingFile} + {descriptionFile}) in the database!\n")
  147. return False
  148. else:
  149. return True
  150. def move_file(filePath, createLog, logFile):
  151. # source = line2.replace(os.path.basename(line2), "") + filename
  152. source = filePath
  153. destination = filePath.replace(os.path.basename(filePath), "") + r'Read/'
  154. try:
  155. shutil.move(source, destination)
  156. return True
  157. except:
  158. print("There was a problem to move the file " + filePath)
  159. incrementError()
  160. if createLog:
  161. logFile.write(
  162. str(nError) + ". There was a problem to move the file " + filePath + "\n")
  163. return False
  164. #main method for this program, what actually gets the parsed info from the parser, and persists them into the db
  165. #calls the different parser methods here depending on the type of html page
  166. def new_parse(forum, url, createLog):
  167. from Forums.Initialization.forums_mining import config, CURRENT_DATE
  168. print("Parsing The " + forum + " Forum and conduct data classification to store the information in the database.")
  169. # Connecting to the database
  170. con = connectDataBase()
  171. cur = con.cursor()
  172. # Creating the tables (The database should be created manually)
  173. create_database(cur, con)
  174. mainDir = os.path.join(config.get('Project', 'shared_folder'), "Forums/" + forum + "/HTML_Pages")
  175. # Creating the log file for each Forum
  176. if createLog:
  177. try:
  178. logFile = open(mainDir + f"/{CURRENT_DATE}/" + forum + "_" + CURRENT_DATE + ".log", "w")
  179. except:
  180. print("Could not open log file!")
  181. raise SystemExit
  182. else:
  183. logFile = None
  184. # Reading the Listing Html Pages
  185. listings = glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Listing", '*.html'))
  186. for listingIndex, listingFile in enumerate(listings):
  187. print("Reading listing folder of '" + forum + "', file '" + os.path.basename(listingFile) + "', index= " + str(
  188. listingIndex + 1) + " ... " + str(len(listings)))
  189. listingSoup = read_file(listingFile, createLog, logFile)
  190. # listing flags
  191. doParseListing = listingSoup is not None
  192. doDescription = False
  193. readDescriptionError = False
  194. parseDescriptionError = False
  195. persistDescriptionError = False
  196. moveDescriptionError = False
  197. rw = []
  198. if doParseListing:
  199. rw = parse_listing(forum, listingFile, listingSoup, createLog, logFile)
  200. doDescription = rw is not None
  201. if doDescription:
  202. for rec in rw:
  203. rec = rec.split(',')
  204. descriptionPattern = cleanLink(rec[6]) + "page[0-9]*.html"
  205. # Reading the associated description Html Pages
  206. descriptions = glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Description", descriptionPattern))
  207. for descriptionIndex, descriptionFile in enumerate(descriptions):
  208. print("Reading description folder of '" + forum + "', file '" + os.path.basename(
  209. descriptionFile) + "', index= " + str(descriptionIndex + 1) + " ... " + str(len(descriptions)))
  210. descriptionSoup = read_file(descriptionFile, createLog, logFile)
  211. # description flags
  212. doParseDescription = descriptionSoup is not None
  213. doPersistRecord = False
  214. doMoveDescription = False
  215. rmm = []
  216. if doParseDescription:
  217. rmm = parse_description(forum, descriptionFile, descriptionSoup, createLog, logFile)
  218. doPersistRecord = rmm is not None
  219. else:
  220. readDescriptionError = True
  221. parseDescriptionError = True
  222. if doPersistRecord:
  223. # Combining the information from Listing and Description Pages
  224. rec = mergePages(rmm, rec)
  225. # Append to the list the classification of the topic
  226. rec.append(str(predict(rec[3], getPosts(rec[14]), language='sup_english')))
  227. # Persisting the information in the database
  228. persistSuccess = persist_record(url, rec, cur, con, createLog, logFile, listingFile, descriptionFile)
  229. doMoveDescription = persistSuccess
  230. else:
  231. parseDescriptionError = True
  232. if doMoveDescription:
  233. # move description files of completed folder
  234. moveSuccess = move_file(descriptionFile, createLog, logFile)
  235. if not moveSuccess:
  236. moveDescriptionError = True
  237. else:
  238. moveDescriptionError = True
  239. if not (readDescriptionError or parseDescriptionError or persistDescriptionError or moveDescriptionError):
  240. # move listing files of completed folder
  241. move_file(listingFile, createLog, logFile)
  242. if createLog:
  243. logFile.close()
  244. print("Parsing the " + forum + " forum and data classification done.")