-
Notifications
You must be signed in to change notification settings - Fork 0
/
pycxg.py
executable file
·280 lines (223 loc) · 7.39 KB
/
pycxg.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
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'Robin Wittler'
__contact__ = '[email protected]'
__license__ = 'GPL3+'
__copyright__ = '(c) 2013 by Robin Wittler'
__version__ = '0.0.1'
import sys
if sys.version_info < (2, 7, 0):
raise SystemError('Python Version 2.7.0 or higher is needed.')
import logging
import urllib2
from argparse import Namespace
from argparse import ArgumentParser
try:
import simplejson as json
except ImportError:
import json
BASE_FORMAT_SYSLOG = (
'%(name)s.%(funcName)s[%(process)d] ' +
'%(levelname)s: %(message)s'
)
BASE_FORMAT_STDOUT = '%(asctime)s ' + BASE_FORMAT_SYSLOG
module_logger = logging.getLogger(__name__)
class PyCXGConfig(Namespace):
def __init__(self, prog, **kwargs):
super(PyCXGConfig, self).__init__(**kwargs)
self.prog = prog
def get_args():
parser = ArgumentParser(
version='%(prog)s ' + __version__,
description='A cli tool for the cxg.de nopaste service.',
)
parser.add_argument(
'--url',
default='http://api.cxg.de',
help='The base cxg.de api url. Default: %(default)s',
)
parser.add_argument(
'--timeout',
default=5,
type=int,
help=(
'When to return if the server did not answer (in seconds). ' +
'Default: %(default)s'
)
)
parser.add_argument(
'--file',
default=None,
help=(
'Read the content to paste from a file '
'- instead of reading it from stdin (which is the default). ' +
'When used with the --get switch, this option is used to ' +
'say where to save the content getting from cxg. If not set ' +
'the content will be printed to stdout (which is the default).'
)
)
parser.add_argument(
'--title',
default='No Title',
help='Sets a title for the paste. Default: %(default)s'
)
parser.add_argument(
'--format',
default='auto',
choices=('auto',),
help=(
'Set the format of the content. Possible choices: %(choices)s. ' +
'Default: %(default)s. ' +
'HINT: There is no API call at the moment for getting ' +
'available choices. This might change in the Future.'
)
)
parser.add_argument(
'--loglevel',
default='error',
choices=('debug', 'info', 'warning', 'error'),
help='Set the loglevel. Default: %(default)s',
)
parser.add_argument(
'--get',
default=None,
help='Get a paste from cxg by a given id.',
metavar='CXG_ID'
)
config = parser.parse_args(namespace=PyCXGConfig(parser.prog))
config.loglevel = getattr(logging, config.loglevel.upper(), logging.ERROR)
return config
class PyCXG(object):
def __init__(self, config):
self.config = config
self.logger = logging.getLogger(
'%s.%s'
%(self.config.prog, self.__class__.__name__)
)
self.create_paste_url = urllib2.urlparse.urljoin(
self.config.url,
'paste'
)
self.get_paste_url = urllib2.urlparse.urljoin(
self.config.url,
'paste/'
)
self.logger.debug('Initialized with: %r', config)
def read_content_from_file(self):
if self.config.file is None:
self.logger.debug('Reading content from stdin.')
return sys.stdin.read()
else:
self.logger.debug('Reading content from %r.', self.config.file)
with open(self.config.file, 'r', 1) as fp:
return fp.read()
def paste_content(self, content):
self.logger.debug(
'Making a paste to url %r with title %r, raw content length ' +
'of %r and with the format %r.',
self.create_paste_url,
self.config.title,
len(content),
self.config.format,
)
json_content = json.dumps(
{
'title': self.config.title,
'content': content,
'format': self.config.format
}
)
headers = {
'Content-Type': 'application/json',
'Content-Length': len(json_content),
'ACCEPT': 'application/json'
}
request = urllib2.Request(
self.create_paste_url,
json_content,
headers=headers
)
self.logger.debug(
'Sending json to %r: %s', self.create_paste_url, json_content
)
response = urllib2.urlopen(request, timeout=self.config.timeout)
del json_content
answer_dict = json.load(response)
self.logger.debug(
'The server answered with code %r and with text:\n\n%s\n\n',
response.code,
answer_dict
)
root_logger = logging.getLogger('')
orig_loglevel = root_logger.level
root_logger.setLevel(logging.INFO)
self.logger.info(
'You can find your paste with the id %r at %s',
answer_dict.get('id'),
answer_dict.get('url')
)
root_logger.setLevel(orig_loglevel)
def get_paste(self, cxg_id):
url = urllib2.urlparse.urljoin(self.get_paste_url, cxg_id)
headers = {
'ACCEPT': 'application/json',
'Content-Type': 'application/json',
}
request = urllib2.Request(url, headers=headers)
self.logger.debug('Sending request to url: %r', url)
response = urllib2.urlopen(request)
answer_dict = json.load(response)
self.logger.debug(
'The server answered with code %r and with text:\n\n%s\n\n',
response.code,
answer_dict
)
root_logger = logging.getLogger('')
orig_loglevel = root_logger.level
root_logger.setLevel(logging.INFO)
self.logger.info(
'Getting paste with title %r, format %r and creation date %r',
answer_dict.get('title'),
answer_dict.get('format'),
answer_dict.get('crdate')
)
if self.config.file is None:
self.logger.info(
'Printing content to stdout:\n\n%s\n\n',
answer_dict.get('content').encode('utf-8')
)
else:
self.logger.info(
'Saving content to file %r',
self.config.file
)
with open(self.config.file, 'w', 1) as fp:
fp.write(answer_dict.get('content').encode('utf-8'))
root_logger.setLevel(orig_loglevel)
def run(self):
if not self.config.get is None:
self.get_paste(self.config.get)
else:
content = self.read_content_from_file()
self.paste_content(content)
def start(self):
try:
self.run()
except Exception as error:
self.logger.exception(error)
self.logger.info('Quit because of previous Error.')
sys.exit(2)
else:
sys.exit(0)
if __name__ == '__main__':
config = get_args()
logging.basicConfig(
format=BASE_FORMAT_STDOUT,
level=config.loglevel,
datefmt='%Y-%m-%d %H:%M:%S',
)
root_logger = logging.getLogger('')
root_logger.setLevel(config.loglevel)
a = PyCXG(config)
a.start()
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4