BDServer/modules/API.py

90 lines
2.1 KiB
Python
Raw Normal View History

# AGPL 3 or any later version
# (C) J.Y.Amihud ( Blender Dumbass )
import os
import json
import time
import email
import random
import hashlib
import urllib.parse
import urllib.request
from datetime import datetime
from modules import Set
from modules.Common import *
API_cache = {}
def Get(url, data=None, headers={}):
if data:
data = json.dumps(data).encode("utf-8")
req = urllib.request.Request(url, data=data, headers=headers)
f = urllib.request.urlopen(req, timeout=10)
data = json.loads(f.read().decode('utf-8'))
return data
def Value(url, keys):
data = Get(url)
for key in keys:
data = data[key]
return data
def Petition(article):
petition = article.get("petition", {})
api = petition.get("api", {})
timestamp = api.get("timestamp",0)
# 5 minutes delay
if time.time() - 300 < timestamp:
return
value = int(Value(api.get("api", ""), api.get("keys", [])))
article["petition"]["api"]["timestamp"] = time.time()
article["petition"]["signed"] = value
f = Set.Folder()
with open(f+"/tabs"+article.get("url", "")+"/metadata.json", "w") as save:
json.dump(article, save, indent=4)
def Mastodon(mastoname, posts=4):
# This function will get few latest posts
# and return them back to whatever needs
# them.
# First we want to get the mastodon ID of the
# user in question ( mastodon API is strange ).
if mastoname.startswith("@"):
mastoname = mastoname[1:]
username, host, *rest = mastoname.split("@")
if not "mastoid" in API_cache:
url = "https://"+host+"/api/v1/accounts/lookup?acct="+username
ID = Value(url, ["id"])
API_cache["mastoid"] = ID
ID = API_cache["mastoid"]
# Now that we have the ID we can request the actuall
# list that we came here for.
if time.time()-300 > API_cache.get("mastotime", 0):
url = "https://"+host+"/api/v1/accounts/"+str(ID)+"/statuses?inned=false&limit="+str(posts)
data = Get(url)
API_cache["mastotime"] = time.time()
API_cache["mastodata"] = data
return API_cache["mastodata"]