Completed
Push — master ( 574502...0b3f92 )
by Fox
01:26
created

ServiceGithub.__init__()   A

Complexity

Conditions 2

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 2
c 1
b 1
f 0
dl 0
loc 18
rs 9.4285
1
# coding: utf-8
2
# github
3
from github3 import GitHub
4
5
# django classes
6
from django.conf import settings
7
from django.core.urlresolvers import reverse
8
from django.utils.log import getLogger
9
from django.core.cache import caches
10
11
# django_th classes
12
from django_th.services.services import ServicesMgr
13
from django_th.models import UserService, ServicesActivated
14
15
"""
16
    handle process with github
17
    put the following in settings.py
18
19
    TH_GITHUB = {
20
        'username': 'username',
21
        'password': 'password',
22
        'consumer_key': 'my key',
23
        'consumer_secret': 'my secret'
24
    }
25
26
27
    TH_SERVICES = (
28
        ...
29
        'th_github.my_github.ServiceGithub',
30
        ...
31
    )
32
33
"""
34
35
logger = getLogger('django_th.trigger_happy')
36
37
cache = caches['th_github']
38
39
40
class ServiceGithub(ServicesMgr):
41
42
    def __init__(self, token=None, **kwargs):
43
        super(ServiceGithub, self).__init__(token, **kwargs)
44
        self.scope = ['public_repo']
45
        self.REQ_TOKEN = 'https://github.com/login/oauth/authorize'
46
        self.AUTH_URL = 'https://github.com/login/oauth/authorize'
47
        self.ACC_TOKEN = 'https://github.com/login/oauth/access_token'
48
        self.username = settings.TH_GITHUB['username']
49
        self.password = settings.TH_GITHUB['password']
50
        self.consumer_key = settings.TH_GITHUB['consumer_key']
51
        self.consumer_secret = settings.TH_GITHUB['consumer_secret']
52
        self.token = token
53
        self.oauth = 'oauth2'
54
        self.service = 'ServiceGithub'
55
        if self.token:
56
            token_key, token_secret = self.token.split('#TH#')
57
            self.gh = GitHub(token=token_key)
58
        else:
59
            self.gh = GitHub(username=self.username, password=self.password)
60
61
    def read_data(self, **kwargs):
62
        """
63
            get the data from the service
64
            :param kwargs: contain keyword args : trigger_id at least
65
            :type kwargs: dict
66
            :rtype: list
67
        """
68
        trigger_id = kwargs.get('trigger_id')
69
        data = list()
70
        cache.set('th_github_' + str(trigger_id), data)
71
72
    def save_data(self, trigger_id, **data):
73
        """
74
            let's save the data
75
            :param trigger_id: trigger ID from which to save data
76
            :param data: the data to check to be used and save
77
            :type trigger_id: int
78
            :type data:  dict
79
            :return: the status of the save statement
80
            :rtype: boolean
81
        """
82
        from th_github.models import Github
83
        if self.token:
84
            title = self.set_title(data)
85
            body = self.set_content(data)
86
            # get the details of this trigger
87
            trigger = Github.objects.get(trigger_id=trigger_id)
88
89
            # check if it remains more than 1 access
90
            # then we can create an issue
91
            limit = self.gh.ratelimit_remaining
92
            if limit > 1:
93
                # repo goes to "owner"
94
                # project goes to "repository"
95
                r = self.gh.create_issue(trigger.repo,
96
                                         trigger.project,
97
                                         title,
98
                                         body)
99
            else:
100
                # rate limit reach
101
                logger.warn("Rate limit reached")
102
                # put again in cache the data that could not be
103
                # published in Github yet
104
                cache.set('th_github_' + str(trigger_id), data, version=2)
105
                return True
106
            sentence = str('github {} created').format(r)
107
            logger.debug(sentence)
108
            status = True
109
        else:
110
            sentence = "no token or link provided for trigger ID {} "
111
            logger.critical(sentence.format(trigger_id))
112
            status = False
113
114
        return status
115
116
    def auth(self, request):
117
        """
118
            let's auth the user to the Service
119
            :param request: request object
120
            :return: callback url
121
            :rtype: string that contains the url to redirect after auth
122
        """
123
        callback_url = 'http://%s%s' % (
124
            request.get_host(), reverse('github_callback'))
125
        auth = self.gh.authorize(self.username,
126
                                 self.password,
127
                                 self.scope,
128
                                 '',
129
                                 '',
130
                                 self.consumer_key,
131
                                 self.consumer_secret)
132
        request.session['oauth_token'] = auth.token
133
        request.session['oauth_id'] = auth.id
134 View Code Duplication
        return callback_url
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
135
136
    def callback(self, request, **kwargs):
137
        """
138
            Called from the Service when the user accept to activate it
139
            :param request: request object
140
            :return: callback url
141
            :rtype: string , path to the template
142
        """
143
        try:
144
            # finally we save the user auth token
145
            # As we already stored the object ServicesActivated
146
            # from the UserServiceCreateView now we update the same
147
            # object to the database so :
148
            # 1) we get the previous objet
149
            us = UserService.objects.get(
150
                user=request.user,
151
                name=ServicesActivated.objects.get(name='ServiceGithub'))
152
            # 2) Readability API require to use 4 params consumer_key/secret +
153
            # token_key/secret instead of usually get just the token
154
            # from an access_token request. So we need to add a string
155
            # separator for later use to split on this one
156
            access_token = request.session['oauth_token'] + "#TH#"
157
            access_token += str(request.session['oauth_id'])
158
            us.token = access_token
159
            # 3) and save everything
160
            us.save()
161
        except KeyError:
162
            return '/'
163
164
        return 'github/callback.html'
165