├── conftest.py
├── assets
├── warnings.log
├── main.png
├── attachment_types.py
├── utils.py
└── storage.py
├── models
├── __init__.py
├── parsing.py
├── sender.py
└── post_creator.py
├── requirements.txt
├── config.py
├── main.py
├── README.md
├── tests
├── test_unit.py
└── consts.py
└── LICENSE
/conftest.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/assets/warnings.log:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/assets/main.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Aragroth/repost-vk-2-tg/HEAD/assets/main.png
--------------------------------------------------------------------------------
/models/__init__.py:
--------------------------------------------------------------------------------
1 | from .parsing import Parser
2 | from .post_creator import Post
3 | from .sender import TelegramSender
4 |
--------------------------------------------------------------------------------
/assets/attachment_types.py:
--------------------------------------------------------------------------------
1 | ERROR = 'error'
2 | LINK = 'link'
3 | LINK_YOUTUBE = 'link-youtube'
4 | PHOTO = 'photo'
5 | DOC = 'doc'
6 | VIDEO_ALBUM = 'video_album'
7 | VIDEO_LARGE = 'video_separate'
8 | ANIMATION = 'animation'
9 |
--------------------------------------------------------------------------------
/assets/utils.py:
--------------------------------------------------------------------------------
1 | from dataclasses import dataclass
2 |
3 |
4 | @dataclass
5 | class Video:
6 | media: bytes
7 | duration: int
8 | width: int
9 | height: int
10 |
11 |
12 | @dataclass
13 | class AttachmentParts:
14 | album_sendings: list
15 | videos: list
16 | docs: list
17 | animations: list
18 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | atomicwrites==1.4.0
2 | attrs==19.3.0
3 | certifi==2020.6.20
4 | chardet==3.0.4
5 | colorama==0.4.3
6 | idna==2.10
7 | importlib-metadata==1.7.0
8 | more-itertools==8.4.0
9 | packaging==20.4
10 | pluggy==0.13.1
11 | py==1.10.0
12 | pyparsing==2.4.7
13 | pytest==5.4.3
14 | requests==2.24.0
15 | six==1.15.0
16 | urllib3==1.26.5
17 | vk-api==11.8.0
18 | wcwidth==0.2.5
19 | youtube-dl==2020.6.16.1
20 | zipp==3.1.0
21 |
--------------------------------------------------------------------------------
/config.py:
--------------------------------------------------------------------------------
1 | config_data = {
2 | # Ссылка на телеграмм-канал, где подключён бот
3 | 'chat_link': "@bla-bla",
4 |
5 | # Телеграм токен бота, которого вы добавили в сообщество
6 | 'telegram_bot_token': "telegram:token",
7 |
8 | # Можно использовать любой токен ВК
9 | 'vk_service_token': "your token",
10 |
11 | # Айди группы, чьи посты надо анализировать
12 | 'vk_group_id': -11111111,
13 |
14 | # Если хотите репостить все посты, оставьте пустым
15 | 'key_tag': "#tag@gruop",
16 |
17 | # Сколько последних постов будет анализироваться каждый раз
18 | 'posts_count': 10,
19 |
20 | # Сколько секунд проходит между каждым анализом.
21 | # Слишком малое значение исчерпает лимит API
22 | 'sleep_time_seconds': 240
23 | }
24 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | import time
2 |
3 | from assets.storage import Store
4 | from config import config_data as config
5 |
6 | from models import TelegramSender, Parser, Post
7 |
8 | ids_of_parsed_posts = Store('ids')
9 |
10 | key_tag = config['key_tag']
11 | vk_token = config['vk_service_token']
12 | group_to_analyze = config['vk_group_id']
13 |
14 |
15 | telegram_sender = TelegramSender(config['telegram_bot_token'], config['chat_link'])
16 | parser = Parser(vk_token, group_to_analyze, key_tag, config['sleep_time_seconds'],
17 | ids_of_parsed_posts, config['posts_count'])
18 |
19 | for current_post in parser.get_posts_to_send():
20 |
21 | post = Post(current_post, group_to_analyze, vk_token)
22 | post.refactor(key_tag)
23 | post.parse_attachments()
24 |
25 | ids_of_parsed_posts.append(current_post['id'])
26 | # Индексируем пост как отправленный сейчас, чтобы в случае ошибок
27 | # telegram_sender пост не пытался отправить бесконечное число раз
28 |
29 | telegram_sender.send_post_as_messages(post)
30 |
--------------------------------------------------------------------------------
/models/parsing.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | from assets.storage import Store
4 | import vk_api
5 | import time
6 |
7 |
8 | class Parser:
9 |
10 | def __init__(self, vk_token: str, group_to_analyze: int, key_tag: str, sleep_time: int,
11 | already_send_posts: Store, posts_analyze_count: int):
12 | vk_session = vk_api.VkApi(token=vk_token)
13 | self.vk = vk_session.get_api()
14 |
15 | self.already_send = already_send_posts
16 | self.tag = key_tag
17 | self.sleep_time = sleep_time
18 | self.posts_count = posts_analyze_count
19 | self.group_id = group_to_analyze
20 |
21 | def get_posts_to_send(self) -> dict:
22 | """
23 | Просматривает последние "self.post_count" постов и
24 | возвращает те, которые ещё не обрабатывались
25 |
26 | :return: Словарь с информацией о каждом посте
27 | """
28 |
29 | while True:
30 | last_posts = self.vk.wall.get(owner_id=self.group_id, count=self.posts_count)
31 | for post in last_posts['items']:
32 | if not self.already_send.contains(post['id']) and self.tag in post['text']:
33 | yield post
34 |
35 | # Я не хочу добавлять каждый пост без "тега-ключа" в список обработанных,
36 | # потому что человек может захотеть позднее сделать перепост данного
37 | # поста в тг. Для этого ему будет достаточно отредактировать пост и добавить тег
38 |
39 | # TODO лог в консоль, если привышен лимит api
40 | # TODO если привышен лимит api, то заснуть до следующего дня
41 |
42 | time.sleep(self.sleep_time)
43 |
--------------------------------------------------------------------------------
/assets/storage.py:
--------------------------------------------------------------------------------
1 | import bisect
2 | import pickle
3 | import os.path
4 | import random
5 |
6 |
7 | class Store:
8 | """
9 | Storage with binary search/adding, that
10 | saves itself after each change action
11 | """
12 |
13 | def __init__(self, name):
14 | self.name = name
15 | self._store = []
16 |
17 | if not os.path.isfile(f'assets/{self.name}.bin'):
18 | self.save_store(clear=True)
19 |
20 | self.load_store()
21 |
22 | def save_store(self, clear=False):
23 | """ clear=True is also equal to create_store """
24 |
25 | with open(f'assets/{self.name}.bin', 'wb') as fp:
26 | pickle.dump([] if clear else self._store, fp)
27 |
28 | def load_store(self):
29 | with open(f'assets/{self.name}.bin', 'rb') as fp:
30 | self._store = pickle.load(fp)
31 |
32 | def assign_list(self, data: list):
33 | self._store = list(data)
34 | self.save_store()
35 |
36 | def append(self, number):
37 | if not self.contains(number):
38 | bisect.insort(self._store, number)
39 | self.save_store()
40 |
41 | def clear(self):
42 | self._store = []
43 | self.save_store(clear=True)
44 |
45 | def contains(self, elem):
46 | self.load_store()
47 |
48 | index = bisect.bisect_left(self._store, elem)
49 | if index < len(self._store):
50 | return self._store[index] == elem
51 | return False
52 |
53 | def pop_random(self):
54 | random_item_ind = random.randint(0, len(self._store) - 1)
55 | random_item = self._store[random_item_ind]
56 | del self._store[random_item_ind]
57 | self.save_store()
58 |
59 | return random_item
60 |
61 | def __len__(self):
62 | return len(self._store)
63 |
64 | def __getitem__(self, key):
65 | return self._store[key]
66 |
67 | def __repr__(self):
68 | return str(self._store)
69 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Авто-репост из Vkontakte в Telegram
2 | 
3 |
4 | ### Как это работает?
5 | Бот парсит последние (поумолчанию 10) посты у группы из ВКонтакте. Если пост содержит "ключевой тег", который
6 | задаётся пользователем в настройках, то будут скачаны вложения поста, а текст будет распарсен, отрефакторен и после
7 | этого отправлен в телеграмм канал со всеми вложениями. Также ID отправленных постов будут сохранены в файле, поэтому при перезапуске бота
8 | он не будет заново отправлять уже обработанные посты. Цель бота - отказоустойчивость, поэтому при ошибках анализа постов
9 | (которые могут чаще всего произойти во вложениях), бот просто пропустит эти данные и запишет Warning в лог-файл **assets/warnings.log**
10 | * **Как запустить бота?** Укажите свои настройки в файле **config.py**, а затем в терминале выполните команду
11 | ```
12 | python3 main.py
13 | ```
14 | * **Как очистить хранилище обработанных постов?** Вы можете удалить файл **assets/ids.bin**. Либо же выполнить данный пайтон код:
15 | ```python
16 | from assets.storage import Store
17 |
18 | Store('ids').clear()
19 | ```
20 | * **Как мне делать репост всех постов, а не только по ключевому-тегу?** Просто оставьте поле **key_tag** в файле настроек **config.py** равным пустой строке
21 | ## Зависимости
22 | ```
23 | pip install -r requirements.txt
24 | ```
25 | Также понадобится библиотека FFMPEG для сжатия видео. На Linux:
26 | ```
27 | sudo apt install ffmpeg
28 | ```
29 | > Мой pull request на pyTelegramBotAPI уже мерджанули, но релизная версия не вышла. Поэтому telebot надо устанавливать
30 | > напрямую из их github репозитория
31 | >```
32 | >pip install git+https://github.com/eternnoir/pyTelegramBotAPI#egg=telebot
33 | >```
34 | ## Остальное
35 | ### TODO
36 | * Pull Request бибилиотеки pyTelegramBotAPI, где добавить в метод send_animations параметры width и height
37 | (и внести эти изменения в метод обработки GIF)
38 | * Улучшить связность метода **text_contains_link_of_attached_video** в классе Post
39 | * Метод **create_telegram_attachments** у класса Sender попробовать реализовать сразу в методе **parse_attachments** у класса Post
40 | * Добавить авто-тесты для класса Sender
41 | ### Тесты
42 | Запускаются из главной директории проекта командой **pytest**
43 |
--------------------------------------------------------------------------------
/tests/test_unit.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | from models.post_creator import Post
4 | from tests.consts import real_post, refactored_text
5 | import pytest
6 |
7 |
8 | def text_post(text):
9 | return Post({'text': text}, -41126705)
10 |
11 |
12 | @pytest.fixture
13 | def post_object():
14 | post_data = Post(real_post, -41126705)
15 | yield post_data
16 |
17 |
18 | @pytest.mark.parametrize(
19 | 'input_post, expected_post_text, key_tag',
20 | [
21 | pytest.param(text_post('#newspace@yandex'), '', '#newspace@yandex', id='key tag check'),
22 | pytest.param(text_post('#abc@yandex'), '#abc', '#newspace', id='no key tag in post'),
23 | pytest.param(text_post('#abc@yandex #tg@newspace\n @new'), '#abc \n @new', '#tg@newspace', id='many tags'),
24 | ],
25 | )
26 | def test_tags_refactor(input_post, expected_post_text, key_tag):
27 | input_post.refactor_tags(key_tag)
28 | assert input_post.text == expected_post_text
29 |
30 |
31 | @pytest.mark.parametrize(
32 | 'input_post, expected_post_text',
33 | [
34 | pytest.param(text_post('[id267990964|Dima Kurdoglo]'), 'Dima Kurdoglo', id='one person'),
35 | pytest.param(text_post('[id267990964|Dima Kurdoglo] и [id145462869|Alisa Zaripova]'),
36 | 'Dima Kurdoglo и Alisa Zaripova', id='multiple persons', ),
37 | ],
38 | )
39 | def test_refactor_user_links(input_post, expected_post_text):
40 | input_post.refactor_user_links()
41 | assert input_post.text == expected_post_text
42 |
43 |
44 | def test_full_refactor(post_object):
45 | post_object.refactor('#telegram@newspacepress')
46 | assert post_object.text == refactored_text
47 |
48 |
49 | def test_parse_attachments(post_object):
50 | post_object.parse_attachments()
51 | print(post_object.attachments_storage)
52 |
53 |
54 | @pytest.mark.skip(reason="Оно работает, но у меня медленный инет, чтобы каждый раз тестить :)")
55 | @pytest.mark.parametrize(
56 | 'post, real_list_of_links',
57 | [pytest.param(text_post(refactored_text), ['https://youtube.com/watch?v=zaSsO689d3w',
58 | 'https://youtube.com/watch?v=wrfzG_5IQyo']),
59 | pytest.param(text_post("а здесь нет ни каких ссылок на ютуб"), [])],
60 | )
61 | def test_get_youtube_links_from_text(post, real_list_of_links):
62 | links = post.get_youtube_links_from_text()
63 | assert links == real_list_of_links
64 |
65 |
66 | @pytest.mark.skip(reason="Оно работает, но у меня медленный инет, чтобы каждый раз тестить :)")
67 | @pytest.mark.parametrize(
68 | 'vk_link, youtube_link',
69 | [
70 | pytest.param("https://vk.com/video-41126705_456239239", 'https://www.youtube.com/watch?v=zaSsO689d3w'),
71 | pytest.param("https://vk.com/video-41126705_456239227", 'https://www.youtube.com/watch?v=bTQ-SmeLTl8'),
72 | pytest.param("https://vk.com/video-41126705_456239206", 'https://www.youtube.com/watch?v=527fb3-UZGo'),
73 |
74 | ],
75 | )
76 | def test_get_youtube_link_from_attachment(vk_link, youtube_link):
77 | data = text_post('some text').get_youtube_link_from_attachment(vk_link)
78 | assert data == youtube_link
79 |
80 |
81 |
--------------------------------------------------------------------------------
/models/sender.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import time
4 |
5 | import telebot
6 | from telebot.types import InputMediaPhoto, InputMediaVideo
7 |
8 | from assets.attachment_types import *
9 | from assets.utils import AttachmentParts
10 |
11 |
12 | class TelegramSender:
13 | """
14 | Отправит обработанный объект типа Post в телеграмм канал
15 | """
16 | SYMBOLS_WITH_ATTACHMENT = 950
17 | SYMBOLS_ONLY_TEXT = 4000
18 | # ограничения на число символов в сообщении с вложением и без
19 |
20 | def __init__(self, tg_token, chat_link):
21 | self.attachments = None
22 | self.tg_client = telebot.TeleBot(tg_token)
23 | self.chat_link = chat_link
24 |
25 | def send_post_as_messages(self, post):
26 | """
27 | Подготовит вложения к финальной отправке. Использует генератор message_generator
28 | Для разбиения текста поста на сообщения. Приоритетно обрабатываются вложения в алюбоме.
29 | Все оставшиеся вложения отправляются по одиночке и дополняются текстом поста
30 | (если он остался). В конце отправляются остатки текста.
31 |
32 | :param post: обработанный объект типа Post
33 | """
34 | self.attachments = AttachmentParts([], [], [], [])
35 | self.create_telegram_attachments(post)
36 |
37 | if not post.text:
38 | self.send_with_no_text()
39 | return
40 |
41 | message_generator = self.message_parts_generator(post.text)
42 | next(message_generator)
43 |
44 | if self.attachments.album_sendings:
45 | self.send_with_album_sendings(message_generator)
46 |
47 | if self.attachments.videos:
48 | self.send_with_videos(message_generator)
49 |
50 | if self.attachments.docs:
51 | self.send_with_docs(message_generator)
52 |
53 | if self.attachments.animations:
54 | self.send_with_animations(message_generator)
55 |
56 | self.send_last_messages_of_text(message_generator)
57 |
58 | def create_telegram_attachments(self, post):
59 | """
60 | Группирует вложения по типам, по возможности объединяет малые видео и картинки в один альбом
61 |
62 | :param post: обработанный объект типа Post
63 | """
64 | # TODO create_telegram_attachments попробовать делать это сразу в методе parse_attachments у поста
65 |
66 | for att in post.attachments_storage:
67 | att_type = [*att.keys()][0]
68 | if att_type in [VIDEO_ALBUM, PHOTO]:
69 | self.attachments.album_sendings.append({att_type: att[att_type]})
70 |
71 | elif att_type in [VIDEO_LARGE]:
72 | self.attachments.videos.append({att_type: att[att_type]})
73 |
74 | elif att_type in [DOC]:
75 | self.attachments.docs.append({att_type: att[att_type]})
76 |
77 | elif att_type in [ANIMATION]:
78 | self.attachments.animations.append({att_type: att[att_type]})
79 |
80 | def send_with_album_sendings(self, message_generator):
81 | """
82 | Отправляет вложения альбома
83 |
84 | :param message_generator: генератор сообщений
85 | """
86 | attachments_album = []
87 | file_first = self.attachments.album_sendings[0]
88 | caption_message = message_generator.send(type(self).SYMBOLS_WITH_ATTACHMENT)
89 |
90 | attachments_album.append(
91 | InputMediaPhoto(file_first[PHOTO], caption=caption_message) if PHOTO in file_first.keys()
92 | else InputMediaVideo(file_first[VIDEO_ALBUM].media, duration=file_first[VIDEO_ALBUM].duration,
93 | width=file_first[VIDEO_ALBUM].width, caption=caption_message,
94 | height=file_first[VIDEO_ALBUM].height)
95 | )
96 |
97 | for file in self.attachments.album_sendings[1:]:
98 | attachments_album.append(
99 | InputMediaPhoto(file[PHOTO]) if PHOTO in file.keys() else InputMediaVideo(
100 | file[VIDEO_ALBUM].media, duration=file[VIDEO_ALBUM].duration,
101 | width=file[VIDEO_ALBUM].width, height=file[VIDEO_ALBUM].height)
102 | )
103 |
104 | self.tg_client.send_media_group(self.chat_link, attachments_album)
105 | time.sleep(3)
106 |
107 | def send_with_videos(self, message_generator):
108 | """
109 | Отправляет видео-вложения
110 |
111 | :param message_generator: генератор сообщений
112 | """
113 | for file in self.attachments.videos:
114 |
115 | try:
116 | sending_message = message_generator.send(type(self).SYMBOLS_WITH_ATTACHMENT)
117 |
118 | self.tg_client.send_video(self.chat_link, file[VIDEO_LARGE].media, file[VIDEO_LARGE].duration,
119 | width=file[VIDEO_LARGE].width, height=file[VIDEO_LARGE].height,
120 | caption=sending_message)
121 |
122 | except StopIteration:
123 | self.tg_client.send_video(self.chat_link, file[VIDEO_LARGE].media, file[VIDEO_LARGE].duration,
124 | width=file[VIDEO_LARGE].width,
125 | height=file[VIDEO_LARGE].height)
126 | time.sleep(3)
127 |
128 | def send_with_docs(self, message_generator):
129 | """
130 | Отправляет вложения-документы
131 |
132 | :param message_generator: генератор сообщений
133 | """
134 | for file in self.attachments.docs:
135 | try:
136 | sending_message = message_generator.send(type(self).SYMBOLS_WITH_ATTACHMENT)
137 | self.tg_client.send_document(self.chat_link, file[DOC], caption=sending_message)
138 |
139 | time.sleep(3)
140 | except StopIteration:
141 | self.tg_client.send_document(self.chat_link, file[DOC])
142 | time.sleep(3)
143 |
144 | def send_with_animations(self, message_generator):
145 | """
146 | Отправляет вложения-анимации (gif картикни)
147 |
148 | :param message_generator: генератор сообщений
149 | """
150 | # TODO - pull request библиотеки pytelebot, где добавить параметры width и height для send_animation
151 | for file in self.attachments.animations:
152 | try:
153 | sending_message = message_generator.send(type(self).SYMBOLS_WITH_ATTACHMENT)
154 | self.tg_client.send_animation(self.chat_link, file[ANIMATION], duration=10, caption=sending_message)
155 | time.sleep(3)
156 |
157 | except StopIteration:
158 | self.tg_client.send_animation(self.chat_link, file[ANIMATION], duration=10)
159 | time.sleep(3)
160 |
161 | def send_with_no_text(self):
162 | """
163 | Отправляет пост, у которого нет исходного текста
164 | """
165 | album_attachments = []
166 |
167 | for file in self.attachments.album_sendings:
168 | album_attachments.append(
169 | InputMediaPhoto(file[PHOTO]) if PHOTO in list(file.keys())[0] else InputMediaVideo(
170 | file[VIDEO_ALBUM].media, duration=file[VIDEO_ALBUM].duration,
171 | width=file[VIDEO_ALBUM].width,
172 | height=file[VIDEO_ALBUM].height)
173 | )
174 |
175 | self.tg_client.send_media_group(self.chat_link, album_attachments)
176 | time.sleep(3)
177 |
178 | for file in self.attachments.videos:
179 | self.tg_client.send_video(self.chat_link, file.media, file.duration, width=file.width, height=file.height)
180 | time.sleep(3)
181 |
182 | for file in self.attachments.docs:
183 | self.tg_client.send_document(self.chat_link, file.media)
184 | time.sleep(3)
185 |
186 | def send_last_messages_of_text(self, message_generator):
187 | """
188 | Отправляет куски текста, оставшиеся без вложений, в длинных сообщениях
189 |
190 | :param message_generator:
191 | """
192 | try:
193 | while True:
194 | sending_message = message_generator.send(type(self).SYMBOLS_ONLY_TEXT)
195 | self.tg_client.send_message(self.chat_link, sending_message)
196 | time.sleep(3)
197 | finally:
198 | time.sleep(5)
199 | # без return ошибка всё-равно появится. Return блокирует её появление
200 | return
201 |
202 | @staticmethod
203 | def message_parts_generator(text):
204 | """
205 | Генерирует "порции" текста. Приоритет деления - не по количеству символов, а по
206 | словам. (в строке "привет мир!" никогда не будет варианта деления: "при" + "вет мир!")
207 |
208 | :param text: текст, который делится на сообщения
209 | :return: кусок текста, который помещается по символам в сообщение
210 | """
211 | count_symbols = yield
212 | text_split = text.split(" ")
213 | message_part = ""
214 |
215 | for num in range(len(text_split)):
216 | if len(message_part + ' ' + text_split[num]) < count_symbols:
217 | message_part += text_split[num] + ' '
218 |
219 | else:
220 | count_symbols = yield message_part[:-1]
221 | message_part = text_split[num] + ' '
222 |
223 | yield message_part[:-1]
224 |
--------------------------------------------------------------------------------
/models/post_creator.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import logging
4 | import os
5 | import re
6 |
7 | import requests
8 | import vk_api
9 | import youtube_dl
10 |
11 | from assets.attachment_types import *
12 | from assets.utils import Video
13 |
14 | logging.basicConfig(filename='assets/warnings.log', format='%(asctime)s - %(levelname)s - %(message)s',
15 | datefmt='%d-%b-%Y %H:%M:%S')
16 |
17 |
18 | class Post:
19 | """
20 | Позволяет обработать и подговить "сырой" пост из ВКонтакте
21 | к отправке в формате сообщений Телеграмма
22 | """
23 |
24 | def __init__(self, raw_post, group_id, vk_service_token):
25 | self.raw_post = raw_post
26 | self.text = raw_post['text']
27 | self.group_id = group_id
28 |
29 | # нужно для создания "укороченных" vk.cc ссылок из обычных
30 | vk_session = vk_api.VkApi(token=vk_service_token)
31 | self.vk = vk_session.get_api()
32 |
33 | self.attachments_storage = []
34 | # Хранит в себе словари вложений. У каждого словаря ключом является
35 | # некий тип вложения (типы опеределены в assets.attachment_types).
36 | # Также есть специальный тип ERROR. Объекты с этим ключом
37 | # в последствии обрабатываются отдельно и удаляются из списка
38 |
39 | def refactor(self, key_tag):
40 | """
41 | Осуществляет чистку текста от частей, которые специфичны и реализованы только в ВКонтакте
42 | """
43 | self.refactor_group_links()
44 | self.refactor_user_links()
45 | self.refactor_tags(key_tag)
46 |
47 | def refactor_group_links(self):
48 | """
49 | Чистит ссылки групп, используемые в ВК. Например: [club12132|SpaceX] -> SpaceX
50 | """
51 | for tag in re.findall(r'\[\w*\|(\w*)]', self.text):
52 | self.text = re.sub(r'\[\w*\|\w*\]', tag, self.text, 1)
53 |
54 | def refactor_user_links(self):
55 | """
56 | Чистит ссылки пользователей, используемые в ВК. Например: [@Alisa|ведущий] -> ведущий
57 | """
58 | for tag in re.findall(r'\[\w*\|(.+?)]', self.text):
59 | self.text = re.sub(r'\[\w*\|.+?]', tag, self.text, 1)
60 |
61 | def refactor_tags(self, key_tag):
62 | """
63 | Удалит ключевой тег перепоста, а также уберёт идентификатор группы после символа @ в тегах.
64 | Например: #key_tag #rocketship@Spacex -> #rocketship
65 |
66 | :param key_tag: тег, по которому идёт перепост в телеграмм
67 | """
68 | self.text = self.text.replace(key_tag, "", 1)
69 |
70 | for tag in re.findall(r'#(\w+?)@\w*', self.text):
71 | self.text = re.sub(r'#(\w+?)@\w*', f'#{tag}', self.text, 1)
72 |
73 | def parse_attachments(self):
74 | """
75 | Поддерживаете следующие виды вложнеий: видео, фото, ссылки, документы, гиф-анимации.
76 | Преобразует каждый вид вложения для отправки. Во время преобразования могут возникнут "ошибки".
77 | Любые виды таких ошибок не прерывают работу скрипта, а позднее логируются.
78 | """
79 | try:
80 | attachments = self.raw_post['attachments']
81 | except KeyError:
82 | attachments = []
83 |
84 | for element in attachments:
85 | if element['type'] == 'video':
86 | self.attachments_storage.append(
87 | self.parse_video(element['video'])
88 | )
89 |
90 | elif element['type'] == 'photo':
91 | self.attachments_storage.append(
92 | self.parse_photo(element['photo'])
93 | )
94 |
95 | elif element['type'] == 'doc':
96 | self.attachments_storage.append(
97 | self.parse_doc(element['doc'])
98 | )
99 |
100 | elif element['type'] == 'link':
101 | self.attachments_storage.append(
102 | self.parse_link(element['link'])
103 | )
104 |
105 | self.validate_parse_errors()
106 | self.add_links_to_text()
107 | self.delete_downloads()
108 |
109 | def parse_video(self, video):
110 | """
111 | Обработчик видео-вложений. Youtube-видео, встроенные в вк через embedded, становятся обычными
112 | ссылками. Телеграмм почему-то не добавляет видео в альбом больше 10МБ, поэтому происходит
113 | попытка сжать видео. Видео длинее 5 минут сразу возвращаются с пометкой VIDEO_LARGE, потому что
114 | сжатие скорее всего не поможет, а только займёт много времени.
115 |
116 | :param video: словарь с деталями видео
117 | :return: словарь с объектом Video, либо ошибка
118 | """
119 |
120 | # у видеозаписей, залитых через вк, нет ключа platform
121 | if 'platform' in video.keys():
122 | if video['platform'] != 'YouTube':
123 | return {ERROR: f"Неизвестная платформа у видео: {self.group_id}_{video['id']}"}
124 |
125 | video_link = self.text_contains_link_of_attached_video(video)
126 | # возвращает строкой ссылку на видео, если оно есть в тексте, иначе ""
127 | # TODO переписать этот логический маразм и переименовать метод (-_-)
128 |
129 | if video_link:
130 | return {LINK_YOUTUBE: video_link}
131 | else:
132 | return {ERROR: f"Данное видео уже содержится как ссылка в посте: {self.group_id}_{video['id']}"}
133 |
134 | try:
135 | video_data = self.download_video(video)
136 |
137 | except Exception as error:
138 | # Этот лог отдельный, чтобы сохранить traceback ошибки
139 | logging.error(repr(error), exc_info=True)
140 | return {ERROR: f"Произошла неизвестная ошибка при загрузке видео: {self.group_id}_{self.video['id']}"}
141 |
142 | return video_data
143 |
144 | def download_video(self, video):
145 | """
146 | Пытается скачать видео из вк. Если оно дольше 5 минут, то оно возвращается
147 | с пометкой VIDEO_LARGE, иначе сжимается до величены меньшей 10MB. (Единственный способ
148 | добавить видео в альбом-вложений)
149 |
150 | :param video: словарь с исходной информации о видео
151 | :return: объектом Video
152 | """
153 | with youtube_dl.YoutubeDL({'outtmpl': 'downloads/saved.mp4'}) as ydl:
154 | ydl.download([f"https://vk.com/video{self.group_id}_{video['id']}"])
155 |
156 | if video['duration'] / 60 > 5:
157 | return {VIDEO_LARGE: self.get_video('downloads/saved.mp4', video)}
158 |
159 | # сжатие через ffmpeg (другие кодеки могут вызывать ошибки, данный работает на linux)
160 | os.system('ffmpeg -y -i downloads/saved.mp4 -vcodec h264 -acodec mp2 downloads/output.mp4')
161 |
162 | # проверка размера видео на превышение 10MB
163 | if float(os.path.getsize('downloads/output.mp4') / 1024 / 1024) > 10:
164 | return {VIDEO_LARGE: self.get_video('downloads/output.mp4', video)}
165 |
166 | return {VIDEO_ALBUM: self.get_video('downloads/output.mp4', video)}
167 |
168 | @staticmethod
169 | def get_video(filename, video):
170 | """
171 | Скачивает видео, сохраняет его биты и метаданные в объект Video
172 |
173 | :param filename: путь к сжатому видео
174 | :param video: словарь с метаданными видео, предаставляется вк
175 | :return: объект Video
176 | """
177 | with open(filename, "rb") as video_file:
178 | data = Video(video_file.read(), video['duration'], video['width'], video['height'])
179 |
180 | return data
181 |
182 | def text_contains_link_of_attached_video(self, video):
183 | """
184 | Возвращает строкой ссылку на видео, если оно есть в тексте, иначе ""
185 |
186 | :param video: данные о видео
187 | :return: '' или полная ссылка на видео
188 | """
189 | mentioned_links_in_text = self.get_youtube_links_from_text()
190 | youtube_link = self.get_youtube_link_from_attachment(f"https://vk.com/video{self.group_id}_{video['id']}")
191 |
192 | return youtube_link if youtube_link not in mentioned_links_in_text else ''
193 |
194 | @staticmethod
195 | def get_youtube_link_from_attachment(vk_video_link):
196 | """
197 | По видео-ссылке из ВК, возвращает аналогичную, но из самого ютуба
198 |
199 | :param vk_video_link: ссылыка из вк
200 | :return: ссылка из ютуба
201 | """
202 | video_in_vk = requests.get(vk_video_link)
203 | link_embed = re.findall(r'//www.youtube.com/embed/\S+?\?', video_in_vk.text)[0]
204 | short_link = 'https:' + link_embed.replace('/embed/', '/', 1)[:-1].replace('www.youtube.com', 'youtu.be')
205 |
206 | youtube_embedded = requests.get(short_link, allow_redirects=True).url
207 | full_link = youtube_embedded.split("&")[0]
208 |
209 | return full_link
210 |
211 | def get_youtube_links_from_text(self):
212 | """
213 | Выделеят из поста все ссылки, которые могут вести на ютуб.
214 | В итоге будет список из несокращённых ссылок (не youtu.be), ведущих на youtube.com
215 |
216 | :returns список ссылок
217 | """
218 | youtube_links = []
219 |
220 | vk_cc_links = re.findall(r"(vk.cc/\S+)", self.text)
221 |
222 | for vk_link in vk_cc_links:
223 | data = requests.get("https://" + vk_link)
224 | link = re.findall(r"value=\"https://www.(youtube.com/watch\?v=\S+?)\"", data.text)
225 | # в регулярку добавлена часть тега, чтобы не цеплялись лишние ссылки, а была одна
226 |
227 | youtube_links.extend(link)
228 | # использовался extend, потому что vk.cc ссылка не всегда ведёт на
229 | # ютуб и re.findall может вернуть пустой список
230 |
231 | short_youtube_links = re.findall(r"(youtu.be/\S+)", self.text)
232 |
233 | for link_be in short_youtube_links:
234 | youtube_full_link = requests.get("https://" + link_be).url.split("&")[0].lstrip("https://www.")
235 | youtube_links.append(youtube_full_link)
236 |
237 | links = re.findall(r"https://www.youtube.com/watch?v=\S+\"", self.text)
238 | youtube_links.extend(links)
239 |
240 | return list(set(youtube_links))
241 |
242 | def validate_parse_errors(self):
243 | """
244 | Удалит из данных все уведомлнеия об ошибках произошедших при парсинге
245 | поста и запишет их в логи (В основном касается скачивания и сжатия видео)
246 | """
247 | for error in [element for element in self.attachments_storage if ERROR in element]:
248 | logging.warning(error[ERROR])
249 |
250 | self.attachments_storage = [element for element in self.attachments_storage if ERROR not in element]
251 |
252 | @staticmethod
253 | def parse_photo(photo) -> dict:
254 | """
255 | Возвращает url картинки с максимальным разрешением
256 |
257 | :param photo: словарь с информацией о фото
258 | :return: словарь с данными фотографии
259 | """
260 | return {PHOTO: photo['sizes'][-1]['url']}
261 |
262 | @staticmethod
263 | def parse_doc(document):
264 | """
265 | Скачивает вк-документ. Если это фотография, то "понижает" вложение до типа
266 | обычной фотографии. Если это гифка, то она помечается типом "анимация".
267 | Все остальные вложения будут отпарвлены, как простые документы.
268 |
269 | :param document: словарь с информацией о документу
270 | :return: словарь с битами вложения
271 | """
272 | r = requests.get(document['url'], allow_redirects=True)
273 |
274 | if document['ext'] in ['jpg', 'png']:
275 | return {PHOTO: r.content}
276 | elif document['ext'] in ['gif']:
277 | return {ANIMATION: r.content}
278 | else:
279 | return {DOC: r.content}
280 |
281 | def parse_link(self, link):
282 | """
283 | Возвращает ссылку, если она не встречалась в тексте поста
284 |
285 | :param link: Словарь с информацией о ссылке
286 | :return: словарь со ссылкой, либо ошибка
287 | """
288 | links_yt = self.get_youtube_links_from_text()
289 |
290 | return {LINK: link['url']} if link not in links_yt else {ERROR: "В посте уже есть эта ссылка"}
291 |
292 | @staticmethod
293 | def delete_downloads():
294 | """
295 | Сотрёт все файлы, которые временно скачивались в директорию download
296 | """
297 | list_of_files = [f for f in os.listdir("downloads")]
298 | for file in list_of_files:
299 | os.remove(os.path.join("downloads", file))
300 |
301 | def add_links_to_text(self):
302 | """
303 | Добавляет полученные ссылки в конец текста поста. Если это ссылка ведёт на ютуб,
304 | то она будет уреза до домена youtu.be, а если ведёт на любой другой ресурс, то
305 | будет минифицирована методом API до vk.cc
306 | """
307 | links = [element for element in self.attachments_storage if [*element][0] in [LINK_YOUTUBE, LINK]]
308 |
309 | if len(links) == 1:
310 | self.text += '\n\nСсылка:\n'
311 | elif links:
312 | self.text += '\n\nСсылки:\n'
313 | else:
314 | return
315 |
316 | for link in links:
317 | if LINK_YOUTUBE in link:
318 | self.text += link[LINK_YOUTUBE].replace('watch?v=', '').replace('https://www.youtube.com',
319 | 'youtu.be') + '\n'
320 | else:
321 | self.text += self.vk.utils.getShortLink(url=link[LINK])['short_url'] + '\n'
322 |
323 | self.text = self.text[:-1]
324 |
--------------------------------------------------------------------------------
/tests/consts.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | real_post = {'attachments': [
4 | {'photo': {'access_key': '9fe58e310fa15bc1d5',
5 | 'album_id': -7,
6 | 'date': 1593877634,
7 | 'has_tags': False,
8 | 'id': 457240334,
9 | 'owner_id': -41126705,
10 | 'sizes': [{'height': 73,
11 | 'type': 'm',
12 | 'url': 'https://sun1-95.userapi.com/23gjmAnqIeq25QUDotgRx6VHu2yFrgj7kfo6RQ/S_ZLmHtXnl0.jpg',
13 | 'width': 130},
14 | {'height': 87,
15 | 'type': 'o',
16 | 'url': 'https://sun1-47.userapi.com/9ah4RZR4s1rvnN_1jZ_MIrbvh_ZGjdjav0zaHw/C4mJ9FPyA0k.jpg',
17 | 'width': 130},
18 | {'height': 133,
19 | 'type': 'p',
20 | 'url': 'https://sun1-24.userapi.com/2zAe15jKXtqqcSxpECORqdfZ8PCPljdLBcFekw/MnM93cZXjhM.jpg',
21 | 'width': 200},
22 | {'height': 213,
23 | 'type': 'q',
24 | 'url': 'https://sun1-25.userapi.com/bmskzwqucOrpSnnfmjz7ca56OZKWxYdYmqr6cQ/aqLJ_x3I1Z0.jpg',
25 | 'width': 320},
26 | {'height': 340,
27 | 'type': 'r',
28 | 'url': 'https://sun1-19.userapi.com/YPCNu6kwEYvFj-nSLlM1bJKhHR6MKju8GTpq6w/VINGidYDyYY.jpg',
29 | 'width': 510},
30 | {'height': 42,
31 | 'type': 's',
32 | 'url': 'https://sun1-16.userapi.com/qZaexKmF8ROTrdP5__92Le9byUoVTV-_Q1xeZQ/Bcz-u-owAMM.jpg',
33 | 'width': 75},
34 | {'height': 1080,
35 | 'type': 'w',
36 | 'url': 'https://sun1-94.userapi.com/asmXJnyrIf7yISxiuGTYDjHA4MI3UMHhfYA6bg/vBciThoYcZk.jpg',
37 | 'width': 1920},
38 | {'height': 340,
39 | 'type': 'x',
40 | 'url': 'https://sun1-20.userapi.com/b58qEfZL_bn7L2ox51Zh0pEs_ptrz7aHmk6vJg/0WHhk639pJo.jpg',
41 | 'width': 604},
42 | {'height': 454,
43 | 'type': 'y',
44 | 'url': 'https://sun1-47.userapi.com/9uIdhCqbVEtD3ChcEJdIJ_7pM1Nk6A9P9SUI_A/bp8T1PASmYQ.jpg',
45 | 'width': 807},
46 | {'height': 720,
47 | 'type': 'z',
48 | 'url': 'https://sun1-16.userapi.com/OPxa_oh0824kpJWSGhNYKoHea5TMCJq0cqbbtw/mmbkALUD4xo.jpg',
49 | 'width': 1280}],
50 | 'text': '',
51 | 'user_id': 100},
52 | 'type': 'photo'},
53 | {'link': {'description': '',
54 | 'photo': {'album_id': -28,
55 | 'date': 1593878297,
56 | 'has_tags': False,
57 | 'id': 457298168,
58 | 'owner_id': 2000062089,
59 | 'sizes': [{'height': 480,
60 | 'type': 'k',
61 | 'url': 'https://sun9-61.userapi.com/c857528/v857528591/21b5c2/mR15_ET3BpE.jpg',
62 | 'width': 1074},
63 | {'height': 240,
64 | 'type': 'l',
65 | 'url': 'https://sun9-66.userapi.com/c857528/v857528591/21b5c1/Qjg2d9kbGXY.jpg',
66 | 'width': 537},
67 | {'height': 73,
68 | 'type': 'm',
69 | 'url': 'https://sun9-72.userapi.com/c857528/v857528591/21b5be/t7rkFR5iabE.jpg',
70 | 'width': 130},
71 | {'height': 146,
72 | 'type': 'p',
73 | 'url': 'https://sun9-61.userapi.com/c857528/v857528591/21b5c0/SYPvtMOQBN8.jpg',
74 | 'width': 260},
75 | {'height': 42,
76 | 'type': 's',
77 | 'url': 'https://sun9-12.userapi.com/c857528/v857528591/21b5bd/oJyivTs2bLk.jpg',
78 | 'width': 75},
79 | {'height': 84,
80 | 'type': 'x',
81 | 'url': 'https://sun9-59.userapi.com/c857528/v857528591/21b5bf/-ULIwcdJ1ew.jpg',
82 | 'width': 150}],
83 | 'text': ''},
84 | 'target': 'internal',
85 | 'title': "Запуск Electron: PICS OR IT DIDN'T "
86 | 'HAPPEN',
87 | 'url': 'https://youtu.be/wrfzG_5IQyo'},
88 | 'type': 'link'}],
89 | 'comments': {'can_post': 1, 'count': 0, 'groups_can_post': True},
90 | 'date': 1593878464,
91 | 'from_id': -41126705,
92 | 'id': 86379,
93 | 'likes': {'can_like': 1, 'can_publish': 1, 'count': 12, 'user_likes': 0},
94 | 'marked_as_ads': 0,
95 | 'owner_id': -41126705,
96 | 'post_source': {'type': 'vk'},
97 | 'post_type': 'post',
98 | 'reposts': {'count': 0, 'user_reposted': 0},
99 | 'text': 'Дорогие друзья, сегодня мы проведём для вас наш первый стрим на '
100 | 'нашем молодом канале [club41126705|NewSpace]! 🚀\n'
101 | '\n'
102 | 'Ведущие: \n'
103 | '[id267990964|Dima Kurdoglo] и [id145462869|Alisa Zaripova] \n'
104 | '\n'
105 | 'Ссылка:https://vk.cc/ax6g0g\n'
106 | 'https://youtu.be/wrfzG_5IQyo \n'
107 | 'https://www.youtube.com/watch?v=wrfzG_5IQyo\n'
108 | 'Стримить начнем за 15 минут до официальной трансляции, поэтому '
109 | 'подключайтесь, задавайте вопросы в эфире или в комментариях под '
110 | 'этим постом, а мы с радостью постараемся рассказать вам самое '
111 | 'главное и ответить на все интересующие вопросы! 🤙🏻\n'
112 | '\n'
113 | '#NewSpace@newspacepress #RocketLab@newspacepress '
114 | '#Electron@newspacepress #telegram@newspacepress',
115 | 'views': {'count': 928}}
116 |
117 | refactored_text = ('Дорогие друзья, сегодня мы проведём для вас наш первый стрим на '
118 | 'нашем молодом канале NewSpace! 🚀\n'
119 | '\n'
120 | 'Ведущие: \n'
121 | 'Dima Kurdoglo и Alisa Zaripova \n'
122 | '\n'
123 | 'Ссылка:https://vk.cc/ax6g0g\n'
124 | 'https://youtu.be/wrfzG_5IQyo \n'
125 | 'https://www.youtube.com/watch?v=wrfzG_5IQyo\n'
126 | 'Стримить начнем за 15 минут до официальной трансляции, поэтому '
127 | 'подключайтесь, задавайте вопросы в эфире или в комментариях под '
128 | 'этим постом, а мы с радостью постараемся рассказать вам самое '
129 | 'главное и ответить на все интересующие вопросы! 🤙🏻\n'
130 | '\n'
131 | '#NewSpace #RocketLab '
132 | '#Electron ')
133 |
134 | no_youtube_links = ('Дорогие друзья, сегодня мы проведём для вас наш первый стрим на '
135 | 'нашем молодом канале NewSpace! 🚀\n'
136 | '\n'
137 | 'Ведущие: \n'
138 | 'Dima Kurdoglo и Alisa Zaripova \n'
139 | '\n'
140 | 'Ссылка:\n'
141 | '\n'
142 | 'Стримить начнем за 15 минут до официальной трансляции, поэтому '
143 | 'подключайтесь, задавайте вопросы в эфире или в комментариях под '
144 | 'этим постом, а мы с радостью постараемся рассказать вам самое '
145 | 'главное и ответить на все интересующие вопросы! 🤙🏻\n'
146 | '\n'
147 | '#NewSpace #RocketLab '
148 | '#Electron ')
149 |
150 | post_with_youtube = {'attachments': [
151 | {'photo': {'access_key': 'fb2323fa6cbd009bcf',
152 | 'album_id': -7,
153 | 'date': 1594830275,
154 | 'has_tags': False,
155 | 'id': 457240483,
156 | 'owner_id': -41126705,
157 | 'sizes': [{'height': 87,
158 | 'type': 'm',
159 | 'url': 'https://sun1-99.userapi.com/c857136/v857136630/1d915b/qqJFj0CqyAk.jpg',
160 | 'width': 130},
161 | {'height': 87,
162 | 'type': 'o',
163 | 'url': 'https://sun1-88.userapi.com/c857136/v857136630/1d9160/3Dq0-NO3Dtg.jpg',
164 | 'width': 130},
165 | {'height': 133,
166 | 'type': 'p',
167 | 'url': 'https://sun1-96.userapi.com/c857136/v857136630/1d9161/-7l79E-wTzo.jpg',
168 | 'width': 200},
169 | {'height': 213,
170 | 'type': 'q',
171 | 'url': 'https://sun1-25.userapi.com/c857136/v857136630/1d9162/8jYWX1JqeUU.jpg',
172 | 'width': 320},
173 | {'height': 340,
174 | 'type': 'r',
175 | 'url': 'https://sun1-25.userapi.com/c857136/v857136630/1d9163/de-khDIB8vw.jpg',
176 | 'width': 510},
177 | {'height': 50,
178 | 'type': 's',
179 | 'url': 'https://sun1-88.userapi.com/c857136/v857136630/1d915a/yFyT-W5BzRw.jpg',
180 | 'width': 75},
181 | {'height': 1707,
182 | 'type': 'w',
183 | 'url': 'https://sun1-88.userapi.com/c857136/v857136630/1d915f/dt-EKa4moNM.jpg',
184 | 'width': 2560},
185 | {'height': 403,
186 | 'type': 'x',
187 | 'url': 'https://sun1-24.userapi.com/c857136/v857136630/1d915c/6Wnhoj_1XvU.jpg',
188 | 'width': 604},
189 | {'height': 538,
190 | 'type': 'y',
191 | 'url': 'https://sun1-27.userapi.com/c857136/v857136630/1d915d/3J543eU5FPI.jpg',
192 | 'width': 807},
193 | {'height': 853,
194 | 'type': 'z',
195 | 'url': 'https://sun1-89.userapi.com/c857136/v857136630/1d915e/ZMhWEthMEMA.jpg',
196 | 'width': 1280}],
197 | 'text': '',
198 | 'user_id': 100},
199 | 'type': 'photo'},
200 | {'type': 'video',
201 | 'video': {'access_key': '1a3a4a9479f21d3f21',
202 | 'can_add': 1,
203 | 'can_add_to_faves': 1,
204 | 'can_comment': 0,
205 | 'can_like': 1,
206 | 'can_repost': 1,
207 | 'can_subscribe': 1,
208 | 'comments': 0,
209 | 'date': 1594830275,
210 | 'description': 'In this Starship update; a new '
211 | 'Nosecone is born in Boca Chica, a '
212 | 'scrap ring stack is moved out of '
213 | 'the fabrication area, earth work '
214 | 'on both sides of the build site '
215 | 'continued, and work at the launch '
216 | 'site and on SN5 continued ahead '
217 | 'of engine testing.\n'
218 | '\n'
219 | 'Video and Pictures from Mary '
220 | '(@BocaChicaGal). Edited by Jack '
221 | 'Beyer (@TheJackBeyer) \n'
222 | '\n'
223 | 'Click "Join" for access to early '
224 | 'fast turnaround clips, exclusive '
225 | 'discord access with the NSF team, '
226 | 'etc - to support the channel.\n'
227 | '\n'
228 | 'Updates: '
229 | 'https://forum.nasaspaceflight.com/inde',
230 | 'duration': 880,
231 | 'id': 456239239,
232 | 'local_views': 6,
233 | 'owner_id': -41126705,
234 | 'photo_130': 'https://sun1-25.userapi.com/iKGMOSZ-zxqGLldGNN4nOo3kDgF5l9RWY-VDsw/GmMTOt9Wprw.jpg',
235 | 'photo_320': 'https://sun1-19.userapi.com/BtJ_EGrm2k45WIHPZ5V5xyL7YN7Tagst2PoQzw/r__FcqN6B9o.jpg',
236 | 'photo_800': 'https://sun1-89.userapi.com/Rp5XAidlIIBQ-6g5icyB_2Q9w9wIvkawMExjUQ/BRIDsc-1DJI.jpg',
237 | 'platform': 'YouTube',
238 | 'title': 'SpaceX Boca Chica - A New Nosecone Is '
239 | 'Born - New Lots Readied For Expansion',
240 | 'track_code': 'video_7e8fa9430Sx_MvWCaEAbmzYHFE-nfyAC-_bDw3_C7oYW7tRYEXblCGIzm4tsQB2SA1ggepFNEzvJxQ',
241 | 'views': 6}}],
242 | 'comments': {'can_post': 1, 'count': 0, 'groups_can_post': True},
243 | 'date': 1594837165,
244 | 'from_id': -41126705,
245 | 'id': 86619,
246 | 'likes': {'can_like': 1, 'can_publish': 1, 'count': 19, 'user_likes': 0},
247 | 'marked_as_ads': 0,
248 | 'owner_id': -41126705,
249 | 'post_source': {'type': 'vk'},
250 | 'post_type': 'post',
251 | 'reposts': {'count': 0, 'user_reposted': 0},
252 | 'text': 'Boca Chica News 🔧 🚀\n'
253 | '\n'
254 | '📌 Команда состыковала 2 части обтекателя [1-3 фото]. Как думаете, '
255 | 'будут ли использовать этот обтекатель в одном из следующих '
256 | 'прототипов? \n'
257 | '\nhttps://www.youtube.com/watch?v=zaSsO689d3w\n'
258 | '⚠ Перекрытия на 15 июля отменены [4 фото] \n'
259 | '\n'
260 | '📌 Вывезен ещё один тестовый бракованный сегмент из трёх колец [5-6 '
261 | 'фото]\n'
262 | '\n'
263 | '#SpaceX@newspacepress #BocaChica@newspacepress '
264 | '#telegram@newspacepress',
265 | 'views': {'count': 1093}}
266 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------