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.

310 lines
12 KiB

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