Completed
Push — master ( 02cd5b...4378c2 )
by Fox
11s
created

ServiceReddit.save_data()   B

Complexity

Conditions 3

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
dl 0
loc 29
rs 8.8571
c 2
b 0
f 0
1
# coding: utf-8
2
# add here the call of any native lib of python like datetime etc.
3
import arrow
4
5
# add the python API here if needed
6
from praw import Reddit as RedditApi
7
# django classes
8
from django.conf import settings
9
from django.core.cache import caches
10
from logging import getLogger
11
12
# django_th classes
13
from django_th.services.services import ServicesMgr
14
from django_th.models import update_result
15
from th_reddit.models import Reddit
16
17
18
"""
19
    put the following in settings.py
20
    TH_REDDIT = {
21
        'client_id': 'abcdefghijklmnopqrstuvwxyz',
22
        'client_secret': 'abcdefghijklmnopqrstuvwxyz',
23
        'user_agent': '<platform>:<app ID>:<version string> (by /u/<reddit username>)'
24
    }
25
26
    TH_SERVICES = (
27
        ...
28
        'th_reddit.my_reddit.ServiceReddit',
29
        ...
30
    )
31
"""
32
33
logger = getLogger('django_th.trigger_happy')
34
35
cache = caches['django_th']
36
37
38
class ServiceReddit(ServicesMgr):
39
    """
40
        service Reddit
41
    """
42
    def __init__(self, token=None, **kwargs):
43
        super(ServiceReddit, self).__init__(token, **kwargs)
44
        self.consumer_key = settings.TH_REDDIT['client_id']
45
        self.consumer_secret = settings.TH_REDDIT['client_secret']
46
        self.user_agent = settings.TH_REDDIT['user_agent']
47
        self.service = 'ServiceReddit'
48
        self.oauth = 'oauth2'
49
        if token:
50
            self.token = token
51
            self.reddit = RedditApi(client_id=self.consumer_key,
52
                                client_secret=self.consumer_secret,
53
                                refresh_token=token,
54
                                user_agent=self.user_agent)
55
56
    def read_data(self, **kwargs):
57
        """
58
            get the data from the service
59
            as the pocket service does not have any date
60
            in its API linked to the note,
61
            add the triggered date to the dict data
62
            thus the service will be triggered when data will be found
63
64
            :param kwargs: contain keyword args : trigger_id at least
65
            :type kwargs: dict
66
67
            :rtype: list
68
        """
69
        trigger_id = kwargs.get('trigger_id')
70
        trigger = Reddit.objects.get(trigger_id=trigger_id)
71
        date_triggered = kwargs.get('date_triggered')
72
        data = list()
73
        submissions = self.reddit.subreddit(trigger.subreddit).top('all')
74
        for submission in submissions:
75
            title = 'From Reddit ' + submission.title
76
            created = arrow.get(submission.created)
77
            if created > date_triggered and\
78
                submission.selftext is not None == trigger.share_link:
79
                body = submission.selftext if submission.selftext \
80
                    else submission.url
81
                data.append({'title': title, 'content': body})
82
                self.send_digest_event(trigger_id, title, '')
83
84
        cache.set('th_reddit_' + str(trigger_id), data)
85
        return data
86
87
    def save_data(self, trigger_id, **data):
88
        """
89
            let's save the data
90
            :param trigger_id: trigger ID from which to save data
91
            :param data: the data to check to be used and save
92
            :type trigger_id: int
93
            :type data:  dict
94
            :return: the status of the save statement
95
            :rtype: boolean
96
        """
97
        title, content = super(ServiceReddit, self).save_data(trigger_id, 
98
                                                                **data)
99
        if self.token:
100
            trigger = Reddit.objects.get(trigger_id=trigger_id)
101
            if trigger.share_link:
102
                status = self.reddit.subreddit(trigger.subreddit)\
103
                    .submit(title=title, url=content)
104
            else:
105
                status = self.reddit.subreddit(trigger.subreddit)\
106
                    .submit(title=title, selftext=content)
107
            sentence = str('reddit submission {} created').format(title)
108
            logger.debug(sentence)
109
        else:
110
            msg = "no token or link provided for trigger " \
111
                  "ID {} ".format(trigger_id)
112
            logger.critical(msg)
113
            update_result(trigger_id, msg=msg, status=False)
114
            status = False
115
        return status