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.

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