~josealberto4444/apodnasabot

ref: 262d543724029575738bd87e6f3e5963a5d772f6 apodnasabot/api.py -rw-r--r-- 5.4 KiB
262d5437José Alberto Orejuela García Fix a new error in scrapping explanation 1 year, 4 months ago
                                                                                
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
# Copyright © 2019-2020 José Alberto Orejuela García (josealberto4444)
#
# 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/>.

import configparser
import datetime
import json
import os.path
import re
import requests
import youtube_dl

def read_config(section, key):
    config = configparser.ConfigParser()
    config.read('config.cfg')
    return config[section][key]

def is_invalid(date):
    try:
        datetime.datetime.strptime(date, '%Y-%m-%d')
    except ValueError:
        return "Incorrect date format, should be YYYY-MM-DD."
    else:
        return False

class Apod:

    def __init__(self, *args):
        self.api_key = read_config('NASA_API', 'api_key')
        if args:
            self.date = args[0]
        else:
            self.date = ''
            self.date = self.ask_api()['date']
        self.filename = 'data/' + self.date
        self.error = False
        self.consult()
        if not self.error:
            self.title = self.api_response['title']
            self.media_type = self.api_response['media_type']
            if self.media_type == 'image':
                self.hdlink = self.api_response['hdurl']
            self.link = self.api_response['url']
            self.explanation()

    def ask_api(self):
        baseurl = 'https://api.nasa.gov/planetary/apod'
        payload = {'api_key': self.api_key, 'date': self.date}
        r = requests.get(baseurl, params=payload)
        return r.json()

    def consult(self):
        if os.path.exists('data/' + self.date + '.json'):
            with open(self.filename + '.json', 'rt') as f:
                self.api_response = json.load(f)
        else:
            self.api_response = self.ask_api()
            if 'code' in self.api_response:
                if self.api_response['code'] == 400:
                    self.error = self.api_response['msg']
                else:
                    self.error = self.api_response['code'] + ': ' + self.api_response['msg']
            else:
                with open(self.filename + '.json', 'wt') as f:
                    json.dump(self.api_response, f)

    def get_userpage(self):
        shortdate = self.date.replace('-', '')
        shortdate = shortdate[2:]
        url = 'https://apod.nasa.gov/apod/ap' + shortdate + '.html'
        payload = {}
        r = requests.get(url, params=payload)
        return r.text

    def scrap_explanation(self, pagesource):
        re_explanation = re.compile("Explanation: </b>(.*?)<p>", flags=re.DOTALL) # Compile regex for extracting explanation.
        explanation = re_explanation.search(pagesource).groups()[0] # Extract explanation.
        explanation = explanation.replace('/\n', '/') # Fix split URLs along several lines.
        explanation = explanation.replace('\n>', '>') # Fix split HTML tags.
        explanation = explanation.replace('<a/>', '</a>') # Fix typos (they seem to write the HTML by hand, yes).
        explanation = explanation.replace('\n', ' ') # Delete all newlines.
        explanation = explanation.replace('<br>', ' ') # Delete all HTML newlines.
        explanation = re.sub('\s+', ' ', explanation).strip() # Substitute repeated spaces and strips the ones at the beginning and the end of the string.
        explanation = re.sub(r'<a([^>]*)href=["\'](?!http)([^"\']*)["\']([^>]*)>', r'<a\1href="https://apod.nasa.gov/apod/\2"\3>', explanation) # Change relative paths to absolute.
        return explanation

    def save_explanation(self, explanation):
        with open(self.filename + '.html', 'wt') as f:
            f.write(explanation)

    def explanation(self):
        filename = self.filename + '.html'
        if os.path.exists(filename):
            with open(filename, 'rt') as f:
                self.explanation = f.read()
            self.html = True
        else:
            try:
                userpage = self.get_userpage()
                explanation = self.scrap_explanation(userpage)
            except:
                explanation = self.api_response['explanation']
                self.html = False
            else:
                self.save_explanation(explanation)
                self.html = True
            self.explanation = explanation

# TO-DO: Check if already downloaded first
#    def download_media():
#        if self.media_type == 'image':
#            link = self.api_response['hdurl']
#            r = requests.get(link)
#            extension = os.path.splitext(link)[1]
#            filename = self.filename + extension
#            with open(filename, 'wb') as f:
#                for chunk in r.iter_content(chunk_size=128):
#                    f.write(chunk)
#        elif self.media_type == 'video':
#            filename = self.filename + '.%(ext)s'
#            ydl_opts = {'outtmpl': filename, 'quiet': True}
#            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
#                ydl.download([api_response['url']])