2022-01-24 19:37:27 +01:00
|
|
|
import os
|
|
|
|
from uuid import uuid4
|
|
|
|
from requests_oauthlib import OAuth1Session
|
|
|
|
from flask import Blueprint, Response, current_app, request, jsonify
|
2022-01-24 20:30:06 +01:00
|
|
|
from ayct_backend.twitter.models import *
|
2022-01-24 19:37:27 +01:00
|
|
|
|
|
|
|
twitter = Blueprint('twitter', __name__)
|
|
|
|
|
|
|
|
consumer_key = current_app.config["TWITTER_CONSUMER_KEY"]
|
|
|
|
consumer_secret = current_app.config["TWITTER_CONSUMER_SECERT"]
|
|
|
|
|
|
|
|
@twitter.route('/account', methods=['GET'])
|
|
|
|
def get_twitter_accounts():
|
|
|
|
twitter_accounts = TwitterAccount.query.all()
|
|
|
|
|
|
|
|
accounts = []
|
|
|
|
|
|
|
|
for account in twitter_accounts:
|
|
|
|
account_data = {}
|
|
|
|
account_data['twitter_user_id'] = account.twitter_user_id
|
|
|
|
account_data['username'] = account.username
|
|
|
|
accounts.append(account_data)
|
|
|
|
|
|
|
|
return Response(
|
|
|
|
jsonify({
|
|
|
|
"twitter_accounts": accounts
|
|
|
|
}),
|
|
|
|
status=200,
|
|
|
|
)
|
|
|
|
|
|
|
|
@twitter.route('/account', methods=['POST'])
|
|
|
|
def add_twitter_account():
|
|
|
|
content_type = request.headers.get('Content-Type')
|
|
|
|
if (content_type == 'application/json'):
|
|
|
|
json = request.json
|
|
|
|
if not json['veryfier']:
|
|
|
|
return Response(
|
|
|
|
"Invalid request!",
|
|
|
|
status=400,
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
oauth = OAuth1Session(
|
|
|
|
consumer_key,
|
|
|
|
client_secret=consumer_secret
|
|
|
|
)
|
|
|
|
request_token_url = "https://api.twitter.com/oauth/request_token?oauth_callback=oob&x_auth_access_type=write"
|
|
|
|
fetch_response = oauth.fetch_request_token(request_token_url)
|
|
|
|
|
|
|
|
access_token_url = "https://api.twitter.com/oauth/access_token"
|
|
|
|
oauth = OAuth1Session(
|
|
|
|
consumer_key,
|
|
|
|
client_secret=consumer_secret,
|
|
|
|
resource_owner_key=fetch_response.get("oauth_token"),
|
|
|
|
resource_owner_secret=fetch_response.get("oauth_token_secret"),
|
|
|
|
verifier=json['veryfier'],
|
|
|
|
)
|
|
|
|
oauth_tokens = oauth.fetch_access_token(access_token_url)
|
|
|
|
|
|
|
|
new_twitter_account = TwitterAccount(
|
|
|
|
twitter_user_id = oauth_tokens["user_id"],
|
|
|
|
username = oauth_tokens["screen_name"],
|
|
|
|
access_token = oauth_tokens["oauth_token"],
|
|
|
|
access_token_secret = oauth_tokens["oauth_token_secret"]
|
|
|
|
)
|
|
|
|
|
|
|
|
twitter_db.session.add(new_twitter_account)
|
|
|
|
twitter_db.session.commit()
|
|
|
|
|
|
|
|
return Response(
|
|
|
|
jsonify({
|
|
|
|
"message": "Twitter account succesfully added."
|
|
|
|
}),
|
|
|
|
status=201,
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
return Response(
|
|
|
|
"Content-type not supported!",
|
|
|
|
status=400,
|
|
|
|
)
|
|
|
|
|