Guest User

rutracker xml parser

a guest
Oct 19th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 26.55 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Author: yura_nn
  5. # License: GNU/GPL v3
  6.  
  7.  
  8. from bs4 import BeautifulSoup
  9. import hashlib
  10. import random
  11. import mysql.connector
  12. import time
  13. import math
  14. import re
  15.  
  16.  
  17. # Здесь нужно указать параметры подключения к базе данных.
  18. host = "localhost"
  19. database = "rutracker"
  20. user = "user_mysql"
  21. password = "password"
  22. phpbb_prefix = "rutrk_"
  23.  
  24. # Путь к файлу xml.
  25. backup_xml = "/path/to/file.xml"
  26. # Начальный идентификатор темы. Таблица topics, поле topic_id.
  27. topic_id = 1
  28. # Начальный идентификатор поста. Таблица posts, поле post_id.
  29. post_id = 1
  30. # Счетчик постов с начальным значением. Таблица users, поле user_posts.
  31. count_post = 1
  32. # Идентификатор форума, в котором будут размещаться темы торрентов. Посмотреть
  33. # можно в таблице forums.
  34. forum_id = 2
  35. # Идентификатор пользователя форума phpbb3. Таблица users, поле user_id.
  36. user_id = 2
  37. # Имя пользователя форума phpbb3.
  38. topic_user = "user_phpBB3"
  39.  
  40.  
  41. def parse_torrent(line_xml):
  42.     """ Функция парсит передаваемую строку. Выполняет нужные промежуточные
  43.    действия. А затем формирует словарь, содержащий необходимые значения и
  44.    возвращает его. """
  45.     soup = BeautifulSoup(line_xml, "xml")
  46.     torrent_all = soup.findAll("torrent")
  47.     torrent_id = torrent_all[0]["id"]
  48.     registred_at = torrent_all[0]["registred_at"]
  49.     torrent_size = torrent_all[0]["size"]
  50.     title = soup.title.string
  51.     title = str(title)
  52.     torrent_hash = torrent_all[1]["hash"]
  53.     tracker_id = torrent_all[1]["tracker_id"]
  54.     forum_id_old = soup.forum["id"]
  55.     forum_name = soup.forum.string
  56.     # Создание магнет ссылок.
  57.     magnet_dht_only = create_magnet_dht(torrent_hash)
  58.     magnet_rutracker = create_magnet_rutracker(torrent_hash)
  59.     # Добавление bbcode code для магнет ссылок.
  60.     magnet_dht_only = "[br]" + "Магнет ссылка (только DHT): " + '\n' + \
  61.                       "[code]" + magnet_dht_only + "[/code]" + '\n'
  62.     magnet_rutracker = "[br]" + "Магнет ссылка (с bt*.t-ru.org): " + '\n' + \
  63.                        "[code]" + magnet_rutracker + "[/code]" + '\n'
  64.     # Добавление bbcode url для торрент линка.
  65.     hash_string = "[br]" + "Хеш раздачи:" + '\n' + "[code]" + \
  66.                   torrent_hash + "[/code]" + '\n'
  67.     data_torrent = "Дата создания раздачи: " + registred_at + '\n'
  68.     post_text = soup.content.string
  69.     # Добавление даты создания раздачи, магнет ссылок, и значения хеша раздачи
  70.     # прямо в пост.
  71.     post_text = post_text + '\n' + magnet_rutracker
  72.     post_text = post_text + magnet_dht_only
  73.     post_text = post_text + hash_string
  74.     post_text = post_text + data_torrent
  75.     # Конвертирование текста поста в формат сообщений phpbb.
  76.     post_text = convert_post_text(post_text)
  77.     # В таблице базы данных нужно указать хеш-сумму сообщения.
  78.     post_checksum = post_hash(post_text)
  79.     # Идентификатор bbcode для поста.
  80.     bbcode_uid = random_id()
  81.     # Здесь добавляется значение текущего времени.
  82.     time_post = math.floor(time.time())
  83.     post_table_string = {
  84.         "torrent_id": torrent_id,
  85.         "title": title,
  86.         "post_text": post_text,
  87.         "post_checksum": post_checksum,
  88.         "bbcode_uid": bbcode_uid,
  89.         "time_post": time_post,
  90.         "torrent_size": torrent_size,
  91.         "tracker_id": tracker_id,
  92.         "forum_id_old": forum_id_old,
  93.         "forum_name": forum_name
  94.     }
  95.     return post_table_string
  96.  
  97.  
  98. def add_post_to_base(post_table_string):
  99.     """ Функция заносит информацию о торренте в базу данных. """
  100.     global topic_id
  101.     global post_id
  102.     global count_post
  103.     # Соединение с базой данных.
  104.     cnx = mysql.connector.connect(host=host,
  105.                                   database=database,
  106.                                   user=user,
  107.                                   password=password)
  108.     cursor = cnx.cursor()
  109.     # Создание новой строки в таблице тем.
  110.     part_query = "INSERT INTO " + phpbb_prefix + "topics "
  111.     query = part_query + "(topic_id,forum_id,icon_id,topic_attachment," + \
  112.             "topic_reported,topic_title,topic_poster,topic_time," + \
  113.             "topic_time_limit,topic_views,topic_status,topic_type," + \
  114.             "topic_first_post_id,topic_first_poster_name," + \
  115.             "topic_first_poster_colour,topic_last_post_id," + \
  116.             "topic_last_poster_id,topic_last_poster_name," + \
  117.             "topic_last_poster_colour,topic_last_post_subject," + \
  118.             "topic_last_post_time,topic_last_view_time,topic_moved_id," + \
  119.             "topic_bumped,topic_bumper,poll_title,poll_start,poll_length," + \
  120.             "poll_max_options,poll_last_vote,poll_vote_change," + \
  121.             "topic_visibility,topic_delete_time,topic_delete_reason," + \
  122.             "topic_delete_user,topic_posts_approved," + \
  123.             "topic_posts_unapproved,topic_posts_softdeleted) " + \
  124.             "VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s," + \
  125.             "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
  126.     data = (topic_id, forum_id, 0, 0, 0, post_table_string["title"],
  127.             user_id, post_table_string["time_post"], 0, 1, 0, 0, topic_id,
  128.             topic_user, "AA0000", topic_id, user_id, topic_user, "AA0000",
  129.             post_table_string["title"], post_table_string["time_post"],
  130.             post_table_string["time_post"], 0, 0, 0, '', 0, 0, 1, 0, 0, 1, 0,
  131.             '', 0, 1, 0, 0)
  132.     cursor.execute(query, data)
  133.     # Создание новой строки в таблице постов.
  134.     part_query = "INSERT INTO " + phpbb_prefix + "posts "
  135.     query = part_query + "(post_id,topic_id,forum_id,poster_id,icon_id," + \
  136.             "poster_ip,post_time,post_reported,enable_bbcode," + \
  137.             "enable_smilies,enable_magic_url,enable_sig,post_username," + \
  138.             "post_subject,post_text,post_checksum,post_attachment, " + \
  139.             "bbcode_bitfield,bbcode_uid,post_postcount,post_edit_time," + \
  140.             "post_edit_reason,post_edit_user,post_edit_count," + \
  141.             "post_edit_locked,post_visibility,post_delete_time," + \
  142.             "post_delete_reason, post_delete_user) " + \
  143.             "VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s," + \
  144.             "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
  145.     data = (post_id, topic_id, forum_id, user_id, 0, "127.0.0.1",
  146.             post_table_string["time_post"], 0, 1, 1, 1, 1, topic_user,
  147.             post_table_string["title"], post_table_string["post_text"],
  148.             post_table_string["post_checksum"], 0, '',
  149.             post_table_string["bbcode_uid"], 1, 0, '', 0, 0, 0, 1, 0, '', 0)
  150.     cursor.execute(query, data)
  151.     # Создание новой строки в таблице topics_posted. Здесь при каждом новом
  152.     # посте должна быть добавлена запись.
  153.     part_query = "INSERT INTO " + phpbb_prefix + "topics_posted "
  154.     query = part_query + "(user_id,topic_id,topic_posted) VALUES (%s,%s,%s)"
  155.     data = (user_id, topic_id, 1)
  156.     cursor.execute(query, data)
  157.     # Изменение данных в таблице users.
  158.     part_query = "UPDATE " + phpbb_prefix + "users "
  159.     # Время последнего визита пользователя.
  160.     query = part_query + "SET user_lastvisit = %s WHERE user_id = %s"
  161.     data = (post_table_string["time_post"], user_id)
  162.     cursor.execute(query, data)
  163.     # Время последнего поста пользователя.
  164.     query = part_query + "SET user_lastpost_time = %s WHERE user_id = %s"
  165.     data = (post_table_string["time_post"], user_id)
  166.     cursor.execute(query, data)
  167.     # Количество постов пользователя.
  168.     query = part_query + "SET user_posts = %s WHERE user_id = %s"
  169.     data = (count_post, user_id)
  170.     cursor.execute(query, data)
  171.     # Изменение данных в таблице forums.
  172.     part_query = "UPDATE " + phpbb_prefix + "forums "
  173.     # ID последнего поста.
  174.     query = part_query + "SET forum_last_post_id = %s WHERE forum_id = %s"
  175.     data = (post_id, forum_id)
  176.     cursor.execute(query, data)
  177.     # Название последней темы.
  178.     query = part_query + "SET forum_last_post_subject = %s WHERE forum_id = %s"
  179.     data = (post_table_string["title"], forum_id)
  180.     cursor.execute(query, data)
  181.     # ID последнего пользователя, добавившего пост.
  182.     query = part_query + "SET forum_last_poster_id = %s WHERE forum_id = %s"
  183.     data = (user_id, forum_id)
  184.     cursor.execute(query, data)
  185.     # Ник последнего пользователя, добавившего пост.
  186.     query = part_query + "SET forum_last_poster_name = %s WHERE forum_id = %s"
  187.     data = (topic_user, forum_id)
  188.     cursor.execute(query, data)
  189.     # Время последнего поста.
  190.     query = part_query + "SET forum_last_post_time = %s WHERE forum_id = %s"
  191.     data = (post_table_string["time_post"], forum_id)
  192.     cursor.execute(query, data)
  193.     # Количество разрешенных постов.
  194.     query = part_query + "SET forum_posts_approved = %s WHERE forum_id = %s"
  195.     data = (count_post, forum_id)
  196.     cursor.execute(query, data)
  197.     # Количество разрешенных тем. Так как количество тем в данном случае равно
  198.     # количеству постов, то в качестве значения добавляется счетчик постов.
  199.     query = part_query + "SET forum_topics_approved = %s WHERE forum_id = %s"
  200.     data = (count_post, forum_id)
  201.     cursor.execute(query, data)
  202.     # Изменение данных в таблице forums_track. Она содержит информацию о том,
  203.     # что пользователь добавил сообщение в определенное время, для
  204.     # определенного форума. В таблице одна строка, поэтому условия не нужны.
  205.     part_query = "UPDATE " + phpbb_prefix + "forums_track "
  206.     query = part_query + "SET user_id = %s"
  207.     data = (user_id,)
  208.     cursor.execute(query, data)
  209.     query = part_query + "SET forum_id = %s"
  210.     data = (forum_id,)
  211.     cursor.execute(query, data)
  212.     query = part_query + "SET mark_time = %s"
  213.     data = (post_table_string["time_post"],)
  214.     cursor.execute(query, data)
  215.     cnx.commit()
  216.     cursor.close()
  217.     cnx.close()
  218.     topic_id += 1
  219.     post_id += 1
  220.     count_post += 1
  221.  
  222.  
  223. def create_magnet_dht(torrent_hash):
  224.     """ Функция создает только DHT магнет линк для раздачи рутрекера. """
  225.     part_begin = "magnet:?xt=urn:btih:"
  226.     magnet_link = part_begin + torrent_hash
  227.     return magnet_link
  228.  
  229.  
  230. def create_magnet_rutracker(torrent_hash):
  231.     """ Функция создает магнет линк для раздачи рутрекера, который имеет связь
  232.    с различными адресами bt*.t-ru.org. """
  233.     part_begin = "magnet:?xt=urn:btih:"
  234.     part_end = [
  235.         "&tr=http%3A%2F%2Fbt.t-ru.org%2Fann%3Fmagnet",
  236.         "&tr=http%3A%2F%2Fbt2.t-ru.org%2Fann%3Fmagnet",
  237.         "&tr=http%3A%2F%2Fbt3.t-ru.org%2Fann%3Fmagnet",
  238.         "&tr=http%3A%2F%2Fbt4.t-ru.org%2Fann%3Fmagnet"
  239.     ]
  240.     number_element = random.randrange(0, 4, 1)
  241.     magnet_link = part_begin + torrent_hash + part_end[number_element]
  242.     return magnet_link
  243.  
  244.  
  245. def post_hash(string):
  246.     """ Функция рассчитывает и возвращает хеш-сумму md5 переданной строки. """
  247.     string = string.encode('utf-8')
  248.     hash_string = hashlib.md5(string).hexdigest()
  249.     return hash_string
  250.  
  251.  
  252. def random_id():
  253.     """ Функция генерирует случайный цифро-буквенный идентификатор. """
  254.     symbols_list = "qwertyuiopasdfghjklzxcvbnm1234567890"
  255.     count_loop = random.randrange(1, 8, 1)
  256.     # Произвольное увеличение заданной строки символов.
  257.     for i in range(count_loop):
  258.         symbols_list = symbols_list + symbols_list
  259.     symbols_list = list(symbols_list)
  260.     random.shuffle(symbols_list)
  261.     destination_id = ''
  262.     # Собственно создание идентификатора.
  263.     for i in range(8):
  264.         destination_id = destination_id + symbols_list[i]
  265.     return destination_id
  266.  
  267.  
  268. def convert_post_text(post_text):
  269.     """ В базе данных текст постов для phpbb лежит в своем собственном формате.
  270.    Эта функция преобразует текст поста в необходимый формат. """
  271.     # Пост сначала делится на отдельные строки для того, чтобы добавить в
  272.     # каждую строку элемент <br/>. Если этого не сделать, то форматирование
  273.     # поста поплывет.
  274.     post_text = post_text.splitlines()
  275.     destination_string = ''
  276.     i = 0
  277.     len_post_text = len(post_text)
  278.     while i < len_post_text:
  279.         new_str = post_text[i] + "<br/>" + '\n'
  280.         del post_text[i]
  281.         post_text.insert(i, new_str)
  282.         destination_string = destination_string + post_text[i]
  283.         i += 1
  284.     # Дальше уже все действия выполняются с одной большой строкой.
  285.     post_text = destination_string
  286.     # Удаление элементов img.
  287.     post_text = re.sub(
  288.         r"(\[[iI][mM][gG]\][\d\s\w\W\n_]{1,}?\[/[iI][mM][gG]\])", '',
  289.         post_text)
  290.     post_text = re.sub(
  291.         r"(\[[iI][mM][gG]=[rR][iI][gG][hH][tT]\][\d\s\w\W\n_]{1,}?\[/[iI][mM][gG]\])",
  292.         '', post_text)
  293.     post_text = re.sub(
  294.         r"(\[[iI][mM][gG]=[lL][eE][fF][tT]\][\d\s\w\W\n_]{1,}?\[/[iI][mM][gG]\])",
  295.         '', post_text)
  296.     post_text = "<r>" + '\n' + post_text + "</r>"
  297.     # Поиск list.
  298.     if re.search(r"(\[[lL][iI][sS][tT]=?1?\])", post_text) is not None:
  299.         # Создание списка соответствий существующих списков в теме.
  300.         list_value = re.findall(
  301.             r"(\[[lL][iI][sS][tT]=?1?\][\d\s\w\W\n_]{1,}?\[/[lL][iI][sS][tT]\])",
  302.             post_text)
  303.         list_value = check_list(list_value)
  304.         for i in list_value:
  305.             # Регулярное выражение для извлечения начального тега list.
  306.             tag_begin = re.search(r"(\[[lL][iI][sS][tT]=?1?](<[br]/>)?)",
  307.                                   i)
  308.             tag_begin = tag_begin.group(0)
  309.             tag_begin = re.sub(r"(\n?(<br/>)?)", '', tag_begin)
  310.             tag_begin = "<LIST><s>" + tag_begin + "</s>" + "<br/>" + '\n'
  311.             tag_end = "<e>[/list]</e></LIST>"
  312.             # Регулярное выражение для извлечения элементов списка.
  313.             list_elements = re.findall(r"(\[\*\].{1,})", i)
  314.             list_elements = check_list(list_elements)
  315.             destination_value = ''
  316.             for n in list_elements:
  317.                 new_str = re.sub(r"(\n?(<br/>)?)", '', n)
  318.                 new_str = re.sub(r"(\[\*\])", '', new_str)
  319.                 new_str = "<LI><s>[*]</s>" + new_str + "</LI>" + '\n'
  320.                 destination_value = destination_value + new_str
  321.             destination_value = re.sub(r"(\[/[lL][iI][sS][tT]\])", '',
  322.                                        destination_value)
  323.             destination_value = tag_begin + destination_value + tag_end
  324.             post_text = post_text.replace(i, destination_value)
  325.     # Поиск font.
  326.     if re.search(r"(\[[fF][oO][nN][tT]=)", post_text) is not None:
  327.         list_value = re.findall(
  328.             r"(\[[fF][oO][nN][tT]=[\'\"]?[\'\"]?[a-zA-Z0-9^$\(\),.\s\-_:\?/=#&!\*<>+]{1,}[\'\"]?[\'\"]?\])",
  329.             post_text)
  330.         list_value = check_list(list_value)
  331.         for i in list_value:
  332.             destination_value = re.sub(r"(\[[fF][oO][nN][tT]=[\'\"]?)",
  333.                                        '', i)
  334.             destination_value = re.sub(r"([\'\"]?\])", '', destination_value)
  335.             destination_value = '<FONT font="' + destination_value \
  336.                                                + '"><s>' + i + "</s>"
  337.             post_text = post_text.replace(i, destination_value)
  338.     # Поиск "color=".
  339.     if re.search(r"(\[[cC][oO][lL][oO][rR]=)", post_text) is not None:
  340.         list_value = re.findall(
  341.             r"(\[[cC][oO][lL][oO][rR]=[\'\"]?[#0-9a-zA-Z]{1,}[\'\"]?\])",
  342.             post_text)
  343.         list_value = check_list(list_value)
  344.         for i in list_value:
  345.             destination_value = re.sub(r"(\[[cC][oO][lL][oO][rR]=[\'\"]?)",
  346.                                        '', i)
  347.             destination_value = re.sub(r"([\'\"]?\])", '', destination_value)
  348.             destination_value = '<COLOR color="' + destination_value \
  349.                                                + '"><s>' + i + "</s>"
  350.             post_text = post_text.replace(i, destination_value)
  351.     # Поиск "size=".
  352.     if re.search(r"(\[[sS][iI][zZ][eE]=)", post_text) is not None:
  353.         list_value = re.findall(
  354.             r"(\[[sS][iI][zZ][eE]=[\"\']?[0-9]{,3}[\"\']?\])", post_text)
  355.         list_value = check_list(list_value)
  356.         for i in list_value:
  357.             destination_value = re.sub(r"(\[[sS][iI][zZ][eE]=[\'\"]?)", '', i)
  358.             destination_value = re.sub(r"([\'\"]?\])", '', destination_value)
  359.             destination_value = '<SIZE size="' + destination_value + \
  360.                                              '"><s>' + i + "</s>"
  361.             post_text = post_text.replace(i, destination_value)
  362.     # Тег "url=".
  363.     if re.search(r"(\[[uU][rR][lL]=)", post_text) is not None:
  364.         list_value = re.findall(
  365.             r"(\[[uU][rR][lL]=[\']?[-a-zA-Zа-яА-ЯёЁ0-9\.\/\:\?=#&@;_%\(\),+!\*<>]{1,}[\']?\])",
  366.             post_text)
  367.         list_value = check_list(list_value)
  368.         for i in list_value:
  369.             destination_value = re.sub(r"(\[[uU][rR][lL]=[\'\"]?)", '', i)
  370.             destination_value = re.sub(r"([\'\"]?\])", '', destination_value)
  371.             destination_value = '<URL url="' + destination_value + '"><s>' + \
  372.                                            i + "</s>"
  373.             post_text = post_text.replace(i, destination_value)
  374.     # Тег spoiler=".
  375.     if re.search(r"(\[[sS][pP][oO][iI][lL][eE][rR]=)",
  376.                  post_text) is not None:
  377.         list_value = re.findall(
  378.             r"(\[[sS][pP][oO][iI][lL][eE][rR]=[\"].{1,}[\"]\])",
  379.             post_text)
  380.         list_value = check_list(list_value)
  381.         for i in list_value:
  382.             destination_value = re.sub(r"(\[[sS][pP][oO][iI][lL][eE][rR]=[\"])",
  383.                                        '', i)
  384.             destination_value = re.sub(r"([\"]\])", '', destination_value)
  385.             destination_value = "<SPOILER spoiler=" + '"' + \
  386.                                                     destination_value + '"' + \
  387.                                                     '><s>' + '[spoiler="' + \
  388.                                                     destination_value + '"' + \
  389.                                                     ']' + "</s>"
  390.             post_text = post_text.replace(i, destination_value)
  391.     # Тег align=".
  392.     if re.search(r"(\[[aA][lL][iI][gG][nN]=)", post_text) is not None:
  393.         list_value = re.findall(
  394.             r"(\[[aA][lL][iI][gG][nN]=[\'\"]?[a-zA-Z]{1,}[\'\"]?\])",
  395.             post_text)
  396.         list_value = check_list(list_value)
  397.         for i in list_value:
  398.             destination_value = re.sub(r"(\[[aA][lL][iI][gG][nN]=[\'\"]?)",
  399.                                        '', i)
  400.             destination_value = re.sub(r"([\'\"]?\])", '', destination_value)
  401.             destination_value = '<ALIGN align="' + destination_value + \
  402.                                                '"><s>[align=' \
  403.                                                + destination_value + \
  404.                                                "]</s>"
  405.             post_text = post_text.replace(i, destination_value)
  406.     # Элемент quote.
  407.     if re.search(r"(\[[qQ][uU][oO][tT][eE]\])", post_text) is not None:
  408.         post_text = re.sub(r"(\[[qQ][uU][oO][tT][eE]\])",
  409.                            "<QUOTE><s>[quote]</s>", post_text)
  410.     if re.search(r"(\[/[qQ][uU][oO][tT][eE]\])", post_text) is not None:
  411.         post_text = re.sub(r"(\[/[qQ][uU][oO][tT][eE]\])",
  412.                            "<e>[/quote]</e></QUOTE>", post_text)
  413.     # Элемент code.
  414.     if re.search(r"(\[[cC][oO][dD][eE]\])", post_text) is not None:
  415.         post_text = re.sub(r"(\[[cC][oO][dD][eE]\])",
  416.                            "<CODE><s>[code]</s>", post_text)
  417.     if re.search(r"(\[/[cC][oO][dD][eE]\])", post_text) is not None:
  418.         post_text = re.sub(r"(\[/[cC][oO][dD][eE]\])",
  419.                            "<e>[/code]</e></CODE>", post_text)
  420.     # Элемент pre.
  421.     if re.search(r"(\[[pP][rR][eE]\])", post_text) is not None:
  422.         post_text = re.sub(r"(\[[pP][rR][eE]\])",
  423.                            "<PRE><s>[pre]</s>", post_text)
  424.     if re.search(r"(\[/[pP][rR][eE]\])", post_text) is not None:
  425.         post_text = re.sub(r"(\[/[pP][rR][eE]\])",
  426.                            "<e>[/pre]</e></PRE>", post_text)
  427.     # Элемент b.
  428.     if re.search(r"(\[[bB]\])", post_text) is not None:
  429.         post_text = re.sub(r"(\[[bB]\])", "<B><s>[b]</s>", post_text)
  430.     if re.search(r"(\[/[bB]\])", post_text) is not None:
  431.         post_text = re.sub(r"(\[/[bB]\])", "<e>[/b]</e></B>", post_text)
  432.     # Элемент i.
  433.     if re.search(r"(\[[iI]\])", post_text) is not None:
  434.         post_text = re.sub(r"(\[[iI]\])", "<I><s>[i]</s>", post_text)
  435.     if re.search(r"(\[/[iI]\])", post_text) is not None:
  436.         post_text = re.sub(r"(\[/[iI]\])", "<e>[/i]</e></I>", post_text)
  437.     # Элемент u.
  438.     if re.search(r"(\[[uU]\])", post_text) is not None:
  439.         post_text = re.sub(r"(\[[uU]\])", "<U><s>[u]</s>", post_text)
  440.     if re.search(r"(\[/[uU]\])", post_text) is not None:
  441.         post_text = re.sub(r"(\[/[uU]\])", "<e>[/u]</e></U>", post_text)
  442.     # Элемент br.
  443.     if re.search(r"(\[[bB][rR]\])", post_text) is not None:
  444.         post_text = re.sub(r"(\[[bB][rR]\])",
  445.                            "<BR><s>[br]</s><e>[/br]</e></BR>", post_text)
  446.     if re.search(r"(\[[hH][rR]\])", post_text) is not None:
  447.         post_text = re.sub(r"(\[[hH][rR]\])",
  448.                            "<HR><s>[hr]</s><e>[/hr]</e></HR>", post_text)
  449.     # Для спойлера без описания.
  450.     if re.search(r"(\[[sS][pP][oO][iI][lL][eE][rR]\])", post_text) \
  451.        is not None:
  452.         post_text = re.sub(r"(\[[sS][pP][oO][iI][lL][eE][rR]\])",
  453.                            "<SPOILER><s>[spoiler]</s>", post_text)
  454.     if re.search(r"(\[/[sS][pP][oO][iI][lL][eE][rR]\])", post_text) \
  455.        is not None:
  456.         post_text = re.sub(r"(\[/[sS][pP][oO][iI][lL][eE][rR]\])",
  457.                            "<e>[/spoiler]</e></SPOILER>", post_text)
  458.     # Для завершающего тега size.
  459.     if re.search(r"(\[/[sS][iI][zZ][eE]\])", post_text) is not None:
  460.         post_text = re.sub(r"(\[/[sS][iI][zZ][eE]\])",
  461.                            "<e>[/size]</e></SIZE>", post_text)
  462.     # Для завершающего тега spoiler.
  463.     if re.search(r"(\[/[cC][oO][lL][oO][rR]\])", post_text) is not None:
  464.         post_text = re.sub(r"(\[/[cC][oO][lL][oO][rR]\])",
  465.                            "<e>[/color]</e></COLOR>", post_text)
  466.     # Для завершающего тега url.
  467.     if re.search(r"(\[/[uU][rR][lL]\])", post_text) is not None:
  468.         post_text = re.sub(r"(\[/[uU][rR][lL]\])",
  469.                            "<e>[/url]</e></URL>", post_text)
  470.     # Для завершающего тега align.
  471.     if re.search(r"(\[/[aA][lL][iI][gG][nN]\])", post_text) is not None:
  472.         post_text = re.sub(r"(\[/[aA][lL][iI][gG][nN]\])",
  473.                            "<e>[/align]</e></ALIGN>", post_text)
  474.     # Для завершающего тега font.
  475.     if re.search(r"(\[/[fF][oO][nN][tT]\])", post_text) is not None:
  476.         post_text = re.sub(r"(\[/[fF][oO][nN][tT]\])",
  477.                            "<e>[/font]</e></FONT>", post_text)
  478.     return post_text
  479.  
  480.  
  481. def check_list(list_value):
  482.     """ Когда используется список совпадения для замены тегов, нельзя, чтобы в
  483.    нем были повторяющиеся пункты, иначе замена может произойти в уже
  484.    замененном. Эта функция удаляет повторения. """
  485.     current_list = []
  486.     n = 0
  487.     len_list_value = len(list_value)
  488.     while n < len_list_value:
  489.         flag = False
  490.         for i in current_list:
  491.             if list_value[n] == i:
  492.                 flag = True
  493.         if flag is False:
  494.             current_list.append(list_value[n])
  495.         n += 1
  496.     return current_list
  497.  
  498.  
  499. def main():
  500.     # Каждая запись с торрентом преобразуется в свой маленький xml файл,
  501.     # который парсится дальше уже с помощью BeautifulSoup.
  502.     first_xml_string = '<?xml version="1.0" encoding="UTF-8"?>' + '\n'
  503.     other_xml_string = "<torrents>" + '\n'
  504.     last_xml_string = "</torrents>" + '\n'
  505.     line_xml = ''
  506.     fd = open(backup_xml, "r")
  507.     for line in fd:
  508.         if line.find("<torrent id") != -1:
  509.             line_xml = first_xml_string + other_xml_string
  510.         line_xml = line_xml + line
  511.         if line.find("</torrent") != -1:
  512.             line_xml = line_xml + last_xml_string
  513.             post_table_string = parse_torrent(line_xml)
  514.             add_post_to_base(post_table_string)
  515.     fd.close()
  516.  
  517.  
  518. if __name__ == "__main__":
  519.     main()
Add Comment
Please, Sign In to add comment