1from io import StringIO 2from urllib.error import URLError 3from urllib.parse import urlencode 4from urllib.request import Request, urlopen 5 6from gi.repository import Gdk, Gtk 7 8from pychess.Utils.const import NAME, UNDOABLE_STATES 9from pychess.Savers import pgn 10from pychess.widgets import mainwindow 11 12URL = "https://www.chesspastebin.com/api/add/" 13APIKEY = "a137d919b75c8766b082367610189358cfb1ba70" 14 15 16def paste(gamemodel): 17 dialog = Gtk.MessageDialog(mainwindow(), type=Gtk.MessageType.QUESTION, buttons=Gtk.ButtonsType.YES_NO) 18 if gamemodel.status in UNDOABLE_STATES: 19 text = _("The current game is over. First, please verify the properties of the game.") 20 else: 21 text = _("The current game is not terminated. Its export may have a limited interest.") 22 text += "\n\n" + _("Should %s publicly publish your game as PGN on chesspastebin.com ?") % NAME 23 dialog.set_markup(text) 24 response = dialog.run() 25 dialog.destroy() 26 if response != Gtk.ResponseType.YES: 27 return 28 29 output = StringIO() 30 text = pgn.save(output, gamemodel) 31 values = {'apikey': APIKEY, 32 'pgn': text, 33 "name": "PyChess", 34 'sandbox': 'false'} 35 36 data = urlencode(values).encode('utf-8') 37 req = Request(URL, data) 38 try: 39 response = urlopen(req, timeout=10) 40 except URLError as err: 41 if hasattr(err, 'reason'): 42 print('We failed to reach the server.') 43 print('Reason: ', err.reason) 44 elif hasattr(err, 'code'): 45 print('The server couldn\'t fulfill the request.') 46 print('Error code: ', err.code) 47 else: 48 ID = response.read() 49 link = "http://www.chesspastebin.com/?p=%s" % int(ID) 50 clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) 51 clipboard.set_text(link, -1) 52 # print(text) 53 # print(clipboard.wait_for_text()) 54 msg_dialog = Gtk.MessageDialog(mainwindow(), type=Gtk.MessageType.INFO, 55 buttons=Gtk.ButtonsType.OK) 56 msg = _( 57 "Game shared at ") + '<a href="%s">chesspastebin.com</a>' % link 58 msg_dialog.set_markup(msg) 59 msg_dialog.format_secondary_text(_("(Link is available on clipboard.)")) 60 msg_dialog.connect("response", lambda msg_dialog, a: msg_dialog.hide()) 61 msg_dialog.show() 62