summaryrefslogtreecommitdiff
path: root/postgresqleu/util/messaging/linkedin.py
blob: 9216668e0b08ae2850b24f777d7db45d0af54a28 (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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django import forms
from django.conf import settings
from django.shortcuts import get_object_or_404
from django.utils.timesince import timeuntil
from django.utils import timezone

from datetime import datetime, timedelta
import re
import requests
import requests_oauthlib
import time

from postgresqleu.util.forms import SubmitButtonField
from postgresqleu.util.oauthapps import get_oauth_client, get_oauth_secret
from postgresqleu.util.random import generate_random_token
from postgresqleu.util.time import datetime_string
from postgresqleu.util.widgets import StaticTextWidget

from postgresqleu.confreg.models import MessagingProvider
from postgresqleu.confreg.backendforms import BackendSeriesMessagingForm

# Scopes to request when fetching token
LINKEDIN_SCOPE = 'r_organization_social,w_organization_social'


class LinkedinBackendForm(BackendSeriesMessagingForm):
    linkedininfo = forms.CharField(widget=StaticTextWidget, label="Account information", required=False)
    pageid = forms.IntegerField(required=True, help_text="The id number of the page to post to. Can be retrieved from the URL of the page.", label='Page ID')

    exclude_fields_from_validation = ['linkedininfo', ]

    @property
    def config_fields(self):
        f = ['linkedininfo', ]
        if self.instance.config.get('token', None):
            return f + ['pageid', ]
        else:
            return f

    @property
    def config_fieldsets(self):
        return [
            {'id': 'linkedin', 'legend': 'Linkedin', 'fields': self.config_fields},
        ]

    @property
    def config_readonly_fields(self):
        return ['linkedininfo', ]

    def fix_fields(self):
        super().fix_fields()

        auth_url, state = requests_oauthlib.OAuth2Session(
            get_oauth_client('https://api.linkedin.com'),
            redirect_uri='{}/oauth_return/messaging/'.format(settings.SITEBASE),
            state='{}_{}'.format(self.instance.id, generate_random_token()),
            scope=LINKEDIN_SCOPE,
        ).authorization_url('https://www.linkedin.com/oauth/v2/authorization')

        if self.instance.config.get('token', None):
            tokenexpires = timezone.make_aware(datetime.fromtimestamp(self.instance.config.get('token_expires')))
            refreshtokenexpires = timezone.make_aware(datetime.fromtimestamp(self.instance.config.get('refresh_token_expires')))

            self.initial.update({
                'linkedininfo': 'Connected to Linkedin account.<br/>Current access token will expire in {} (on {}), and will be automatically renewed until {}, after which it must be manually re-authenticated.<br/>To re-athenticate, click <a href="{}">this link</a> and log in with a Linkedin account with the appropriate permissions.'.format(
                    timeuntil(tokenexpires),
                    datetime_string(tokenexpires),
                    datetime_string(refreshtokenexpires),
                    auth_url,
                ),
            })
        else:
            self.remove_field('pageid')

            if not self.instance.id:
                self.initial.update({
                    'linkedininfo': 'Not connected. Save the provider first, and then return here to configure.',
                })
            else:
                # Create an oauth URL for access
                # (XXX: we don't store the state for verification here, which maybe we should, but we don't care that much here)

                self.initial.update({
                    'linkedininfo': 'Not connected. Please follow <a href="{}">this link</a> and authorize access to Linkedin.'.format(auth_url),
                })

    def clean(self):
        d = super().clean()
        if d.get('active', False):
            if not d.get('pageid', 0):
                self.add_error('active', 'Cannot activate without a pageid')

            # Unfortunately, the linkedin api gives us no good way to validate that we have access to a page. If we could
            # work without a rate limit, we could create an unpublished post and then delete it, but with the default rate limiting that
            # is very wasteful so we skip it for now.

        return d


class Linkedin(object):
    provider_form_class = LinkedinBackendForm
    can_process_incoming = False
    can_broadcast = True
    can_notification = False
    direct_message_max_length = None
    typename = 'Linkedin'
    max_post_length = 3000

    re_adminpage_url = re.compile(r'https://www.linkedin.com/company/(\d+)/.*')
    re_publicpage_url = re.compile(r'https://www.linkedin.com/company/([^/]+)/.*')

    @classmethod
    def can_track_users_for(self, whatfor):
        return False

    @classmethod
    def validate_baseurl(self, baseurl):
        return None

    @classmethod
    def clean_identifier_form_value(self, whatfor, value):
        raise Exception("Not implemented")

    @classmethod
    def get_link_from_identifier(self, value):
        return 'https://linkedin.com/company/{}'.format(value)

    def __init__(self, id, config):
        self.providerid = id
        self.providerconfig = config
        self._sess = None
        if 'pageid' in self.providerconfig:
            self.urn = 'urn:li:organization:{}'.format(self.providerconfig['pageid'])
        else:
            self.urn = None

    @property
    def sess(self):
        if self._sess is None:
            self._sess = requests.Session()
            self._sess.headers.update({
                'Authorization': 'Bearer {}'.format(self.providerconfig['token']),
                'LinkedIn-Version': '202505',
            })
        return self._sess

    def _api_url(self, url):
        return 'https://api.linkedin.com/{}'.format(url)

    def _get(self, url, *args, **kwargs):
        return self.sess.get(self._api_url(url), timeout=30, *args, **kwargs)

    def _post(self, url, *args, **kwargs):
        return self.sess.post(self._api_url(url), timeout=30, *args, **kwargs)

    def oauth_return(self, request):
        try:
            tokens = requests_oauthlib.OAuth2Session(
                get_oauth_client('https://api.linkedin.com'),
                redirect_uri='{}/oauth_return/messaging/'.format(settings.SITEBASE),
                state='{}_{}'.format(self.providerid, generate_random_token()),
                scope=LINKEDIN_SCOPE,
            ).fetch_token(
                'https://www.linkedin.com/oauth/v2/accessToken',
                code=request.GET['code'],
                include_client_id=True,
                client_secret=get_oauth_secret('https://api.linkedin.com'),
                scopes=LINKEDIN_SCOPE,
            )
        except Exception as e:
            return 'Could not fetch token: {}'.format(e)

        m = get_object_or_404(MessagingProvider, pk=self.providerid)
        m.config.update({
            'token': tokens['access_token'],
            'refresh_token': tokens['refresh_token'],
            'token_expires': int(tokens['expires_in'] + time.time()),
            'refresh_token_expires': int(tokens['refresh_token_expires_in'] + time.time()),
        })
        m.save(update_fields=['config'])

    def post(self, text, image=None, replytotweetid=None):
        if not self.urn:
            # Can't post without an URN
            return

        d = {
            'author': self.urn,
            'commentary': text,
            'visibility': 'PUBLIC',
            'distribution': {
                'feedDistribution': 'MAIN_FEED',
            },
            'lifecycleState': 'PUBLISHED',
        }

        if image:
            # Initiate multi-step image upload
            r = self._post('rest/images', params={'action': 'initializeUpload'}, json={
                'initializeUploadRequest': {
                    'owner': self.urn,
                }
            })
            if r.status_code != 200:
                return (None, 'Failed to initialize image upload: {}'.format(r.text))
            ir = self.sess.put(r.json()['value']['uploadUrl'], bytearray(image), timeout=60)
            if ir.status_code != 201:
                return (None, 'Failed to upload image: {}'.format(ir.text))
            # Upload complete, we can use it!
            d['content'] = {
                'media': {
                    'id': r.json()['value']['image'],
                },
            }
        r = self._post('rest/posts', json=d)
        if r.status_code != 201:
            return (None, r.text)

        # Format of id is urn:li:share:7196857142283268096
        return (r.headers['x-linkedin-id'], None)

    def repost(self, tweetid):
        raise Exception("Not implemented")

    def send_direct_message(self, recipient_config, msg):
        raise Exception("Not implemented")

    def poll_public_posts(self, lastpoll, checkpoint):
        raise Exception("Not implemented")

    def poll_incoming_private_messages(self, lastpoll, checkpoint):
        raise Exception("Not implemented")

    def get_regconfig_from_dm(self, dm):
        raise Exception("Not implemented")

    def get_regdisplayname_from_config(self, config):
        raise Exception("Not implemented")

    def get_public_url(self, post):
        return 'https://www.linkedin.com/feed/update/urn:li:share:{}/'.format(post.statusid)

    def get_attendee_string(self, token, messaging, attendeeconfig):
        raise Exception("Not implemented")

    def refresh_access_token(self):
        r = requests.post('https://www.linkedin.com/oauth/v2/accessToken', data={
            'grant_type': 'refresh_token',
            'refresh_token': self.providerconfig['refresh_token'],
            'client_id': get_oauth_client('https://api.linkedin.com'),
            'client_secret': get_oauth_secret('https://api.linkedin.com'),
        }, timeout=30)
        if r.status_code == 200:
            tokens = r.json()
            provider = MessagingProvider.objects.get(pk=self.providerid)
            provider.config.update({
                'token': tokens['access_token'],
                'refresh_token': tokens['refresh_token'],
                'token_expires': int(tokens['expires_in'] + time.time()),
                'refresh_token_expires': int(tokens['refresh_token_expires_in'] + time.time()),
            })
            provider.save(update_fields=['config'])
            self.providerconfig = provider.config
            return True, None
        return False, r.text

    def check_messaging_config(self, state):
        tokenexpires = timezone.make_aware(datetime.fromtimestamp(self.providerconfig.get('token_expires')))
        refreshtokenexpires = timezone.make_aware(datetime.fromtimestamp(self.providerconfig.get('refresh_token_expires')))

        if tokenexpires < timezone.now() + timedelta(days=10):
            # We start trying to refresh when there are 10 days to go
            if refreshtokenexpires < timezone.now() + timedelta(days=1):
                # We add one day margin here
                return False, "Refresh token has expired, re-authentication needed."

            # Attempt to refresh
            ok, err = self.refresh_access_token()
            if ok:
                return True, "Access token refreshed, new token valid until {}.".format(timezone.make_aware(datetime.fromtimestamp(self.providerconfig.get('token_expires'))))
            else:
                return False, "Access token refresh failed: {}".format(err)

        if refreshtokenexpires < timezone.now() + timedelta(days=10):
            return True, "Refresh token will expire in {} (on {}), manual re-authentication needed!".format(
                timeuntil(refresh_token_expires),
                refresh_token_expires,
            )

        # Token not expired or about to, so verify that what we have works.
        r = self._get(
            'rest/posts',
            params={
                'author': self.urn,
                'q': 'author',
                'count': 1,
            },
        )
        if r.status_code != 200:
            return False, "Failed to get post (status {}): {}".format(r.status_code, r.text)
        # We can't really check that there is at least one post returned, because there might
        # be no posts available. But at least this way we have verified that the token is OK.
        return True, ''

    def get_link(self, id):
        return [
            'linkedin',
            'https://www.linkedin.com/feed/update/{}/'.format(id),
        ]