ServicePelican._set_filename()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
1
# coding: utf-8
2
import arrow
3
4
from slugify import slugify
5
6
# django classes
7
from django.conf import settings
8
from logging import getLogger
9
10
# django_th classes
11
from django_th.services.services import ServicesMgr
12
from django_th.tools import to_datetime
13
14
"""
15
    TH_SERVICES = (
16
        ...
17
        'th_pelican.my_pelican.ServicePelican',
18
        ...
19
    )
20
"""
21
22
logger = getLogger('django_th.trigger_happy')
23
24
25
class ServicePelican(ServicesMgr):
26
    """
27
        Service Pelican
28
    """
29
    def __init__(self, token=None, **kwargs):
30
        super(ServicePelican, self).__init__(token, **kwargs)
31
        self.AUTHOR = settings.TH_PELICAN_AUTHOR \
32
            if settings.TH_PELICAN_AUTHOR else ''
33
34
    def _create_content(self, site_title, content, pelican_path, url, **data):
35
        """
36
            create the file in the 'content' directory of pelican
37
            :param content: the content of the post
38
            :param pelican_path: where the files are created
39
            :param url: url of the datasource
40
            :param data: the data to check to be used and save
41
            :type content: string
42
            :type pelican_path: string
43
            :type url: string
44
            :type data:  dict
45
            :return: the status of the save statement
46
            :rtype: boolean
47
        """
48
        published = to_datetime(data)
49
50
        category = data.get('category') if data.get('category') else ''
51
        tags = data.get('tags') if data.get('tags') else ''
52
53
        filename = self._set_filename(data.get('title'), pelican_path)
54
55
        full_content = self._set_full_content(site_title, data.get('title'),
56
                                              published, content, url,
57
                                              category, tags)
58
59
        try:
60
            with open(filename, 'w') as f:
61
                f.write(full_content)
62
            status = True
63
        except Exception as e:
64
            logger.critical(e)
65
            status = False
66
67
        return status
68
69
    @staticmethod
70
    def _set_filename(title, pelican_path):
71
        """
72
            build the filename
73
            :param title: the title of the post
74
            :param pelican_path: where the files are created
75
            :type title: string
76
            :type pelican_path: string
77
            :return: the filename
78
            :rtype: string
79
        """
80
        # cleaning the special char
81
        name = title.replace('/', '_').replace('\\', '_').\
82
            replace(' ', '_').replace(':', '_').replace('&', '').\
83
            replace('?', '').replace('!', '')
84
85
        return "{}/{}.html".format(pelican_path, name)
86
87
    def _set_full_content(self, site_title, title, published,
88
                          content, url, category='', tags=''):
89
        """
90
            generate the full content of the file
91
            create the file in the 'content' directory of pelican
92
            :param site_title: title of the website
93
            :param title: the title of the post
94
            :param content: the content of the post
95
            :param published: the date when the data
96
            has been published by the provider
97
            :param url: url of the datasource
98
            :param category: category of this data
99
            :type site_title: string
100
            :type title: string
101
            :type content: string
102
            :type published: string
103
            :type url: string
104
            :param category: string
105
            :return: the the complet content
106
            :rtype: string
107
        """
108
109
        header = self._set_meta(title, published, category, tags)
110
        content = self._set_content(content)
111
        footer = self._set_footer(url, site_title)
112
113
        full_content = self._set_html_begin() + self._set_title(title)
114
        full_content += header + content + footer + self._set_html_end()
115
116
        return full_content
117
118
    def _set_meta(self, title, published, category='', tags=''):
119
        """
120
            the header
121
122
            :param title: the title of the post
123
            :param published: the date when the data
124
            has been published by the provider
125
            :param category: category of this data
126
            :param tags: the tags
127
            :type title: string
128
            :type published: string
129
            :param category: string
130
            :param tags: string
131
            :return: the complet head
132
            :rtype: string
133
        """
134
        slug_published = slugify(arrow.get(published).format(
135
            'YYYY-MM-DD HH:mm'))
136
        slug_title = slugify(title)
137
138
        header = '\n\t\t<meta name="date" content="{}" />\n'.format(published)
139
        if tags:
140
            header += '\t\t<meta name="tags" content="{}" />\n'.format(tags)
141
        if category:
142
            header += '\t\t<meta name="category" content="{}" />\n'.format(
143
                category)
144
        if self.AUTHOR:
145
            header += '\t\t<meta name="authors" content="{}" />\n'.format(
146
                self.AUTHOR)
147
        header += '\t\t<meta name="slug" content="{}"/>\n'.format(
148
            slug_published + '-' + slug_title)
149
        header += '\t</head>'
150
151
        return header
152
153
    @staticmethod
154
    def _set_title(title):
155
        """
156
            the title of the Article
157
            :param title: the title of the post
158
            :type title: string
159
            :return: the title
160
            :rtype: string
161
        """
162
        return "\t<head>\n\t\t<title>{}</title>".format(title)
163
164
    @staticmethod
165
    def _set_content(content):
166
        """
167
            the body of the article
168
            :param content: the content
169
            :param content: string
170
            :return: the complet content
171
            :rtype: string
172
        """
173
        return "\n\t<body>{}".format(content)
174
175
    @staticmethod
176
    def _set_footer(url, name):
177
        """
178
            Footer of the article
179
            that displays what website provided
180
            the article
181
            :param url: string of the source
182
            :param name: name of the source
183
            :return: the complet footer
184
            :rtype: string
185
        """
186
        provided = "\t\t<p><em><a href='{}'>Provided by {}</a>" \
187
                   "</em></p>\n\t</body>"
188
        return provided.format(url, name)
189
190
    @staticmethod
191
    def _set_html_begin():
192
        """
193
           start the html page
194
        """
195
        return "<html>\n"
196
197
    @staticmethod
198
    def _set_html_end():
199
        """
200
           close the html page
201
        """
202
        return "\n</html>"
203
204
    def save_data(self, trigger_id, **data):
205
        """
206
            let's save the data
207
            :param trigger_id: trigger ID from which to save data
208
            :param data: the data to check to be used and save
209
            :type trigger_id: int
210
            :type data: dict
211
            :return: the status of the save statement
212
            :rtype: boolean
213
        """
214
        from th_pelican.models import Pelican
215
216
        title, content = super(ServicePelican, self).save_data(
217
            trigger_id, **data)
218
219
        trigger = Pelican.objects.get(trigger_id=trigger_id)
220
221
        params = {'tags': trigger.tags.lower(),
222
                  'category': trigger.category.lower()}
223
224
        if 'tags' in data:
225
            del data['tags']
226
227
        params.update(data)
228
229
        if self._create_content(trigger.title, content, trigger.path,
230
                                trigger.url, **params):
231
            sentence = 'pelican {} created'
232
            status = True
233
        else:
234
            sentence = 'pelican {} not created'
235
            status = False
236
        logger.debug(sentence.format(title))
237
238
        return status
239