forked from gicmo/lit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lit.py
executable file
·404 lines (318 loc) · 9.84 KB
/
lit.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#!/usr/bin/env python
# (c) 2011 Christian Kellner <[email protected]>
import sys
import getopt
import os
import datetime
from paramiko import SSHClient, SSHConfig
baseURL = "sftp://gate.g-node.org/groups/wachtler/literature"
class Paper(object):
def __init__(self, name, inCentury):
self._name = name
extStart = name.rfind(".")
ext = name[extStart+1:]
self._ext = ext
if ext != 'pdf':
return None
self._century = inCentury
yearStart = -1
for idx in xrange(0, extStart):
if name[idx].isdigit():
yearStart = idx
break
if not yearStart != -1:
return None
yearEnd = -1
for idx in xrange(yearStart, extStart+1):
if not name[idx].isdigit():
yearEnd = idx
break
if not yearEnd != -1:
return None
self._author = name[:yearStart]
self._year = int(name[yearStart:yearEnd])
@property
def year(self):
year = self._year
yearBase = self._century
if not yearBase:
yearBase = 20
year += yearBase * 100
return year
@property
def author(self):
return self._author
@property
def filetype(self):
return self._ext
@property
def uri(self):
return None
@property
def name(self):
return self._name
def __repr__(self):
return "Paper('%s')" % self.name
def __str__(self):
return "%s %d" % (self.author, self.year)
class Filter(object):
def __init__(self, searchFor=None, inYear=None):
self._filterString = searchFor
self.year = inYear
def apply(self, paper):
if paper.filetype != 'pdf':
return False
if self.year != None and paper.year != self.year:
return False
if not self._filterString:
return True
else:
return paper.author.startswith(self._filterString)
@property
def year(self):
return self._year
@year.setter
def year(self, value):
if not value:
self._year = None
return
if type(value) != int:
value = self._parseYear(value)
self._year = value
def _parseYear(self, string):
yearEnd = len(string)
for idx in xrange(0, yearEnd):
if not string[idx].isdigit():
yearEnd = idx
break
year = int(string[0:yearEnd])
return year
class Library(object):
def __init__(self):
path = os.path.expanduser ('~/.ssh/config')
cfg = SSHConfig()
cfg.parse(open(path))
ssh = SSHClient()
ssh.load_system_host_keys()
(host, params) = self._ssh_cfg2params(cfg)
ssh.connect(host, **params)
self._ssh = ssh
self._sftp = ssh.open_sftp()
def _ssh_cfg2params(self, config):
params = {}
cfg = config.lookup ('gate.g-node.org')
if cfg and cfg.has_key('user'):
params['username'] = cfg['user']
else:
params['username'] = os.getlogin()
if cfg and cfg.has_key('identityfile'):
params['key_filename'] = cfg['identityfile']
else:
keyfile = os.path.expanduser ('~/.ssh/id_rsa')
params['key_filename'] = keyfile
return ('gate.g-node.org', params)
def _year2folder(self, year):
if year < 1998:
if year < 1990:
string = "%.2s.." % str(year)
else:
string = "%.3s." % str(year)
else:
string = str(year)
return string
def _folder2century(self, folder):
yearEnd = len(folder)
for idx in xrange(0, yearEnd):
if not folder[idx].isdigit():
yearEnd = idx
break
yearStr = folder[0:yearEnd]
return int (int(yearStr)/(pow(10, len(yearStr) - 2)))
def _pathForPaper(self, paper):
basepath = self.basepath
folder = self._year2folder(paper.year)
path = "%s%s/%s" % (basepath, folder, paper.name)
return path
def uriForPaper(self, paper):
path = self._pathForPaper(paper)
return "sftp://gate.g-node.org" + path
def list(self, withFilter):
basepath = self.basepath
melitta = withFilter
if not melitta.year:
folders = self.paperFolders
else:
folders = {str(melitta.year) : basepath + self._year2folder(melitta.year)}
sftp = self._sftp
papers = []
for year in folders.iterkeys():
names = sftp.listdir(path=folders[year])
for name in names:
century = self._folder2century(year)
try:
paper = Paper(name, century)
if melitta.apply(paper):
papers.append(paper)
except:
print "Could not parse: %s" % (name)
return papers
def download(self, papers, pbar, localDir=None):
sftp = self._sftp
localFiles = []
if type(papers) != list:
papers = [papers]
for paper in papers:
remote = self._pathForPaper(paper)
if not localDir:
localDir = os.getcwd()
local = os.path.join (localDir, paper.name)
sftp.get(remote, local, pbar.callback)
localFiles.append(local)
pbar.nextTask()
return localFiles
@property
def paperFolders(self):
sftp = self._sftp
wd = self.basepath
dirs = sftp.listdir(path=wd)
folders = {folder : wd + folder for folder in dirs if folder[0].isdigit()}
return folders
@property
def basepath(self):
return '/groups/wachtler/literature/'
class ProgressBar(object):
def __init__(self, numTasks=1):
self._numTasks = numTasks
self._curTask = 1
def progress(self, cur_value, max_value):
size = 60
prefix = "%2s/%2s" % (self._curTask, self._numTasks)
x = int (size*cur_value/max_value)
sys.stdout.write("%s [%s%s] %i/%i\r" % (prefix, "#"*x, "." * (size-x),
cur_value, max_value))
sys.stdout.flush()
def nextTask(self):
self._curTask += 1
@property
def callback(self):
return self.progress
# ----- -----
def printPaperList(papers, withNumber=False):
extraSpace = 0
fmt = "%-20s | %4s | %-25s"
string = fmt % ("Author", "year", "Filename")
fmt_len = 55
if withNumber:
prefix = " Id | "
string = prefix + string
extraSpace = len(prefix)
print string
print "-"*(fmt_len + extraSpace)
num = 0
for paper in papers:
string = fmt % (paper.author, paper.year, paper.name)
if withNumber:
string = "%3d | %s" % (num, string)
num += 1
print string
print "-"*(fmt_len + extraSpace)
def userPickPaper(papers):
question = "Select number or all[default] ?"
while True:
answer = raw_input(question)
if answer == 'all' or answer == 'a':
return papers
try:
num = int(answer)
paper = papers[num]
return [paper]
except:
continue
# ---- commands ----
commands = {}
def Command(name, aliases=None):
def decorator(func):
commands[name] = func
if aliases:
for alias in aliases:
commands[alias] = func
def wrapper(*args, **kwargs):
func(*args, **kwargs)
return wrapper
return decorator
@Command('list', ['l'])
def doList(lib, withFilter):
melitta = withFilter
if not melitta.year:
print "Global search! This may take a while..."
papers = lib.list(withFilter=melitta)
printPaperList(papers)
return 0
@Command('download', ['dl'])
def doDownload(lib, withFilter):
melitta = withFilter
papers = lib.list(withFilter=melitta)
if len(papers) > 1:
printPaperList(papers, withNumber=True)
print "Multiple matches found!"
papers = userPickPaper(papers)
pbar = ProgressBar(numTasks=len(papers))
lib.download(papers, pbar)
return 0
@Command('open', ['o'])
def doOpen(lib, withFilter):
melitta = withFilter
papers = lib.list(withFilter=melitta)
if len(papers) > 1:
printPaperList(papers, withNumber=True)
numStr = raw_input ('Number to open? ')
try:
num = int(numStr)
paper = papers[num]
except:
print "Oh oh!"
return -1
else:
paper = papers[0]
pbar = ProgressBar(numTasks=len(papers))
local = lib.download (paper, pbar, '/tmp')
cmd = 'xdg-open "%s"' % (local[0])
os.system (cmd)
return 0
# ---- ---- ----
def createFilter(argv):
year=None
filterStr=None
if argv[0][0].isdigit():
year = argv[0]
else:
filterStr = argv[0]
if len(argv) > 1:
if not year:
year = argv[1]
else:
filterStr = argv[1]
melitta = Filter(searchFor=filterStr, inYear=year)
return melitta
def main(argv):
opts, rem = getopt.getopt(sys.argv[1:], 'v', ['version',
])
output = None
for opt, arg in opts:
if opt in ("-o", "--output"):
output = arg
if len (rem) < 1:
print "Wrong number of arguments"
return -1
cmdStr = rem[0]
if not commands.has_key(cmdStr):
print >> sys.stderr, "Unkown command: %s." % (cmdStr)
return -1;
melitta = createFilter(rem[1:])
cmd = commands[cmdStr]
lib = Library()
res = cmd(lib, melitta)
return res
if __name__ == "__main__":
res = main(sys.argv[1:])
sys.exit(res)