-
Notifications
You must be signed in to change notification settings - Fork 2
/
TinyURL.py
180 lines (152 loc) · 5.04 KB
/
TinyURL.py
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
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-2017 IzunaDevs
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
import sys
try:
import urllib.request
import urllib.parse
except ImportError:
import urllib
from bs4 import BeautifulSoup
import optparse
import re
try:
parse_helper = urllib.parse
except AttributeError:
parse_helper = urllib
try:
request_helper = urllib.request
except AttributeError:
request_helper = urllib
class errors:
"""
Holds all error Classes.
"""
class URLError(Exception):
"""
For URL Errors.
"""
pass
class InvalidURL(Exception):
"""
For Invalid URL's.
"""
pass
class InvalidAlias(Exception):
"""
For Invalid Aliases.
"""
pass
class AliasUsed(Exception):
"""
For already used Aliases.
"""
pass
API_CREATE_LIST = [
"http://tinyurl.com/api-create.php",
"http://tinyurl.com/create.php?"]
DEFAULT_DELIM = "\n"
USAGE = """TinyURL [options] url [url url ...]
Options:
-d / --delimiter
Any number of urls may be passed and will be returned
in order with the given delimiter, default=\\n
"""
pattern = "(arp|dns|dsn|imap|http|sftp|ftp|icmp|idrp|ip|irc|pop3|par|rlogin"
pattern += "|smtp|ssl|ssh|tcp|telnet|upd|up|file|git)(s?):\/\/[\/]?"
ALL_OPTIONS = ((('-d', '--delimiter'), dict(
dest='delimiter', default=DEFAULT_DELIM,
help='delimiter for returned results')),)
def _build_option_parser():
prs = optparse.OptionParser(usage=USAGE)
for args, kwargs in ALL_OPTIONS:
prs.add_option(*args, **kwargs)
return prs
def create_one(url, alias=None):
"""
Shortens a URL using the TinyURL API.
"""
if url != '' and url is not None:
regex = re.compile(pattern)
searchres = regex.search(url)
if searchres is not None:
if alias is not None:
if alias != '':
payload = {
'url': url,
'submit': 'Make TinyURL!',
'alias': alias
}
data = parse_helper.urlencode(payload)
full_url = API_CREATE_LIST[1] + data
ret = request_helper.urlopen(full_url)
soup = BeautifulSoup(ret, 'html.parser')
check_error = soup.p.b.string
if 'The custom alias' in check_error:
raise errors.AliasUsed(
"The given Alias you have provided is already"
" being used.")
else:
return soup.find_all(
'div', {'class': 'indent'}
)[1].b.string
else:
raise errors.InvalidAlias(
"The given Alias cannot be 'empty'.")
else:
url_data = parse_helper.urlencode(dict(url=url))
byte_data = str.encode(url_data)
ret = request_helper.urlopen(
API_CREATE_LIST[0], data=byte_data).read()
result = str(ret).replace('b', '').replace("\'", '')
return result
else:
raise errors.InvalidURL("The given URL is invalid.")
else:
raise errors.URLError("The given URL Cannot be 'empty'.")
def create(*urls):
"""
Shortens URL's
"""
for url in urls:
yield create_one(url)
def main():
"""
Entry Point.
"""
if len(sys.argv) > 1:
sysargs = sys.argv[:]
parser = _build_option_parser()
opts, urls = parser.parse_args(sysargs[1:])
try:
for url in create(*urls):
sys.stdout.write(url + opts.delimiter)
except Exception as ex:
print("Error: " + str(ex))
else:
print(USAGE)
__title__ = 'TinyURL'
__author__ = 'Decorater'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015-2017 Decorater'
__version__ = '0.1.10'
__build__ = 0x0001010
if __name__ == '__main__':
main()