aboutsummaryrefslogtreecommitdiff
path: root/src/crawler/default_crawler.py
blob: 543724bc2a37001ec83d358e7ae997fd1772d925 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#! /usr/bin/env python
# -*- coding: utf-8 -

# newspipe - A Web based news aggregator.
# Copyright (C) 2010-2019  Cédric Bonhomme - https://www.cedricbonhomme.org
#
# For more information : https://gitlab.com/newspipe/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__ = "Cedric Bonhomme"
__version__ = "$Revision: 4.0 $"
__date__ = "$Date: 2010/09/02 $"
__revision__ = "$Date: 2010/05/21 $"
__copyright__ = "Copyright (c) Cedric Bonhomme"
__license__ = "AGPLv3"

import io
import asyncio
import logging
import requests
import feedparser
import dateutil.parser
from datetime import datetime, timezone, timedelta
from sqlalchemy import or_

import conf
from bootstrap import db
from web.models import User
from web.controllers import FeedController, ArticleController
from lib.feed_utils import construct_feed_from, is_parsing_ok
from lib.article_utils import construct_article, extract_id, \
                                    get_article_content

logger = logging.getLogger(__name__)

sem = asyncio.Semaphore(5)


def get(*args, **kwargs):
    #kwargs["connector"] = aiohttp.TCPConnector(verify_ssl=False)
    try:
        logger.info('Retrieving feed {}'.format(args[0]))
        resp = requests.get(args[0], timeout=20.0)
    except requests.ReadTimeout:
        logger.info('Timeout when reading feed {}'.format(args[0]))
        raise e
    content = io.BytesIO(resp.content)
    try:
        data = feedparser.parse(content)
    except Exception as e:
        raise e
    return data



def parse_feed(user, feed):
    """
    Fetch a feed.
    Update the feed and return the articles.
    """
    parsed_feed = None
    up_feed = {}
    articles = []
    #with (await sem):
    try:
        parsed_feed = get(feed.link)
    except Exception as e:
        up_feed['last_error'] = str(e)
        up_feed['error_count'] = feed.error_count + 1
        logger.exception("error when parsing feed: " + str(e))
    finally:
        up_feed['last_retrieved'] = datetime.now(dateutil.tz.tzlocal())
        if parsed_feed is None:
            try:
                FeedController().update({'id': feed.id}, up_feed)
            except Exception as e:
                logger.exception('something bad here: ' + str(e))
            return

    if not is_parsing_ok(parsed_feed):
        up_feed['last_error'] = str(parsed_feed['bozo_exception'])
        up_feed['error_count'] = feed.error_count + 1
        FeedController().update({'id': feed.id}, up_feed)
        return
    if parsed_feed['entries'] != []:
        articles = parsed_feed['entries']

    up_feed['error_count'] = 0
    up_feed['last_error'] = ""

    # Feed information
    try:
        construct_feed_from(feed.link, parsed_feed).update(up_feed)
    except:
         logger.exception('error when constructing feed: {}'.format(feed.link))
    if feed.title and 'title' in up_feed:
        # do not override the title set by the user
        del up_feed['title']
    FeedController().update({'id': feed.id}, up_feed)

    return articles


async def insert_articles(queue, nḅ_producers=1):
    """Consumer coroutines.
    """
    nb_producers_done = 0
    while True:
        item = await queue.get()
        if item is None:
            nb_producers_done += 1
            if nb_producers_done == nḅ_producers:
                print('All producers done.')
                print('Process finished.')
                break
            continue

        user, feed, articles = item


        if None is articles:
            logger.info('None')
            articles = []

        logger.info('Inserting articles for {}'.format(feed.title))

        art_contr = ArticleController(user.id)
        for article in articles:
            new_article = await construct_article(article, feed)

            try:
                existing_article_req = art_contr.read(feed_id=feed.id,
                                entry_id=extract_id(article))
            except Exception as e:
                logger.exception("existing_article_req: " + str(e))
                continue
            exist = existing_article_req.count() != 0
            if exist:
                continue

            # insertion of the new article
            try:
                art_contr.create(**new_article)
                logger.info('New article added: {}'.format(new_article['link']))
            except Exception:
                logger.exception('Error when inserting article in database:')
                continue


async def retrieve_feed(queue, users, feed_id=None):
    """
    Launch the processus.
    """
    for user in users:
        logger.info('Starting to retrieve feeds for {}'.format(user.nickname))
        filters = {}
        filters['user_id'] = user.id
        if feed_id is not None:
            filters['id'] = feed_id
        filters['enabled'] = True
        filters['error_count__lt'] = conf.DEFAULT_MAX_ERROR
        filters['last_retrieved__lt'] = datetime.now() - \
                                    timedelta(minutes=conf.FEED_REFRESH_INTERVAL)
        feeds = FeedController().read(**filters).all()


        if feeds == []:
            logger.info('No feed to retrieve for {}'.format(user.nickname))


        for feed in feeds:
            articles = parse_feed(user, feed)
            await queue.put((user, feed, articles))

    await queue.put(None)
bgstack15