#!/usr/bin/env python3
# http://stackoverflow.com/questions/7243750/download-file-from-web-in-python-3

import urllib.request
import urllib.parse
import feedparser
import os
from sys import exit
from subprocess import call

###############
# Global vars #
###############
BRANGE = True
RANGE = 10
FEEDS_FILE = "feeds.txt"
LOCK = "/tmp/fetchcast.lock"

#############
# Functions #
#############
# Download the podcasts
def fetchDownload(feed, dir_name, i, j):
    # If the dictionary does not contain the key "type" then
    # continue with the other indeces of the list
    if "type" not in j:
        return
    if "audio" in j.type or "video" in j.type:
        url_download=j.href
        file_name=urllib.parse.urlparse(url_download)
        file_name=file_name.path.split('/')[-1]
        # Check if file exists, if it does then do NOT download again
        if os.path.isfile(dir_name + "/" + file_name):
            print(feed.entries[i].title + ": The file already exists. Do not download.")
        else:
            print(feed.entries[i].title + ": Downloading the file...")
            urllib.request.urlretrieve(url_download, dir_name + "/" + file_name)

# Find the URL to download the podcasts
def fetchPodcast(url):
    try:
        feed = feedparser.parse(url)
        dir_name = feed.feed.title
    except:
        print("Please check that the following URL is correct: " + url)
        return

    # Create directory (if it does not exist)
    # to download all podcasts to
    if not os.path.exists(dir_name):
        os.makedirs(dir_name)

    ###################################
    # Option A                        #
    # Only download the last X amount #
    # of files on the feed            #
    ###################################
    if BRANGE:
        max_iter = len(feed.entries)
        for i in range(RANGE):
            if i >= max_iter:
                break
            for j in feed.entries[i].links:
                fetchDownload(feed, dir_name, i, j)

    ##################################
    # Option B                       #
    # Download all files on the feed #
    ##################################
    else:
        for i in range(len(feed.entries)):
            for j in feed.entries[i].links:
                fetchDownload(feed, dir_name, i, j)

########
# MAIN #
########
if os.path.isfile(LOCK):
    exit("The program is already running. It can only be executed one time.")
else:
    call(["touch", LOCK])
    file = open(FEEDS_FILE, 'r')
    for line in file:
        if line[0] is not '#':
            fetchPodcast(line)
    call(["rm", LOCK])
