#!/usr/bin/env python3

import requests
import datetime
import hmac
import hashlib
import base64
import json

publicKey = 'PUBLIC_KEY_HERE'
privateKey = 'PRIVATE_KEY_HERE'


def main():

	# Keyword search via the /markets/summary endpoint to summarize all
	# listings with "fentanyl" in the listing title.
	# Instead of getting the results back, we use the /markets/summary
	# endpoint to get a summary.
	print('Summarizing market listings with "fentanyl" in the title...')
	payload = {"searchText": "fentanyl"}
	response = perform_query(payload=payload, endpoint='markets/summary')
	# Save the summary to a file
	with open('./summary_for_fentanyl.json', 'w') as outFile:
		json.dump(response, outFile)
	print(f'\tSummarization of listings saved.')

	print()

	# Keyword search via the /markets/search endpoint to find all
	# listings with "fentanyl" in the listing title.
	# Pick the first result in the list to get more detail from the detail endpoint
	print('Searching market titles for "fentanyl"...')
	payload = {"searchText": "fentanyl", "options": {"sort": 'firstSeen'}}
	response = perform_query(payload=payload, endpoint='markets/search')
	# Save the first page of results to a file
	with open('./results_for_fentanyl.json', 'w') as outFile:
		json.dump(response, outFile)
	print(f'\t{response["total"]} listings found. Saved first 20 to file.')

	ref = response['results'][0]['ref']

	print()

	# Get all known information about a specific listing using the /markets/detail endpoint
	print('Getting listing detail...')
	response = perform_query(method='GET', endpoint='markets/detail', path=ref.replace('/api/v1/markets/detail', ''))
	# Save the detail result to a file
	with open('./listing_detail.json', 'w') as outFile:
		json.dump(response, outFile)
	print(f'\tListing detail saved.')

	


def perform_query(payload=None, method='POST', endpoint='markets/search', path=''):
	host = 'api.darkowl.com'
	endpoint = f'/api/v1/{endpoint}'

	url = f'https://{host}{endpoint}{path}'
	absPath = endpoint + path
	headers = gen_headers(absPath, method)
	if method == 'GET':
		r = requests.get(url, headers=headers)
	elif method =='POST':
		r = requests.post(url, headers=headers, json=payload)

	if r.status_code == 200:
		return r.json()
	else:
		print(r.content)
		exit(1)

### Generates request headers based on the the URL being queried
def gen_headers(absPath, method='POST'):
	#get current date
	date = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')

	 # create string to hash and sign
	string2hash = f'{method}{absPath}{date}'
	# convert to bytes
	bkey = bytes(source=privateKey, encoding='UTF-8')
	bpayload = bytes(source=string2hash, encoding='UTF-8')
	# sign with priv key
	hmacsha1 = hmac.new(bkey, bpayload, hashlib.sha1).digest()
	# convert to b64
	base64encoded = base64.b64encode(hmacsha1).decode('UTF-8')
	# construct final auth header
	auth = f'OWL {publicKey}:{base64encoded}'

	#return headers
	return {'Authorization': auth, 'X-VISION-DATE': date, 'Accept': 'application/json'}


if __name__ == '__main__':
	main()
