<commit_before>#!/usr/bin/env python
"""
Podcast Archiver v0.1: Feed parser for local podcast archive creation

Copyright (c) 2014 <NAME>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""


import sys
import getopt
import feedparser
from urllib.request import urlopen
import urllib.error
from shutil import copyfileobj
from os import path,remove,makedirs
from string import ascii_letters, digits


verbose = 1
savedir = ''
filename = ''
subdirs = False

def main():
    global verbose
    global savedir
    global subdirs
    # Parse input arguments
    try:
        opts, args = getopt.getopt(sys.argv[1:],
                                   "f:d:vs",
                                   ["feed=", "dir=", "verbose", "subdirs"])
    except getopt.GetoptError as error:
        print("An error occured during input parsing: " + error.msg)
        return

    feedlist = []
    for opt in opts:
        if opt[0] == '-f' or opt[0] == '--feed':
            feedlist.append(opt[1])
        elif opt[0] == '-d' or opt[0] == '--dir':
            if path.isdir(opt[1]):
                savedir = opt[1]
            else:
                 print("The provided directory does not exist")
                 return
        elif opt[0] == '-v' or opt[0] == '--verbose':
            verbose += 1
        elif opt[0] == '-s' or opt[0] == '--subdirs':
            subdirs = True

    if verbose > 1:
        print("Verbose level: ", verbose-1)

    for feed in feedlist:
        if verbose > 0:
            print("\nDownloading archive for: " + feed)
        download_archive(feed)
        if verbose > 0:
            print("\n ... Done.")
    return


def download_archive(nextPage):
    global savedir
    global filename

    if (verbose > 0): print("1. Gathering link list ..", end="")

    linklist = []
    while nextPage is not None:
        print(".", end="", flush=True)
        feedobj = feedparser.parse(nextPage)

        # Escape improper feed-URL
        if feedobj['status'] == 404:
            print("\nQuery returned 404 (Not Found) on ", nextPage)
            return

        nextPage = None

        if len(linklist) == 0 and subdirs:

            # Get subdir name and sanitize it
            subdir = feedobj['feed']['title']
            if path.supports_unicode_filenames:
                valid_chars = "-_.() %s%s" % (ascii_letters, digits)
                subdir = ''.join(c for c in subdir if c in valid_chars)

            subdir.replace(path.pathsep,'_')
            subdir.replace(path.sep,'_')

            curbasedir = path.join(savedir, subdir, '')

            # Create the subdir, if it does not exist
            if not path.isdir(curbasedir):
                makedirs(curbasedir)

        for link in feedobj['feed']['links']:
            if link['rel'] == 'next':
                nextPage = link['href']
                break

        # Try different feed episode layouts. 1st: 'items'
        for episode in feedobj['items']:
            linklist.append(parse_episode(episode))

        linklist = [x for x in linklist if x is not None]

        # Try different feed episode layouts. 1st: 'entries'
        if len(linklist) == 0:
            for episode in feedobj['entries']:
                linklist.append(parse_episode(episode))

            linklist = [x for x in linklist if x is not None]

        # Exit gracefully when no episodes have been found
        if len(linklist) == 0:
            print("No audio items have been found.",
                  "Maybe we don't know the feed's audio MIME type yet?")<commit_msg>If no audio urls have been found: suggest that the MIME type is unknown and the display the existing types of the current feed<commit_after>#!/usr/bin/env python
"""
Podcast Archiver v0.1: Feed parser for local podcast archive creation

Copyright (c) 2014 <NAME>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""


import sys
import getopt
import feedparser
from urllib.request import urlopen
import urllib.error
from shutil import copyfileobj
from os import path,remove,makedirs
from string import ascii_letters, digits


verbose = 1
savedir = ''
filename = ''
subdirs = False

def main():
    global verbose
    global savedir
    global subdirs
    # Parse input arguments
    try:
        opts, args = getopt.getopt(sys.argv[1:],
                                   "f:d:vs",
                                   ["feed=", "dir=", "verbose", "subdirs"])
    except getopt.GetoptError as error:
        print("An error occured during input parsing: " + error.msg)
        return

    feedlist = []
    for opt in opts:
        if opt[0] == '-f' or opt[0] == '--feed':
            feedlist.append(opt[1])
        elif opt[0] == '-d' or opt[0] == '--dir':
            if path.isdir(opt[1]):
                savedir = opt[1]
            else:
                 print("The provided directory does not exist")
                 return
        elif opt[0] == '-v' or opt[0] == '--verbose':
            verbose += 1
        elif opt[0] == '-s' or opt[0] == '--subdirs':
            subdirs = True

    if verbose > 1:
        print("Verbose level: ", verbose-1)

    for feed in feedlist:
        if verbose > 0:
            print("\nDownloading archive for: " + feed)
        download_archive(feed)
        if verbose > 0:
            print("\n ... Done.")
    return


def download_archive(nextPage):
    global savedir
    global filename

    if (verbose > 0): print("1. Gathering link list ..", end="")

    linklist = []
    while nextPage is not None:
        print(".", end="", flush=True)
        feedobj = feedparser.parse(nextPage)

        # Escape improper feed-URL
        if feedobj['status'] == 404:
            print("\nQuery returned 404 (Not Found) on ", nextPage)
            return

        nextPage = None

        if len(linklist) == 0 and subdirs:

            # Get subdir name and sanitize it
            subdir = feedobj['feed']['title']
            if path.supports_unicode_filenames:
                valid_chars = "-_.() %s%s" % (ascii_letters, digits)
                subdir = ''.join(c for c in subdir if c in valid_chars)

            subdir.replace(path.pathsep,'_')
            subdir.replace(path.sep,'_')

            curbasedir = path.join(savedir, subdir, '')

            # Create the subdir, if it does not exist
            if not path.isdir(curbasedir):
                makedirs(curbasedir)

        for link in feedobj['feed']['links']:
            if link['rel'] == 'next':
                nextPage = link['href']
                break

        # Try different feed episode layouts. 1st: 'items'
        for episode in feedobj['items']:
            linklist.append(parse_episode(episode))

        linklist = [x for x in linklist if x is not None]

        # Try different feed episode layouts. 1st: 'entries'
        if len(linklist) == 0:
            for episode in feedobj['entries']:
                linklist.append(parse_episode(episode))

            linklist = [x for x in linklist if x is not None]

        # Exit gracefully when no episodes have been found
        if len(linklist) == 0:
            print("No audio items have been found.",
                  "Maybe we don't know the feed's audio MIME type yet?")
            print("Suggestions (as defined in the feed's 'links' field:)")
            for link in episode['links']:
                print(link["type"])
{'fraction_non_alphanumeric': 0.09557560137457044, 'fraction_numerical': 0.007946735395189003, 'mean_word_length': 2.2574326687653024, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '70392', 'n_tokens_mistral': 2694, 'n_tokens_neox': 2498, 'n_words': 1003}