

import requests, sys  # pip install requests
import jwt  # pip install pyjwt
from datetime import datetime as date
import json
import os

sys.path.append('/var/www/digisnaxx.ado/scrapers')
import dtss
dtss.getReady()

from datasnaxx.models import Subscriber

ADMIN_API = "66b2f3f778c05d6323155324:bd7d2034c1e0e52de8c549e8e5e3b8927032eacbe04647b6ae626fda4e08d821"
API_URL = "https://canin.dreamfreely.org"
JSON_PATH = "<YOUR JSON PATH>"

key = ADMIN_API
id, secret = key.split(':')

iat = int(date.now().timestamp())

header = {'alg': 'HS256', 'typ': 'JWT', 'kid': id}
payload = {
    'iat': iat,
    'exp': iat + 5 * 60,
    'aud': '/v4/admin/'
}

token = jwt.encode(payload, bytes.fromhex(secret),
                    algorithm='HS256', headers=header)

# Make an authenticated request to create a post

url = API_URL + "/ghost/api/admin/members/"
headers = {'Authorization': 'Ghost {}'.format(token)}

r = requests.get(url, headers=headers)

data = json.loads(r.text)
subs = data['members']

for s in subs:
    d = {}
    d['email' ] = s['email']
    d['sub'] = s['subscribed']
    d['open_rate'] = s['email_open_rate']
    d['created_at'] = s['created_at']
    sub, created = Subscriber.objects.get_or_create(
        email=d['email'],
        subscribed=d['sub'],
        created_at = d['created_at'],
        open_rate = d['open_rate'],
    )
    if len(s['labels']) > 0:
        sub.label = s['labels'][0]['name']
        sub.save()
    if len(s['subscriptions']) > 0:
        sub_desc = s['subscriptions'][0]
        sub.status = sub_desc['status']
        sub.start_date = sub_desc['start_date']
        sub.amount = sub_desc['price']['amount']
        sub.interval = sub_desc['price']['interval']
        sub.reoccuring = sub_desc['price']['type']
        sub.tier = sub_desc['tier']['name']
        sub.save()



