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

# Newspipe - A web news aggregator.
# Copyright (C) 2010-2020 <NAME> - https://www.cedricbonhomme.org
#
# For more information: https://git.sr.ht/~cedric/newspipe
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

__author__ = "<NAME>"
__version__ = "$Revision: 1.10 $"
__date__ = "$Date: 2010/12/07 $"
__revision__ = "$Date: 2016/11/22 $"
__copyright__ = "Copyright (c) <NAME>"
__license__ = "AGPLv3"

import glob
import logging
import operator
import os
import re
import subprocess
import sys
import urllib
from collections import Counter
from contextlib import contextmanager

import sqlalchemy
from flask import request

from newspipe.bootstrap import application
from newspipe.controllers import ArticleController
from newspipe.lib.utils import clear_string

try:
    from urlparse import urlparse, parse_qs, urlunparse
except:
    from urllib.parse import urlparse, parse_qs, urlunparse, urljoin


logger = logging.getLogger(__name__)

ALLOWED_EXTENSIONS = set(["xml", "opml", "json"])


def is_safe_url(target):
    """
    Ensures that a redirect target will lead to the same server.
    """
    ref_url = urlparse(request.host_url)
    test_url = urlparse(urljoin(request.host_url, target))
    return test_url.scheme in ("http", "https") and ref_url.netloc == test_url.netloc


def get_redirect_target():
    """
    Looks at various hints to find the redirect target.
    """
    for target in request.args.get("next"), request.referrer:
        if not target:
            continue
        if is_safe_url(target):
            return target


def allowed_file(filename):
    """
    Check if the uploaded file is allowed.
    """
    return "." in filename and filename.rsplit(".", 1)[1] in ALLOWED_EXTENSIONS


@contextmanager
def opened_w_error(filename, mode="r"):
    try:
        f = open(filename, mode)
    except IOError as err:
        yield None, err
    else:
        try:
            yield f, None
        finally:
            f.close()


def fetch(id, feed_id=None):
    """
    Fetch the feeds in a new processus.
    The default crawler ("asyncio") is launched with the manager.
    """
    cmd = [
        sys.executable,
        application.config["BASE_DIR"] + "/manager.py",
        "fetch_asyncio",
        "--user_id=" + str(id),
    ]
    if feed_id:
        cmd.append("--feed_id=" + str(feed_id))
    return subprocess.Popen(cmd, stdout=subprocess.PIPE)


def history(user_id, year=None, month=None):
    """
    Sort articles by year and month.
    """
    articles_counter = Counter()
    articles = ArticleController(user_id).read()
    if None != year:
        articles = articles.filter(sqlalchemy.extract("year", "Article.date") == year)
        if None != month:
            articles = articles.filter(
                sqlalchemy.extract("month", "Article.date") == month
            )<commit_msg>fixed generated command to fetch newly created feed.<commit_after>#! /usr/bin/env python
# -*- coding: utf-8 -*-

# Newspipe - A web news aggregator.
# Copyright (C) 2010-2020 <NAME> - https://www.cedricbonhomme.org
#
# For more information: https://git.sr.ht/~cedric/newspipe
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

__author__ = "<NAME>"
__version__ = "$Revision: 1.10 $"
__date__ = "$Date: 2010/12/07 $"
__revision__ = "$Date: 2016/11/22 $"
__copyright__ = "Copyright (c) <NAME>"
__license__ = "AGPLv3"

import glob
import logging
import operator
import os
import re
import subprocess
import sys
import urllib
from collections import Counter
from contextlib import contextmanager

import sqlalchemy
from flask import request

from newspipe.bootstrap import application
from newspipe.controllers import ArticleController
from newspipe.lib.utils import clear_string

try:
    from urlparse import urlparse, parse_qs, urlunparse
except:
    from urllib.parse import urlparse, parse_qs, urlunparse, urljoin


logger = logging.getLogger(__name__)

ALLOWED_EXTENSIONS = set(["xml", "opml", "json"])


def is_safe_url(target):
    """
    Ensures that a redirect target will lead to the same server.
    """
    ref_url = urlparse(request.host_url)
    test_url = urlparse(urljoin(request.host_url, target))
    return test_url.scheme in ("http", "https") and ref_url.netloc == test_url.netloc


def get_redirect_target():
    """
    Looks at various hints to find the redirect target.
    """
    for target in request.args.get("next"), request.referrer:
        if not target:
            continue
        if is_safe_url(target):
            return target


def allowed_file(filename):
    """
    Check if the uploaded file is allowed.
    """
    return "." in filename and filename.rsplit(".", 1)[1] in ALLOWED_EXTENSIONS


@contextmanager
def opened_w_error(filename, mode="r"):
    try:
        f = open(filename, mode)
    except IOError as err:
        yield None, err
    else:
        try:
            yield f, None
        finally:
            f.close()


def fetch(id, feed_id=None):
    """
    Fetch the feeds in a new processus.
    The default crawler ("asyncio") is launched with the manager.
    """
    cmd = [
        sys.executable,
        "manager.py",
        "fetch_asyncio",
        "--user_id=" + str(id),
    ]
    if feed_id:
        cmd.append("--feed_id=" + str(feed_id))
    return subprocess.Popen(cmd, stdout=subprocess.PIPE)


def history(user_id, year=None, month=None):
    """
    Sort articles by year and month.
    """
    articles_counter = Counter()
    articles = ArticleController(user_id).read()
    if None != year:
        articles = articles.filter(sqlalchemy.extract("year", "Article.date") == year)
        if None != month:
            articles = articles.filter(
                sqlalchemy.extract("month", "Article.date") == month
            )
{'fraction_non_alphanumeric': 0.10397379290699331, 'fraction_numerical': 0.00911551061102407, 'mean_word_length': 3.15748963883955, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 4, 'lorem ipsum': 0, 'www.': 4, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2613987', 'n_tokens_mistral': 2151, 'n_tokens_neox': 2055, 'n_words': 710}