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.

364 lines
14 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. __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. # determines if forum is russian, not really used now but maybe later
  17. def isRussianForum(forum):
  18. with open('russian_forums.txt') as f:
  19. forums = f.readlines()
  20. result = False
  21. for iforum in forums:
  22. iforum = iforum.replace('\n','')
  23. if iforum == forum:
  24. result = True
  25. break
  26. return result
  27. #tries to match description pages to listing pages by using a key made for every description page and every link in listing page
  28. #once verified and matched, the info is merged into a 'rec', which is returned
  29. #@param: detPage is a list of keys of valid pages, rec is the row of data of an instance
  30. #return: rec, row of data, that may have additional data added on after matching description to listing page
  31. def mergePages(rmm, rec):
  32. # key = u"Top:" + rec[1].upper().strip() + u" User:" + rec[5].upper().strip()
  33. # key = rec[16]
  34. print ("----------------- Matched: " + rec[3] + "--------------------")
  35. rec[9] = rmm[1]
  36. rec[10] = rmm[2]
  37. rec[11] = rmm[3]
  38. rec[12] = rmm[4]
  39. rec[13] = rmm[5]
  40. rec[14] = rmm[6]
  41. rec[15] = rmm[7]
  42. rec[16] = rmm[8]
  43. return rec
  44. #gets a string of posts and joins them together into one string to be put in the database as one string of text
  45. #@param: list of strings (the posts of a thread)
  46. #return: string containing the concatenation of all the strings
  47. def getPosts(posts):
  48. strPosts = ' '.join(posts)
  49. return strPosts.strip()
  50. #uses db connection , another program, methods to persists values to the correct categories
  51. #@param: row is the list of entries for this instance, cur is the db connection object
  52. def persist_data(url, row, cur):
  53. forum = create_forum(cur, row, url)
  54. board = create_board(cur, row, forum)
  55. author = create_user(cur, row, forum, 0)
  56. topic = create_topic(cur, row, forum, board, author)
  57. create_posts(cur, row, forum, board, topic)
  58. #main method for this program, what actually gets the parsed info from the parser, and persists them into the db
  59. #calls the different parser methods here depending on the type of html page
  60. def new_parse(forum, url, createLog):
  61. from Forums.Initialization.forums_mining import config, CURRENT_DATE
  62. print("Parsing The " + forum + " Forum and conduct data classification to store the information in the database.")
  63. # ini = time.time()
  64. # Connecting to the database
  65. con = connectDataBase()
  66. cur = con.cursor()
  67. # Creating the tables (The database should be created manually)
  68. create_database(cur, con)
  69. nError = 0
  70. lines = [] # listing pages
  71. lns = [] # description pages
  72. detPage = {} # first pages
  73. other = {} # other pages
  74. # Creating the log file for each Forum
  75. if createLog:
  76. if not os.path.exists("./" + forum + "/Logs/" + forum + "_" + CURRENT_DATE + ".log"):
  77. logFile = open("./" + forum + "/Logs/" + forum + "_" + CURRENT_DATE + ".log", "w")
  78. else:
  79. print("Files of the date " + CURRENT_DATE + " from the Forum " + forum +
  80. " were already read. Delete the referent information in the Data Base and also delete the log file"
  81. " in the _Logs folder to read files from this Forum of this date again.")
  82. raise SystemExit
  83. mainDir = os.path.join(config.get('Project', 'shared_folder'), "Forums/" + forum + "/HTML_Pages")
  84. # Reading the Listing Html Pages
  85. for fileListing in glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Listing", '*.html')):
  86. lines.append(fileListing)
  87. # Reading the Description Html Pages
  88. for fileDescription in glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Description", '*.html')):
  89. lns.append(fileDescription)
  90. # Parsing the Description Pages and put the tag's content into a dictionary (Hash table)
  91. for index, line2 in enumerate(lns):
  92. print("Reading description folder of '" + forum + "', file '" + os.path.basename(line2) + "', index= " + str(index + 1) + " ... " + str(len(lns)))
  93. try:
  94. html = codecs.open(line2.strip('\n'), encoding='utf8')
  95. soup = BeautifulSoup(html, "html.parser")
  96. html.close()
  97. except:
  98. try:
  99. html = open(line2.strip('\n'))
  100. soup = BeautifulSoup(html, "html.parser")
  101. html.close()
  102. except:
  103. nError += 1
  104. print("There was a problem to read the file " + line2 + " in the Description section!")
  105. if createLog:
  106. logFile.write(str(nError) + ". There was a problem to read the file " + line2 + " in the Description section!\n")
  107. continue
  108. try:
  109. if forum == "BestCardingWorld":
  110. rmm = bestcardingworld_description_parser(soup)
  111. elif forum == "Cardingleaks":
  112. rmm = cardingleaks_description_parser(soup)
  113. elif forum == "CryptBB":
  114. rmm = cryptBB_description_parser(soup)
  115. elif forum == "OnniForums":
  116. rmm = onniForums_description_parser(soup)
  117. elif forum == "Altenens":
  118. rmm = altenens_description_parser(soup)
  119. elif forum == "Procrax":
  120. rmm = procrax_description_parser(soup)
  121. elif forum == "Libre":
  122. rmm = libre_description_parser(soup)
  123. # key = u"Top:" + rmm[0].upper().strip() + u" User:" + rmm[2][0].upper().strip()
  124. key = u"Url:" + os.path.basename(line2).replace(".html", "")
  125. # check if "page1" exists at the end of a string
  126. # if yes add to first page directory if no add to other
  127. check = re.compile(r'page1$')
  128. if check.search(key):
  129. # print(key, 'is a first page\n')
  130. detPage[key] = {'rmm': rmm, 'files': [os.path.basename(line2)]}
  131. else:
  132. # print(key, 'is an other page\n')
  133. other[key] = {'rmm': rmm, 'filename': os.path.basename(line2)}
  134. except:
  135. nError += 1
  136. print("There was a problem to parse the file " + line2 + " in the Description section!")
  137. traceback.print_exc()
  138. if createLog:
  139. logFile.write(str(nError) + ". There was a problem to parse the file " + line2 + " in the Description section.\n")
  140. # goes through keys from detPage and other, checks if the keys match.
  141. # if yes adds other[key] values to detPage w/o overwritting
  142. for key in detPage.keys():
  143. for k in list(other.keys()):
  144. checkkey = str(key[4:])
  145. checkk = str(k[4:])
  146. if checkkey in checkk:
  147. detPage[key]['rmm'][1].extend(other[k]['rmm'][1])
  148. detPage[key]['rmm'][2].extend(other[k]['rmm'][2])
  149. detPage[key]['rmm'][3].extend(other[k]['rmm'][3])
  150. detPage[key]['rmm'][4].extend(other[k]['rmm'][4])
  151. detPage[key]['rmm'][5].extend(other[k]['rmm'][5])
  152. detPage[key]['rmm'][6].extend(other[k]['rmm'][6])
  153. detPage[key]['rmm'][7].extend(other[k]['rmm'][7])
  154. detPage[key]['rmm'][8].extend(other[k]['rmm'][8])
  155. detPage[key]['files'].append(other[k]['filename'])
  156. other.pop(k)
  157. # Parsing the Listing Pages and put the tag's content into a list
  158. for index, line1 in enumerate(lines):
  159. print("Reading listing folder of '" + forum + "', file '" + os.path.basename(line1) + "', index= " + str(index + 1) + " ... " + str(len(lines)))
  160. readError = False
  161. try:
  162. html = codecs.open(line1.strip('\n'), encoding='utf8')
  163. soup = BeautifulSoup(html, "html.parser")
  164. html.close()
  165. except:
  166. try:
  167. html = open(line1.strip('\n'))
  168. soup = BeautifulSoup(html, "html.parser")
  169. html.close()
  170. except:
  171. nError += 1
  172. print("There was a problem to read the file " + line1 + " in the Listing section!")
  173. if createLog:
  174. logFile.write(str(nError) + ". There was a problem to read the file " + line1 + " in the Listing section.\n")
  175. readError = True
  176. if not readError:
  177. parseError = False
  178. try:
  179. if forum == "BestCardingWorld":
  180. rw = bestcardingworld_listing_parser(soup)
  181. elif forum == "Cardingleaks":
  182. rw = cardingleaks_listing_parser(soup)
  183. elif forum == "CryptBB":
  184. rw = cryptBB_listing_parser(soup)
  185. elif forum == "OnniForums":
  186. rw = onniForums_listing_parser(soup)
  187. elif forum == "Altenens":
  188. rw = altenens_listing_parser(soup)
  189. elif forum == "Procrax":
  190. rw = procrax_listing_parser(soup)
  191. elif forum == "Libre":
  192. rw = libre_listing_parser(soup)
  193. except:
  194. nError += 1
  195. print("There was a problem to read the file " + line1 + " in the listing section!")
  196. traceback.print_exc()
  197. if createLog:
  198. logFile.write(
  199. str(nError) + ". There was a problem to read the file " + line1 + " in the Listing section.\n")
  200. parseError = True
  201. if not parseError:
  202. persistError = False
  203. moveError = False
  204. num_in_db = 0
  205. num_persisted_moved = 0
  206. for rec in rw:
  207. rec = rec.split(',')
  208. # print(rec)
  209. # key = u"Top:" + rec[1].upper().strip() + u" User:" + rec[5].upper().strip()
  210. key = u"Url:" + cleanLink(rec[6]) + "page1"
  211. # print(key)
  212. if key in detPage:
  213. # Combining the information from Listing and Description Pages
  214. rmm = detPage[key]['rmm']
  215. rec = mergePages(rmm, rec)
  216. # Append to the list the classification of the topic
  217. # if isRussianForum(forum):
  218. # rec.append(str(predict(rec[1], getPosts(rec[8]), language='sup_russian')))
  219. # else:
  220. # rec.append(str(predict(rec[1], getPosts(rec[8]), language='sup_english')))
  221. rec.append(str(predict(rec[3], getPosts(rec[14]), language='sup_english')))
  222. # Persisting the information in the database
  223. try:
  224. persist_data(url, tuple(rec), cur)
  225. con.commit()
  226. except:
  227. trace = traceback.format_exc()
  228. if trace.find("already exists") == -1:
  229. nError += 1
  230. print("There was a problem to persist the file " + detPage[key]['filename'] + " in the database!")
  231. if createLog:
  232. logFile.write(
  233. str(nError) + ". There was a problem to persist the file " + detPage[key]['filename'] + " in the database.\n")
  234. persistError = True
  235. con.rollback()
  236. if not persistError:
  237. # move description files of completed folder
  238. for filename in detPage[key]['files']:
  239. source = line2.replace(os.path.basename(line2), "") + filename
  240. destination = line2.replace(os.path.basename(line2), "") + r'Read/'
  241. try:
  242. shutil.move(source, destination)
  243. num_persisted_moved += 1
  244. except:
  245. print("There was a problem to move the file " + filename + " in the Description section!")
  246. nError += 1
  247. if createLog:
  248. logFile.write(
  249. str(nError) + ". There was a problem to move the file " + filename + " in the Description section!.\n")
  250. moveError = True
  251. # if the associated description page is not read or not parsed
  252. else:
  253. # query database
  254. # if the post already exists:
  255. # num_in_db += 1
  256. pass
  257. # if number of topics on listing page is equal to
  258. # the number of merged, persisted, and moved topics plus
  259. # the number of topics already in the database
  260. if not persistError and not moveError and len(rw) == (num_persisted_moved + num_in_db):
  261. # move listing file to completed folder
  262. source = line1
  263. destination = line1.replace(os.path.basename(line1), "") + r'Read/'
  264. try:
  265. shutil.move(source, destination)
  266. except:
  267. nError += 1
  268. print("There was a problem to move the file " + line1 + " in the Listing section!")
  269. if createLog:
  270. logFile.write(str(nError) + ". There was a problem to move the file " + line1 + " in the Listing section!.\n")
  271. if createLog:
  272. logFile.close()
  273. #end = time.time()
  274. #finalTime = float(end-ini)
  275. #print (forum + " Parsing Perfomed Succesfully in %.2f" %finalTime + "!")
  276. input("Parsing the " + forum + " forum and data classification done successfully. Press ENTER to continue\n")