<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-

import json
import httplib
import os
import argparse
import logging

def main():
  args = getParsedArguments()
  seen_episodes = getSeenEpisodesFromRPC(args.host)

  for episode in  seen_episodes:
    if args.delete and args.host == 'localhost':
      if deleteFileAndSubtitle( episode['file'] ):
        print "[OK] Deleted episode " + episode['title']
      else:
        print "[FAILED] Cannot delete " + episode['file']
    else:
      printEpisode( episode )

  show_count = len(seen_episodes)
  print "TOTAL: "  + str(show_count)

def getParsedArguments():
  """
  Returns the parsed arguments given in the command line
  """

  parser = argparse.ArgumentParser(
    description='Lists all TV Shows marked as seen and allows to delete them')

  # Optional arguments
  parser.add_argument('-d', '--delete',
                      action='store_true', # Allows this argument to behave like a flag
                      help='Delete files and subtitles of seen TV shows. Ignored when using the flag --host'
                      )
  parser.add_argument('-H', '--host',
                      help="""Hostname or IP of a remote machine running the Kodi JSON-RPC service.
                      Remote deletion of files through the RPC service is not suported. Ignores
                      flag --delete if present.""",
                      default="localhost"
                      )
  args = parser.parse_args()
  return args


def printEpisode(episode):
    print "--"
    print episode['label']
    print episode['file']
    print "Last played: " + episode['lastplayed']
    print "Play count: " + str( episode['playcount'])

def deleteFileAndSubtitle(file):
  try:
    isDeleted = os.remove(file)

    # Delete subtitle if present:
    basename = os.path.splitext(file)[0]
    subtitle = basename + ".srt"
    if os.path.isfile(subtitle):
      os.remove(file)

    return isDeleted
  except OSError:
    return False


def getSeenEpisodesFromRPC(rpc_host='localhost'):
  """
  Retrieves from Kodi JSON-RPC service the list of episodes
  marked as seen and not played in the last month (avoids
  immediate deletion)
  """<commit_msg>Encode files, log delete errors<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-

import json
import httplib
import os
import argparse
import logging

def main():
  args = getParsedArguments()
  seen_episodes = getSeenEpisodesFromRPC(args.host)

  for episode in  seen_episodes:
    if args.delete and args.host == 'localhost':
      if deleteFileAndSubtitle( episode['file'].encode('utf-8') ):
        print "[OK] Deleted episode " + episode['title'].encode('utf-8')
    else:
      printEpisode( episode )

  show_count = len(seen_episodes)
  print "TOTAL: "  + str(show_count)

def getParsedArguments():
  """
  Returns the parsed arguments given in the command line
  """

  parser = argparse.ArgumentParser(
    description='Lists all TV Shows marked as seen and allows to delete them')

  # Optional arguments
  parser.add_argument('-d', '--delete',
                      action='store_true', # Allows this argument to behave like a flag
                      help='Delete files and subtitles of seen TV shows. Ignored when using the flag --host'
                      )
  parser.add_argument('-H', '--host',
                      help="""Hostname or IP of a remote machine running the Kodi JSON-RPC service.
                      Remote deletion of files through the RPC service is not suported. Ignores
                      flag --delete if present.""",
                      default="localhost"
                      )
  args = parser.parse_args()
  return args


def printEpisode(episode):
    print "--"
    print episode['label'].encode('utf-8')
    print episode['file'].encode('utf-8')
    print "Last played: " + episode['lastplayed']
    print "Play count: " + str( episode['playcount'])

def deleteFileAndSubtitle(file):
  try:
    print(file)
    isDeleted = os.remove(file)

    # Delete subtitle if present:
    basename = os.path.splitext(file)[0]
    subtitle = basename + ".srt"
    if os.path.isfile(subtitle):
      os.remove(subtitle)

    return isDeleted
  except OSError as e:
    logging.error(e)
    return False


def getSeenEpisodesFromRPC(rpc_host='localhost'):
  """
  Retrieves from Kodi JSON-RPC service the list of episodes
  marked as seen and not played in the last month (avoids
  immediate deletion)
  """
{'fraction_non_alphanumeric': 0.10561797752808989, 'fraction_numerical': 0.0017977528089887641, 'mean_word_length': 2.648360655737705, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6690052', 'n_tokens_mistral': 1322, 'n_tokens_neox': 1271, 'n_words': 403}