Advertisement
Guest User

claim_itch

a guest
Jun 23rd, 2020
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 22.92 KB | None | 0 0
  1. '''
  2. ClaimItch/0.10
  3.  
  4. requirements:
  5. - python (tested on 3.8)
  6. - requests
  7. - beautiful soup
  8. - lxml
  9. - selenium
  10. - firefox
  11. - geckodriver
  12.  
  13. files and variables:
  14. - SOURCES variable:   includes itch sales/collections or reddit threads you want check, pass --recheck to retcheck them
  15. - history file:       includes the results of the current run so they can be used in future runs
  16.                      see the HISTORY_KEYS variable
  17. - log file
  18.  
  19. todo - functionality:
  20. - better interface for SOURCES
  21. - seperate always-free download-only games like https://leafxel.itch.io/hojiya
  22. - when discovering a game connected to a sale, check out the sale
  23. - games that redirect to a sale
  24. - notification of new script version
  25. - download non-claimable games?
  26. - login?
  27. - follow discovered reddit threads?
  28.  
  29. todo - coding:
  30. - the steamgifts source is huge, could probably be optimized 'https://itch.io/c/537762/already-claimed-will-be-on-sale-again'
  31. - handle network errors?
  32. - debug mode that enables breakpoints
  33. - log exceptions and urls on error
  34. - use classes?
  35. - edge case: non writable config location - would do the work but loss history
  36. - intersection between SOURCES and discovered collections in has_more?
  37. - confirm that the keys before & after don't need to be checked in reddit's json
  38. - proper log
  39. - proper config
  40. - claim() return values
  41. - "selenium.common.exceptions.ElementNotInteractableException: Message: Element <a class="button buy_btn" href=".."> could not be scrolled into view"
  42. - selenium's performance?
  43. - less strict parsing / navigation (use .lower) / fuller regex (to work with match and search)
  44. - pylint
  45. - a claimable game was recorded as dl_only, was it changed? https://melessthanthree.itch.io/lucah
  46. '''
  47.  
  48. import os
  49. import sys
  50. import re
  51. import json
  52. import html
  53. import argparse
  54. import requests
  55. from time import sleep, time
  56. from bs4 import BeautifulSoup
  57. from selenium import webdriver
  58. from selenium.common.exceptions import NoSuchElementException
  59.  
  60.  
  61. # add any itch sale/collection or reddit thread to this set
  62. SOURCES = {
  63.     'https://itch.io/c/757294/games-to-help-you-stay-inside',
  64.     'https://itch.io/c/759545/self-isolation-on-a-budget',
  65.     'https://old.reddit.com/r/FreeGameFindings/comments/fka4be/itchio_mega_thread/',
  66.     'https://old.reddit.com/r/GameDeals/comments/fkq5c3/itchio_a_collecting_compiling_almost_every_single',
  67.     'https://itch.io/c/537762/already-claimed-will-be-on-sale-again',
  68.     'https://old.reddit.com/r/FreeGameFindings/comments/fxhotl/itchio_mega_thread/',
  69.     'https://old.reddit.com/r/FreeGameFindings/comments/gbcjdn/itchio_mega_thread_3/',
  70.     'https://old.reddit.com/r/FreeGameFindings/comments/gkz20p/itchio_mega_thread_4/',
  71.     'https://old.reddit.com/r/FreeGameFindings/comments/hbkz5o/itchio_mega_thread_5/',
  72.     'https://itch.io/c/840421/paid-gone-free-sales'
  73. }
  74.  
  75.  
  76. PATTERNS = {
  77.     'itch_collection': r'.+itch\.io/c/.+',
  78.     'itch_sale': r'.+itch\.io/s/.+',
  79.     'itch_group': r'.+itch\.io/[sc]/\d+/.+', # sale or collection
  80.     'reddit_thread': r'.+(?P<thread>reddit\.com/r/.+/comments/.+)/.+',
  81.     'itch_game': r'(http://|https://)?(?P<game>.+\.itch\.io/[^/?]+)'
  82. }
  83.  
  84.  
  85. USER_AGENT = 'ClaimItch/0.10'
  86.  
  87.  
  88. HISTORY_KEYS = [
  89.     'urls',           # discovered game urls
  90.     'claimed',        # claimed games
  91.     'has_more',       # a sale, collection, or game that is connected to more sales
  92.     'checked_groups', # a sale/collection that was checked for games, pass --recheck-groups to recheck it
  93.     'dl_only',        # game is not claimable
  94.     'dl_only_old',    # downloadable game you want to skip for now
  95.     'always_free',    # downloadable game that is always free
  96.     'web',            # game is not claimable or downloadable, web game
  97.     'downloaded',     # games that were downloaded (edit this manually)
  98.     'buy',            # game is not free
  99.     'removed',        # game does not exist
  100.     'error',          # games that broke the script
  101.     'old_error',      # games that broke the script but were fixed later
  102. ]
  103.  
  104. PROCESSED_GAMES = ('claimed', 'dl_only', 'dl_only_old', 'downloaded', 'buy', 'removed', 'web', 'always_free')
  105.  
  106.  
  107. class ParsingError(Exception):
  108.     def __init__(self, url, *args, **kwargs):
  109.         # breakpoint()
  110.         self.url = url
  111.         super().__init__(url, *args, **kwargs)
  112.  
  113.  
  114. def extract_from_itch_group(group_page):
  115.     '''
  116.    INPUT  html sale or collection page
  117.    OUTPUT urls of all games, urls of games that avie noted is connected to more sales
  118.    '''
  119.     soup = BeautifulSoup(group_page, 'lxml')
  120.     urls, more = set(), set()
  121.     games = soup.find_all('div', class_='game_cell')
  122.     for game in games:
  123.         url = game.find('a').get('href')
  124.         urls.add(url)
  125.         if game.find('div', class_='blurb_outer') is not None:
  126.             more.add(url)
  127.     return urls, more
  128.  
  129.  
  130. def get_from_itch_group(group_url, sleep_time=15, max_page=None, sale=False):
  131.     '''
  132.    INPUT  itch.io collection url
  133.    OUTPUT see extract_urls
  134.    '''
  135.     if sale:
  136.         max_page = 1 # sales don't seem to have pages
  137.     page = 1
  138.     urls = set()
  139.     has_more = set()
  140.     while max_page is None or page <= max_page:
  141.         print(f' getting page {page}')
  142.         params = {'page': page} if not sale else None
  143.         res = requests.get(group_url, params=params)
  144.         if res.status_code == 404:
  145.             break
  146.         elif res.status_code != 200:
  147.             # breakpoint()
  148.             res.raise_for_status()
  149.         page += 1
  150.         new_urls, new_more = extract_from_itch_group(res.text)
  151.         urls.update(new_urls)
  152.         has_more.update(new_more)
  153.         print(f' sleeping for {sleep_time}s')
  154.         sleep(sleep_time)
  155.     print(f' got {len(urls)} games')
  156.     return urls, has_more
  157.  
  158.  
  159. def get_from_reddit_thread(url, sleep_time=15):
  160.     '''
  161.    INPUT  reddit thread url
  162.    OUTPUT itch.io game urls, itch.io groups (sales, collections)
  163.    '''
  164.     global USER_AGENT, PATTERNS
  165.  
  166.     # https://www.reddit.com/dev/api#GET_comments_{article}
  167.     # https://github.com/reddit-archive/reddit/wiki/JSON
  168.     base_url = f"https://{re.match(PATTERNS['reddit_thread'], url)['thread']}" # does not end with /
  169.     urls = set()
  170.     has_more = set()
  171.  
  172.     chains = ['']
  173.     while len(chains) > 0:
  174.         current_chain = chains.pop()
  175.         print(f' getting a comment chain {current_chain}')
  176.         json_url = base_url + current_chain + '.json?threaded=false'
  177.         res = requests.get(json_url, headers={'User-Agent': USER_AGENT})
  178.         if res.status_code != 200:
  179.             res.raise_for_status()
  180.         data = res.json()
  181.         for listing in data:
  182.             if listing['kind'].lower() != 'listing':
  183.                 raise ParsingError(json_url)
  184.             children = listing['data']['children']
  185.             for child in children:
  186.                 text = None
  187.                 if child['kind'] == 't3':
  188.                     text = child['data']['selftext_html']
  189.                 elif child['kind'] == 't1':
  190.                     text = child['data']['body_html']
  191.                 elif child['kind'] == 'more':
  192.                     chains.extend(['/thread/' + chain for chain in child['data']['children']])
  193.                 else:
  194.                     raise ParsingError(json_url)
  195.                 if text is not None and len(text) > 0:
  196.                     soup = BeautifulSoup(html.unescape(text), 'lxml')
  197.                     new_urls = set(a.get('href') for a in soup.find_all('a'))
  198.                     urls.update(url for url in new_urls if re.match(PATTERNS['itch_game'], url))
  199.                     has_more.update(url for url in new_urls if re.match(PATTERNS['itch_group'], url))
  200.         print(f' sleeping for {sleep_time}s')
  201.         sleep(sleep_time)
  202.     print(f' got {len(urls)} games | {len(has_more)} collections/sales')
  203.     return urls, has_more
  204.  
  205.  
  206. def get_urls(url, sleep_time=15, max_page=None):
  207.     global PATTERNS
  208.  
  209.     print(f'getting games from {url}')
  210.     if re.match(PATTERNS['itch_collection'], url):
  211.         return get_from_itch_group(url, sleep_time, max_page)
  212.     elif re.match(PATTERNS['itch_sale'], url):
  213.         return get_from_itch_group(url, sleep_time, sale=True)
  214.     elif re.match(PATTERNS['reddit_thread'], url):
  215.         return get_from_reddit_thread(url, sleep_time)
  216.     else:
  217.         # breakpoint()
  218.         raise NotImplementedError(f'{url} is not supported')
  219.  
  220.  
  221. def claim(url, driver):
  222.     '''
  223.    INPUTS
  224.      url     game url
  225.      driver  a webdriver for a browser that is logged in to itch.io
  226.    OUTPUT
  227.      status
  228.        'claimed'           success
  229.        'dl_only'           cannot be claimed
  230.        'web'               cannot be claimed or downloaded, web game
  231.        'buy'               not for sale
  232.        'claimed has_more'  success, and indicaes that the game is connected to another sale
  233.        'removed'           game does not exist
  234.        'always_free'       dl_only game that is always free
  235.    '''
  236.     global PATTERNS
  237.  
  238.     url = f"https://{re.search(PATTERNS['itch_game'], url)['game']}"
  239.     print(f'handling {url}')
  240.  
  241.     driver.get(url)
  242.     original_window = driver.current_window_handle
  243.     assert len(driver.window_handles) == 1
  244.  
  245.     # removed game
  246.     try:
  247.         driver.find_element_by_css_selector('div.not_found_game_page')
  248.         return 'removed'
  249.     except NoSuchElementException:
  250.         pass
  251.  
  252.     # already owned
  253.     try:
  254.         if 'You own this' in driver.find_element_by_css_selector('div.purchase_banner_inner h2').get_attribute('textContent'):
  255.             print(f' already claimed: {url}')
  256.             return 'claimed'
  257.     except NoSuchElementException:
  258.         pass
  259.  
  260.     # check if claimable, download only, or a web game
  261.     try:
  262.         buy = driver.find_element_by_css_selector('div.buy_row a.buy_btn')
  263.     except NoSuchElementException:
  264.         try:
  265.             buy = driver.find_element_by_css_selector('section.game_download a.buy_btn')
  266.         except NoSuchElementException:
  267.             try:
  268.                 driver.find_element_by_css_selector('div.uploads')
  269.                 print(f' download only: {url}')
  270.                 return 'dl_only'
  271.             except NoSuchElementException:
  272.                 try:
  273.                     driver.find_element_by_css_selector('div.html_embed_widget')
  274.                     print(f' web game: {url}')
  275.                     return 'web'
  276.                 except NoSuchElementException as nse_e:
  277.                     raise ParsingError(url) from nse_e
  278.  
  279.     if 'Download Now' in buy.get_attribute('textContent'):
  280.         try:
  281.             sale_rate = driver.find_element_by_css_selector('.sale_rate')
  282.         except NoSuchElementException as nse_e:
  283.             print(f' always free: {url}')
  284.             return 'always_free'
  285.         else:
  286.             if '100' in sale_rate.get_attribute('textContent'):
  287.                 print(f' download only: {url}')
  288.                 return 'dl_only'
  289.             else:
  290.                 raise ParsingError(url)
  291.     elif 'buy now' in buy.get_attribute('textContent').lower():
  292.         print(f' buy: {url}')
  293.         return 'buy'
  294.     elif 'pre-order' in buy.get_attribute('textContent').lower():
  295.         print(f' buy (pre-order): {url}')
  296.         return 'buy'
  297.     # claim
  298.     elif 'Download or claim' in buy.get_attribute('textContent'):
  299.         #buy.location_once_scrolled_into_view
  300.         #buy.click()
  301.         driver.get(f'{url}/purchase')
  302.  
  303.         try:
  304.             no_thanks = driver.find_element_by_css_selector('a.direct_download_btn')
  305.         except NoSuchElementException as nse_e:
  306.             raise ParsingError(url) from nse_e
  307.  
  308.         if 'No thanks, just take me to the downloads' in no_thanks.get_attribute('textContent'):
  309.             no_thanks.click()
  310.  
  311.             # in case the download page opens in a new window
  312.             original_window = switch_to_new_window(driver, original_window)
  313.  
  314.             try:
  315.                 claim_btn = driver.find_element_by_css_selector('div.claim_to_download_box form button')
  316.             except NoSuchElementException as nse_e:
  317.                 raise ParsingError(url) from nse_e
  318.  
  319.             if 'claim' in claim_btn.get_attribute('textContent').lower():
  320.                 claim_btn.click()
  321.  
  322.                 try:
  323.                     message = driver.find_element_by_css_selector('div.game_download_page div.inner_column p')
  324.                 except NoSuchElementException as nse_e:
  325.                     raise ParsingError(url) from nse_e
  326.  
  327.                 if 'for the promotion' in message.get_attribute('textContent'):
  328.                     print(f' just claimed | part of a sale: {url}')
  329.                     return 'claimed has_more'
  330.                 if 'You claimed this game' in message.get_attribute('textContent'):
  331.                     print(f' just claimed: {url}')
  332.                     return 'claimed'
  333.                 else:
  334.                     raise ParsingError(url)
  335.             else:
  336.                 raise ParsingError(url)
  337.         else:
  338.             raise ParsingError(url)
  339.     else:
  340.         raise ParsingError(url)
  341.  
  342.  
  343. def create_driver(enable_images=False):
  344.     options = webdriver.firefox.options.Options()
  345.     if not enable_images:
  346.         options.set_preference('permissions.default.image', 2)
  347.     if os.path.exists('geckodriver.exe'):
  348.         driver = webdriver.Firefox(options=options, executable_path='geckodriver.exe')
  349.     else:
  350.         # geckodriver should be in PATH
  351.         driver = webdriver.Firefox(options=options)
  352.     driver.implicitly_wait(10)
  353.     return driver
  354.  
  355.  
  356. def switch_to_new_window(driver, original_window):
  357.     '''If a new window was opened, switch to it'''
  358.     sleep(1)
  359.     if len(driver.window_handles) > 1:
  360.         new_handle = None
  361.         for window_handle in driver.window_handles:
  362.             if window_handle != original_window:
  363.                 new_handle = window_handle
  364.                 break
  365.         driver.close()
  366.         driver.switch_to.window(new_handle)
  367.         return new_handle
  368.     return original_window
  369.  
  370.  
  371. def log(name, data):
  372.     with open(name, 'a') as f:
  373.         for k, v in data.items():
  374.             f.write(k + ': ' + str(v) + '\n')
  375.  
  376.  
  377. def load_history(name):
  378.     global HISTORY_KEYS
  379.  
  380.     try:
  381.         f = open(name, 'r')
  382.         with f:
  383.             data = json.load(f)
  384.         print(f'loaded history from file {name}')
  385.     except FileNotFoundError:
  386.         data = dict()
  387.         print(f'new history file will be created: {name}')
  388.     history = {k: set(data.get(k, [])) for k in HISTORY_KEYS}
  389.     return history
  390.  
  391.  
  392. def save_history(name, data):
  393.     print(f'writing history to file {name}')
  394.     with open(name, 'w') as f:
  395.         json.dump({k: list(v) for k, v in data.items()}, f, indent=2)
  396.  
  397.  
  398. def print_summary(history_file, history):
  399.     global SOURCES, PATTERNS, PROCESSED_GAMES
  400.  
  401.     print('\nSUMMARY')
  402.  
  403.     if not os.path.exists(history_file):
  404.         print(f'No history is stored in {history_file}')
  405.         return
  406.  
  407.     print(f'History stored in {history_file}')
  408.     print()
  409.  
  410.     print(f'Using {len(SOURCES)} main sources (use --recheck to recheck them)')
  411.     print(f"Discovered {len(history['urls'])} games")
  412.     print(f"Claimed {len(history['claimed'])} games")
  413.     not_processed = history['urls'].difference(*map(history.get, PROCESSED_GAMES))
  414.     print(f"{len(not_processed)} games should be claimed on the next run")
  415.     print()
  416.  
  417.     itch_groups = set(filter(re.compile(PATTERNS['itch_group']).match, history['has_more']))
  418.     itch_games = set(filter(re.compile(PATTERNS['itch_game']).match, history['has_more']))
  419.     print(f"{len(itch_groups)} discovered collections / sales should be checked on the next run")
  420.     print(f"{len(history['checked_groups'])} discovered collections / sales were checked (use --recheck-groups to recheck them)")
  421.     print(f"{len(itch_games)} discovered games are connected to sales that may not have been checked")
  422.     print(f"{len(history['removed'])} games were removed or invalid")
  423.     print()
  424.  
  425.     print(f"Play {len(history['web'])} non-claimable and non-downloadable games online:")
  426.     for url in history['web']:
  427.         print(f'  {url}')
  428.     print()
  429.  
  430.     print(f"Download {len(history['dl_only'])} non-claimable games manually:")
  431.     for url in history['dl_only']:
  432.         print(f'  {url}')
  433.     print(f"{len(history['always_free'])} downloadable games are always free (not listed above)")
  434.     print(f"{len(history['downloaded'])} games were marked as downloaded (to mark games: move them in the history file from 'dl_only' to 'downloaded')")
  435.     print(f"{len(history['dl_only_old'])} downloadable games were skipped (moved to 'dl_only_old')")
  436.     print()
  437.  
  438.     print(f"Buy {len(history['buy'])} non-free games.")
  439.     print()
  440.  
  441.     print(f"Error encountered in {len(history['error'])} games (some maybe already solved):")
  442.     for url in history['error']:
  443.         print(f'  {url}')
  444.     print()
  445.  
  446.  
  447. def get_urls_and_update_history(history, sources, itch_groups):
  448.     '''
  449.    INPUT
  450.      history      a dict that'll be updates as `sources` are processed
  451.      sources      sources to get links from
  452.      itch_groups  itch sales/collections in `sources` that should be marked as checked in `history`
  453.    '''
  454.     for i, source in enumerate(sources):
  455.         print(f'{i+1}/{len(sources)}')
  456.         new_urls, new_more = get_urls(source)
  457.         history['urls'].update(new_urls)
  458.         history['has_more'].update(new_more)
  459.     history['checked_groups'].update(itch_groups)
  460.     history['has_more'].difference_update(history['checked_groups'])
  461.  
  462.  
  463. def main():
  464.     global SOURCES, HISTORY_KEYS, PROCESSED_GAMES
  465.  
  466.     run_time = int(time())
  467.     script_name = os.path.basename(os.path.splitext(sys.argv[0])[0])
  468.     log_file = f'{script_name}.log.txt'
  469.     default_history_file = f'{script_name}.history.json'
  470.     log(log_file, {'# new run': run_time})
  471.  
  472.     arg_parser = argparse.ArgumentParser(
  473.         description=f'Claim free itch.io games in an itch.io sale/collection or reddit thread. \
  474.                     Writes the results (game links, claimed games, ..) to history_file. Logs to {log_file}')
  475.     arg_parser.add_argument('history_file', nargs='?', help=f'a json file generated by a previous run of this script (default: {default_history_file})')
  476.     arg_parser.add_argument('--show-history', action='store_true', help='show summary of history in history_file and exit')
  477.     arg_parser.add_argument('--recheck', action='store_true', help='reload game links from SOURCES')
  478.     arg_parser.add_argument('--recheck-groups', action='store_true', help='reload game links from discovered itch collections / sales')
  479.     arg_parser.add_argument('--enable-images', action='store_true', help='load images in the browser while claiming games')
  480.     arg_parser.add_argument('--ignore', action='store_true', help='continue even if an error occurs when handling a game')
  481.     args = arg_parser.parse_args()
  482.  
  483.     if args.history_file is not None:
  484.         history_file = args.history_file
  485.     else:
  486.         history_file = default_history_file
  487.     history = load_history(history_file)
  488.     log(log_file, {'history_file': history_file})
  489.     log(log_file, {k: len(v) for k, v in history.items()})
  490.  
  491.     if args.show_history:
  492.         print_summary(history_file, history)
  493.         sys.exit(0)
  494.  
  495.     # getting game links
  496.     itch_groups = set(filter(re.compile(PATTERNS['itch_group']).match, history['has_more']))
  497.     check_sources = not os.path.exists(history_file) or args.recheck
  498.     check_groups = len(itch_groups) > 0 or args.recheck_groups
  499.     if check_sources or check_groups:
  500.         print('will reload game urls from the internet')
  501.         # keep getting newly discovered sales/collections
  502.         first_pass = True
  503.         while True:
  504.             target_sources = set()
  505.             itch_groups = set(filter(re.compile(PATTERNS['itch_group']).match, history['has_more']))
  506.             if first_pass:
  507.                 if check_sources:
  508.                     target_sources.update(SOURCES)
  509.                 if args.recheck_groups:
  510.                     itch_groups.update(history['checked_groups'])
  511.             else:
  512.                 if len(itch_groups) == 0:
  513.                     break
  514.                 else:
  515.                     print('getting links from newly discovered sales/collections')
  516.             target_sources.update(itch_groups)
  517.             get_urls_and_update_history(history, target_sources, itch_groups)
  518.             first_pass = False
  519.             log(log_file, {'## got links': time(), 'sources': target_sources, 'urls': history['urls'], 'has_more': history['has_more']})
  520.     else:
  521.         print('using game urls saved in the history file')
  522.         print(' pass the option --recheck and/or --recheck-groups to reload game urls from the internet')
  523.  
  524.     # claiming games
  525.     url = None
  526.     sleep_time = 15
  527.     try:
  528.         ignore = set().union(*map(history.get, PROCESSED_GAMES))
  529.         valid = history['urls'].difference(ignore)
  530.         if len(valid) > 0:
  531.             with create_driver(args.enable_images) as driver:
  532.                 driver.get('https://itch.io/login')
  533.                 # manually log in
  534.                 input('A new Firefox window was opened. Log in to itch then click enter to continue')
  535.                 for i, url in enumerate(valid):
  536.                     print(f"{i+1}/{len(valid)} ({len(history['urls'])})")
  537.                     if url not in ignore:
  538.                         try:
  539.                             result = claim(url, driver)
  540.                         except ParsingError as pe:
  541.                             if not args.ignore:
  542.                                 raise
  543.                             history['error'].add(pe.url)
  544.                             print(f'Unknown Error: skipping {pe.url}')
  545.                         else:
  546.                             if url in history['error']:
  547.                                 history['error'].remove(url)
  548.                                 history['old_error'].add(url)
  549.                             if 'claimed' in result:
  550.                                 history['claimed'].add(url)
  551.                             if 'web' in result:
  552.                                 history['web'].add(url)
  553.                             if 'has_more' in result:
  554.                                 history['has_more'].add(url)
  555.                             if 'buy' in result:
  556.                                 history['buy'].add(url)
  557.                             if 'removed' in result:
  558.                                 history['removed'].add(url)
  559.                             if 'always_free' in result:
  560.                                 history['always_free'].add(url)
  561.                                 continue
  562.                             if 'dl_only' in result:
  563.                                 history['dl_only'].add(url)
  564.                             print(f' sleeping for {sleep_time}s')
  565.                         sleep(sleep_time)
  566.     except ParsingError as pe:
  567.         history['error'].add(pe.url)
  568.         raise
  569.     except Exception as e:
  570.         if url is not None:
  571.             history['error'].add(url)
  572.         raise
  573.     finally:
  574.         print()
  575.         save_history(history_file, history)
  576.         print_summary(history_file, history)
  577.  
  578.  
  579. if __name__ == '__main__':
  580.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement