2018-06-01 18:29:44 +00:00
|
|
|
import json
|
2018-05-18 18:41:41 +00:00
|
|
|
import logging
|
2018-06-18 22:10:19 +00:00
|
|
|
import os
|
2018-05-18 18:41:41 +00:00
|
|
|
import random
|
|
|
|
|
|
|
|
import requests
|
|
|
|
from celery import Celery
|
|
|
|
from requests.exceptions import HTTPError
|
|
|
|
|
|
|
|
from config import DB
|
2018-06-18 22:10:19 +00:00
|
|
|
from config import HEADERS
|
2018-05-18 18:41:41 +00:00
|
|
|
from config import KEY
|
|
|
|
from config import USER_AGENT
|
2018-06-18 22:10:19 +00:00
|
|
|
from little_boxes.httpsig import HTTPSigAuth
|
|
|
|
from little_boxes.linked_data_sig import generate_signature
|
2018-05-18 18:41:41 +00:00
|
|
|
from utils.opengraph import fetch_og_metadata
|
|
|
|
|
2018-05-28 17:46:23 +00:00
|
|
|
log = logging.getLogger(__name__)
|
2018-06-18 22:10:19 +00:00
|
|
|
app = Celery(
|
|
|
|
"tasks", broker=os.getenv("MICROBLOGPUB_AMQP_BROKER", "pyamqp://guest@localhost//")
|
|
|
|
)
|
|
|
|
SigAuth = HTTPSigAuth(KEY)
|
2018-05-18 18:41:41 +00:00
|
|
|
|
|
|
|
|
|
|
|
@app.task(bind=True, max_retries=12)
|
2018-06-01 18:29:44 +00:00
|
|
|
def post_to_inbox(self, payload: str, to: str) -> None:
|
2018-05-18 18:41:41 +00:00
|
|
|
try:
|
2018-06-18 22:10:19 +00:00
|
|
|
log.info("payload=%s", payload)
|
|
|
|
log.info("generating sig")
|
2018-06-01 18:29:44 +00:00
|
|
|
signed_payload = json.loads(payload)
|
2018-06-18 22:10:19 +00:00
|
|
|
generate_signature(signed_payload, KEY)
|
|
|
|
log.info("to=%s", to)
|
|
|
|
resp = requests.post(
|
|
|
|
to,
|
|
|
|
data=json.dumps(signed_payload),
|
|
|
|
auth=SigAuth,
|
|
|
|
headers={
|
|
|
|
"Content-Type": HEADERS[1],
|
|
|
|
"Accept": HEADERS[1],
|
|
|
|
"User-Agent": USER_AGENT,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
log.info("resp=%s", resp)
|
|
|
|
log.info("resp_body=%s", resp.text)
|
2018-05-18 18:41:41 +00:00
|
|
|
resp.raise_for_status()
|
|
|
|
except HTTPError as err:
|
2018-06-18 22:10:19 +00:00
|
|
|
log.exception("request failed")
|
2018-05-18 18:41:41 +00:00
|
|
|
if 400 >= err.response.status_code >= 499:
|
2018-06-18 22:10:19 +00:00
|
|
|
log.info("client error, no retry")
|
2018-05-18 18:41:41 +00:00
|
|
|
return
|
|
|
|
self.retry(exc=err, countdown=int(random.uniform(2, 4) ** self.request.retries))
|
|
|
|
|
|
|
|
|
|
|
|
@app.task(bind=True, max_retries=12)
|
|
|
|
def fetch_og(self, col, remote_id):
|
|
|
|
try:
|
2018-06-18 22:10:19 +00:00
|
|
|
log.info("fetch_og_meta remote_id=%s col=%s", remote_id, col)
|
|
|
|
if col == "INBOX":
|
|
|
|
log.info(
|
|
|
|
"%d links saved", fetch_og_metadata(USER_AGENT, DB.inbox, remote_id)
|
|
|
|
)
|
|
|
|
elif col == "OUTBOX":
|
|
|
|
log.info(
|
|
|
|
"%d links saved", fetch_og_metadata(USER_AGENT, DB.outbox, remote_id)
|
|
|
|
)
|
2018-05-18 18:41:41 +00:00
|
|
|
except Exception as err:
|
2018-06-18 22:10:19 +00:00
|
|
|
self.log.exception("failed")
|
2018-05-18 18:41:41 +00:00
|
|
|
self.retry(exc=err, countdown=int(random.uniform(2, 4) ** self.request.retries))
|