#!/usr/bin/env python
from gi.repository import Gdk
from io import StringIO, BytesIO
from subprocess import call, Popen, PIPE
from xdg import BaseDirectory
import base64
import datetime
import json
import os
import requests
import sys
def notify(message):
"""
Sends a user notification.
Current implementation calls notify-send, but this will change in future.
"""
# TODO: make a pure-python implementation
call(["/usr/bin/notify-send", message])
def get_scrot():
"""
Returns the screenshot's size and the screenshot in base64
"""
win = Gdk.get_default_root_window()
h = win.get_height()
w = win.get_width()
size = "{} x {}".format(w, h)
pb = Gdk.pixbuf_get_from_window(win, 0, 0, w, h)
pb.savev("/tmp/scrotpush.png", "png", [], [])
bio = BytesIO()
base64.encode(open("/tmp/scrotpush.png", "rb"), bio)
return size, bio.getvalue()
def save_data(filename, data):
"""
Save the data into the user's cache folder (in case he wants the delete
hash or something)
"""
path = os.path.join(BaseDirectory.xdg_cache_home, "scrotpush")
if not os.path.exists(path):
os.mkdir(path)
f = open(os.path.join(path, filename), "w")
f.write(data)
f.close()
def copy_text(text):
"""
Copies some text into the user's clipboard
"""
# TODO: Make clipboard/primary configurable
# TODO: make a pure-python implementation
c = Popen(["xclip", "-selection", "clipboard"], stdin=PIPE)
c.communicate(input=text.encode('utf-8'))
if __name__ == '__main__':
if len(sys.argv) > 1:
print("""Usage: scrotpush""")
sys.exit(0)
# Gather the data
size, scrot = get_scrot()
notify("Screenshot taken...")
now = datetime.datetime.now().isoformat()
# Prepare the request
url = "https://api.imgur.com/3/image"
payload = {
'image': scrot,
'title': 'Screenshot taken at {}'.format(now)
}
headers = {'Authorization': 'Client-ID fda3104aa1a2503'}
# Do the API call
r = requests.post(url, data=payload, headers=headers)
# Clean up!
if (r.status_code == 200):
response = json.loads(r.text)
response_str = json.dumps(response, indent=2)
copy_text(response["data"]["link"])
notify("... screenshot uploaded!")
save_data(now, response_str)
else:
notify("... Error uploading screenshot. :-(")