~thomas-deruyter-3/qreator/qreator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# Copyright (C) 2012 David Planella <david.planella@ubuntu.com>
# This program is free software: you can redistribute it and/or modify it 
# under the terms of the GNU General Public License version 3, as published 
# by the Free Software Foundation.
# 
# This program is distributed in the hope that it will be useful, but 
# WITHOUT ANY WARRANTY; without even the implied warranties of 
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR 
# PURPOSE.  See the GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License along 
# with this program.  If not, see <http://www.gnu.org/licenses/>.
### END LICENSE

from gi.repository import Gtk, GObject
from GtkHelpers import clear_text_entry, show_clear_icon
from qreator_lib.helpers import get_data_file
from qreator_lib.i18n import _
import requests
import json


class IsdgShortener(object):
    # TRANSLATORS: this refers to the is.gd URL shortening service
    name = _("Isgd")

    def __init__(self, url=None):
        self.api_url = "http://is.gd/create.php"
        self.url = url

    def short_url(self):
        self.r = requests.get("{0}?format=simple&url={1}".format(self.api_url,
                                                                 self.url))
        if self.r.content.startswith("Error"):
            raise Exception(self.r.content)
        return self.r.content


class TinyUrlShortener(object):
    # TRANSLATORS: this refers to the tinyurl.com URL shortening service
    name = _("TinyUrl")

    def __init__(self, url=None):
        self.api_url = "http://tinyurl.com/api-create.php"
        self.url = url

    def short_url(self):
        self.r = requests.get("{0}?url={1}".format(self.api_url, self.url))
        return self.r.content


class BitlyShortener(object):
    # TRANSLATORS: this refers to the bit.ly URL shortening service
    name = _("Bitly")

    def __init__(self, url=None):
        self.api_url = 'http://api.bit.ly/v3/shorten'
        self.url = url
        self.data = {"login": "",  # TODO
                     "apiKey": "",  # TODO
                     "longUrl": self.url}

    def short_url(self):
        self.r = requests.get(self.api_url, params=self.data)
        self.results = json.loads(self.r.content)
        return self.results["data"]["url"]


class GoogleShortener(object):
    # TRANSLATORS: this refers to the goo.gl URL shortening service
    name = _("Google")

    def __init__(self, url=None):
        self.api_key = "AIzaSyCU_pFNpACW4luWEZRgNnfWMEUdlnZyYQI"
        self.api_url = 'https://www.googleapis.com/urlshortener/v1/url'
        self.url = url
        self.params = {"key": self.api_key,
                       'Content-Type': 'application/json'}
        self.data = {"longUrl": self.url}

    def short_url(self):
        self.r = requests.post(self.api_url, headers=self.params,
                               data=json.dumps(self.data))
        self.results = json.loads(self.r.content)
        return self.results["id"]


SHORTENER_TYPES = [
    IsdgShortener,
    TinyUrlShortener,
    BitlyShortener,
    GoogleShortener,
    ]


class QRCodeURLGtk(object):
    def __init__(self, qr_code_update_func):
        self.qr_code_update_func = qr_code_update_func
        self.builder = Gtk.Builder()

        self.builder.add_from_file(
            get_data_file('ui', '%s.ui' % ('QrCodeURL',)))
        self.builder.connect_signals(self)
        self.grid = self.builder.get_object('qr_code_url')

        self.messagedialog = self.builder.get_object('messagedialog1')

        self.entry = self.builder.get_object('entryURL')
        self.combobox = self.builder.get_object('comboboxtextProtocol')

        # Initialize placeholder text (we need to do that because due to
        # a Glade bug they are otherwise not marked as translatable)
        self.entry.set_placeholder_text(_('[URL]'))
        self.combobox.set_active(0)

        # Currently four shortener options are available: isdg, google,
        # tinyurl, bitly
        # We are choosing isdg at the moment. Later we will allow to define
        # this in preferences.
        self.Shortener = SHORTENER_TYPES[0]

        # TRANSLATORS: leave '{0}' as it is, it will be replaced by the
        # chosen URL shortening service
        self.builder.get_object("togglebuttonShorten").set_tooltip_text(
            "Use the {0} online service to generate a short URL.".format(
                self.Shortener.name))
        self.builder.get_object("togglebuttonShorten").set_has_tooltip(True)

        self.entryhandler = self.entry.connect("changed",
                                               self.on_entryURL_changed)
        # Moved this signal from the glade file to here, to be able to block
        # it later
        self.iconhandler = self.entry.connect("icon-press",
                                              self.on_entryURL_icon_press)
        self.combobox.connect("changed", self.on_comboboxtextProtocol_changed)

    def on_togglebuttonShorten_toggled(self, widget):
        if widget.get_active():
            # not sensitive while shortener is making the network requests
            # not editable while the shortener button is toggled
            self.entry.set_sensitive(False)
            self.entry.set_editable(False)
            self.entry.handler_block(self.iconhandler)
            self.combobox.set_sensitive(False)
            self.long_address = self.address
            self.entry.set_icon_activatable(Gtk.EntryIconPosition.SECONDARY,
                                            False)
            # If the request takes longer, the interface should in the
            # meantime change to unsensitive button and entry, to show at
            # least some behaviour
            GObject.idle_add(self._shorten_and_display)
        else:
            self.entry.set_has_tooltip(False)
            self.entry.set_text(self.long_address)
            self.entry.set_editable(True)
            self.entry.handler_unblock(self.iconhandler)
            self.combobox.set_sensitive(True)
            self.qr_code_update_func(self.address)
            self.entry.set_icon_activatable(Gtk.EntryIconPosition.SECONDARY,
                                            True)

    def on_messagedialog1_response(self, widget, data=None):
        widget.hide()

    def _reset_shortener(self):
        self.builder.get_object('togglebuttonShorten').set_active(False)

    def _shorten_and_display(self):
        self.entry.set_sensitive(True)
        s = self.Shortener(url=self.address)
        try:
            self.short_address = s.short_url()
        except requests.exceptions.ConnectionError as e:
            # TRANSLATORS: leave '{0}' as it is, it will be replaced by the
            # exception's error message
            self.messagedialog.set_markup(
                _("A network connection error occured: {0}".format(e)))
            self.messagedialog.show()
            GObject.idle_add(self._reset_shortener)
            return
        except Exception as e:
            # TRANSLATORS: leave '{0}' as it is, it will be replaced by the
            # exception's error message
            self.messagedialog.set_markup(
                _("An error occured while trying to shorten the URL: {0}".format(e)))   # pylint: disable=E0501
            self.messagedialog.show()
            GObject.idle_add(self._reset_shortener)
            return
        self.entry.set_tooltip_text(self.long_address)
        self.entry.set_has_tooltip(True)
        self.entry.set_text(self.short_address)
        self.entry.select_region(0, len(self.entry.get_text()))
        self.qr_code_update_func(self.short_address)

    def on_activated(self):
        pass

    def on_prepared(self):
        pass

    def update_url_qr_code(self, protocol=None, www=None):
        if not protocol:
            protocol = self.combobox.get_active_text()
        if not www:
            www = self.entry.get_text()

        if not protocol or www == '':
            return

        self.address = protocol + www

        self.qr_code_update_func(self.address)
        return False

    def on_entryURL_icon_press(self, widget, icon, mouse_button):
        clear_text_entry(widget, icon)

    def check_and_remove_protocol(self, widget):
        """
        Creates a list of protocols (as given by the combobox).
        Checks if the beginning of the text entry is in that list. If so,
        remove the protocol and select the appropriate protocol in the
        combobox.
        """
        for n, protocol in enumerate(
            [mr[0] for mr in self.combobox.get_model()]):
            if widget.get_text().strip().startswith(protocol):
                widget.set_text(widget.get_text().strip()[len(protocol):])
                self.combobox.set_active(n)
                return

    def on_entryURL_changed(self, widget, data=None):
        show_clear_icon(widget)
        self.check_and_remove_protocol(widget)
        self.update_url_qr_code()

    def on_comboboxtextProtocol_changed(self, widget, data=None):
        self.update_url_qr_code(protocol=widget.get_active_text())