#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# feed_proxy.py
#
# Copyright (C) 2021-2022 Franco Masotti (franco \D\o\T masotti {-A-T-} tutanota \D\o\T com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
r"""Save RSS feeds."""

import pathlib
import shlex
import sys
import time

import requests
import yaml

if __name__ == '__main__':
    configuration_file = shlex.quote(sys.argv[1])
    config = yaml.load(open(configuration_file, 'r'), Loader=yaml.SafeLoader)

    for f in config['feeds']:
        for feed in f:
            try:
                if f[feed]['user_agent'] == str():
                    headers = dict()
                else:
                    headers = {'User-Agent': f[feed]['user_agent']}
                r = requests.get(f[feed]['url'], headers=headers)
                full_path_file = str(
                    pathlib.Path(config['files']['base_path'],
                                 f[feed]['relative_path']))
                # Write the new file as binary.
                with open(full_path_file, 'wb') as f:
                    f.write(r.content)

            except requests.exceptions.RequestException as e:
                print(e)

            time.sleep(config['network']['sleep_seconds_between_feeds'])
