Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- """
- Python 3, testowane na wersjach 3.2.3 i 3.4.3.
- Zależności: moduł 'requests' (pip install requests).
- Changelog:
- 2.0.4: porządki w kodzie
- 2.0.3: opcja wypisywania odnośnika do zapisu chata w terminalu
- przy każdej wiadomości (CONFIG['print_chat_uri'])
- 2.0.2: poprawne zamykanie rozmowy po inicie z sebkami,
- których już śledzimy
- """
- VER = '2.0.4'
- import json
- import time
- import os.path
- import random
- import shutil
- import string
- import re
- import threading
- import requests
- CONFIG = {
- # -- "SKONFIGURUJ TO KURWO" SECTION
- 'threads': {
- # ACHTUNG! PRZESADA GROZI MANEM.
- # Liczba wątków. Każdy wątek = 1 sebek, każdy sebek = kilka rozmów.
- 'count': 4,
- # ACHTUNG! PRZESADA GROZI MANEM.
- # Opóznienie startu kolejnych wątkow w sekundach.
- 'start_delay': 12
- },
- # ACHTUNG! PRZESADA GROZI MANEM.
- # Opóźnienie pomiędzy zapytaniami o nowe wiadomości/zdarzenia w sekundach.
- 'request_delay': 1,
- # Czas bez wiadomości u sebka po którm zostanie porzucony w sekundach.
- 'activity_threshold': 60,
- 'boot_data': [
- {
- 'type': 'boot',
- 'lang': 'pl'
- },
- {
- 'type': 'start',
- 'prefs': {
- # Kogo szukamy.
- 'me': {
- 'gender': 'f',
- 'age': 17
- },
- # Kogo szuka ten, którego my szukamy
- 'them': {
- 'gender': 'm',
- 'age': 18,
- 'loc': 'śląskie'
- },
- 'color': 'dark'
- }
- }
- ],
- # Wypisywanie odnośnika do rozmowy przy każdej wiadomości.
- # Przydatne dla posiadaczy emulatora terminala z klikalnymi linkami.
- 'print_chat_uri': True,
- # Nazwy katalogów ze zdjęciami i zapisami rozmów (tworzone automatycznie).
- 'directories': {
- 'photos': 'photos',
- 'chats': 'chats'
- },
- # -- KUC SECTION
- 'request_headers': {
- 'User-Agent': random.choice([
- 'Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)',
- ('Mozilla/5.0 (compatible; MSIE 10.0; Macintosh; '
- 'Intel Mac OS X 10_7_3; Trident/6.0)'),
- ('Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; '
- 'GTB7.4; InfoPath.2; SV1; .NET CLR 3.3.69573; WOW64; en-US)'),
- 'Opera/9.80 (X11; Linux i686; U; ru) Presto/2.8.131 Version/11.11',
- ('Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2'
- '(KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2'),
- ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.13'
- 'KHTML, like Gecko) Chrome/24.0.1290.1 Safari/537.13'),
- ('Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 '
- '(KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11'),
- ('Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:16.0.1)'
- 'Gecko/20121011 Firefox/16.0.1'),
- ('Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 '
- '(KHTML like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25'),
- ('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 '
- '(KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36 ')
- ])
- },
- # -- INNE
- 'base_url': 'http://czatek.pl',
- 'sync_path': '/sync',
- 'uid': {
- 'symbols': string.digits + string.ascii_lowercase[:6],
- 'separator': '-',
- 'segment_lengths': [8, 4, 4, 4, 12]
- },
- 'photo_url_regex': '^\/\w+\/(\w+)(?:\?key=\w+)?$',
- }
- SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
- THREAD_LOCAL_DATA = threading.local()
- JSON_EMPTY = '[]'
- SEBKI = set()
- TIME_DIFF = None
- MESSAGES = {
- 'init': '-- [WYKOP.PL] CZATEK {version}: ELEKTRYCZNE BOOGALOO --',
- 'directory_created': 'Katalog "{directory}" utworzon\'d',
- 'probably_banned': ('Jest możliwe, że zostałeś zbanowany. '
- 'Jeżeli się to potwierdzi, prosimy o pilny kontakt '
- 'poprzez adres [email protected]'),
- 'banned': ('Zostałeś zbanowany. Prosimy o pilny kontakt poprzez adres '
- 'found_sebek': 'Znalezion\'d sebek {sebek_uid}',
- 'sebek_dropped': ('Sebek {sebek_uid} over and out. '
- 'Wznawiam polowanie, rucham psa jak sra.'),
- 'saving_photo': 'Zapisuje zdjecie: {full_path}'
- }
- TEMPLATES = {
- 'message': '{sender_label} -> {receiver_label}: {content}',
- 'local_uri': 'file://{base_dir}/',
- 'chat_path': '{chats_dir}/{chat_id}.html',
- 'chat_photo': '<img src=\'../{filename}\' width=\'640px\'>',
- 'chat_entry': '{prefix}<p><strong>{party_label}</strong>: {content}</p>',
- 'photo_path': '{photos_dir}/{chat_id}-{filename}.jpg',
- 'thread_label': '[{thread_name}]'
- }
- FRAGMENTS = {
- 'sebek_label': '(SEBEK)',
- 'photo_placeholder': '[ZDJECIE]',
- 'party_labels': {
- 'sebek': 'S',
- 'other': 'L'
- },
- 'chat_header': '<html><meta charset=\'utf-8\'>'
- }
- def thread_print(msg):
- print('{} {}'.format(threading.current_thread().getName(), msg))
- def generate_hexish_string(length):
- chars = [random.choice(CONFIG['uid']['symbols']) for _ in range(length)]
- return ''.join(chars)
- def generate_random_uid():
- segments = [generate_hexish_string(n)
- for n in CONFIG['uid']['segment_lengths']]
- return CONFIG['uid']['separator'].join(segments)
- def trim_uid(uid):
- return uid.rpartition(':')[0] if ':' in uid else uid
- def shorten_uid(uid):
- return uid.rpartition('-')[2]
- def set_time_diff(timestamp_with_ms):
- global TIME_DIFF
- if TIME_DIFF == None:
- TIME_DIFF = time.time() - strip_timestamp_ms(timestamp_with_ms)
- def strip_timestamp_ms(timestamp_with_ms):
- return int(timestamp_with_ms / 1000)
- def make_sync_request(uid, data):
- return requests.post(CONFIG['base_url'] + CONFIG['sync_path'],
- params={'uid': uid, 'last-msg': 0},
- headers=CONFIG['request_headers'],
- data=data)
- def find_sebek():
- my_uid = generate_random_uid()
- init_response = make_sync_request(my_uid, json.dumps(CONFIG['boot_data']))
- if init_response.status_code == 403:
- print(MESSAGES['banned'])
- return -1
- sebek_response = make_sync_request(my_uid, JSON_EMPTY)
- if not sebek_response or sebek_response.text == JSON_EMPTY:
- print(MESSAGES['probably_banned'])
- return None
- close_data = [{'type': 'shutdown', 'from': my_uid}]
- make_sync_request(my_uid, json.dumps(close_data))
- sebek_data = sebek_response.json()[0]
- sebek_uid = trim_uid(sebek_data['from'])
- set_time_diff(sebek_data['ts'])
- if sebek_uid in SEBKI:
- return None
- SEBKI.add(sebek_uid)
- THREAD_LOCAL_DATA.last_message_timestamp = sebek_data['ts']
- thread_print(MESSAGES['found_sebek'].format(sebek_uid=sebek_uid))
- return sebek_uid
- def eavesdrop_sebek(uid):
- while True:
- sync_response = make_sync_request(uid, JSON_EMPTY)
- try:
- handle_sync(uid, sync_response.json())
- except ValueError:
- print(MESSAGES['probably_banned'])
- break
- if time_to_drop_sebek():
- thread_print(MESSAGES['sebek_dropped'].format(sebek_uid=uid))
- SEBKI.remove(uid)
- break
- time.sleep(CONFIG['request_delay'])
- def time_to_drop_sebek():
- stripped_last_message_timestamp = \
- strip_timestamp_ms(THREAD_LOCAL_DATA.last_message_timestamp)
- synced_last_message_timestamp = stripped_last_message_timestamp + \
- TIME_DIFF
- seconds_since_last_message = time.time() - synced_last_message_timestamp
- return seconds_since_last_message > CONFIG['activity_threshold']
- def handle_sync(sebek_uid, sync_data_container):
- if not sync_data_container or sync_data_container == JSON_EMPTY:
- return -1
- sync_data = sync_data_container[0]
- if sync_data['type'] == 'msg':
- if sync_data['ts'] <= THREAD_LOCAL_DATA.last_message_timestamp:
- return 0
- sender_uid = trim_uid(sync_data['from'])
- receiver_uid = trim_uid(sync_data['to'])
- if sender_uid == sebek_uid:
- sender_label = FRAGMENTS['sebek_label']
- receiver_label = shorten_uid(receiver_uid)
- else:
- sender_label = shorten_uid(sender_uid)
- receiver_label = FRAGMENTS['sebek_label']
- content = (sync_data['content'] if not sync_data['img']
- else FRAGMENTS['photo_placeholder'])
- output = TEMPLATES['message'].format(sender_label=sender_label,
- receiver_label=receiver_label,
- content=content)
- short_uids = [shorten_uid(uid) for uid in [sender_uid, receiver_uid]]
- chat_id = '-'.join(sorted(short_uids))
- if CONFIG['print_chat_uri']:
- chat_uri = TEMPLATES['local_uri'].format(base_dir=SCRIPT_DIR)
- chats_dir = CONFIG['directories']['chats']
- chat_uri += TEMPLATES['chat_path'].format(chats_dir=chats_dir,
- chat_id=chat_id)
- output = ' '.join([chat_uri, output])
- thread_print(output)
- photo_filename = None
- if sync_data['img']:
- photo_filename = download_photo(chat_id, sync_data['img'])
- save_message(chat_id,
- sender_uid == sebek_uid,
- sync_data['content'],
- photo_filename)
- THREAD_LOCAL_DATA.last_message_timestamp = sync_data['ts']
- return 0
- else:
- return -1
- def save_message(chat_id, is_sebeks, content, photo_filename):
- chats_dir = CONFIG['directories']['chats']
- path = TEMPLATES['chat_path'].format(chats_dir=chats_dir, chat_id=chat_id)
- grand_opening = FRAGMENTS['chat_header'] if not os.path.isfile(path) else ''
- if photo_filename:
- content = TEMPLATES['chat_photo'].format(filename=photo_filename)
- party_label_name = 'sebek' if is_sebeks else 'other'
- party_label = FRAGMENTS['party_labels'][party_label_name]
- with open(path, 'a+') as out:
- out.write(TEMPLATES['chat_entry'].format(prefix=grand_opening,
- party_label=party_label,
- content=content))
- def download_photo(chat_id, path):
- photos_dir = CONFIG['directories']['photos']
- full_path = CONFIG['base_url'] + path
- photo_response = requests.get(full_path,
- stream=True,
- headers=CONFIG['request_headers'])
- matcher = re.search(CONFIG['photo_url_regex'], path)
- photo_file_path = TEMPLATES['photo_path'].format(photos_dir=photos_dir,
- chat_id=chat_id,
- filename=matcher.group(1))
- thread_print(MESSAGES['saving_photo'].format(full_path=photo_file_path))
- with open(photo_file_path, 'wb') as out:
- shutil.copyfileobj(photo_response.raw, out)
- del photo_response
- return photo_file_path
- def do_work():
- THREAD_LOCAL_DATA.last_message_timestamp = 0
- while True:
- sebek_uid = find_sebek()
- if sebek_uid and sebek_uid != -1:
- eavesdrop_sebek(sebek_uid)
- def initialize_directories():
- for directory in CONFIG['directories'].values():
- if os.path.isfile(directory):
- os.remove(directory)
- if not os.path.exists(directory):
- os.mkdir(directory)
- thread_print(MESSAGES['directory_created'].format(
- directory=directory))
- def main():
- print(MESSAGES["init"].format(version=VER))
- initialize_directories()
- for i in range(CONFIG['threads']['count']):
- thread_name = TEMPLATES['thread_label'].format(thread_name=i + 1)
- thread = threading.Thread(name=thread_name, target=do_work)
- thread.daemon = True
- thread.start()
- time.sleep(CONFIG['threads']['start_delay'])
- while True:
- time.sleep(1)
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment