-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsv2pocket.py
executable file
·216 lines (177 loc) · 7.08 KB
/
csv2pocket.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
#! /usr/bin/env python
import webbrowser
import urllib
import urllib2
import json
import ConfigParser
import os.path
import csv
import argparse
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
# app specific key
pocket_consumer_key = "56619-e39b73d25753a7667856d855"
# basic Pocket API endpoints
oauth_request_url = "https://getpocket.com/v3/oauth/request"
oauth_authorize_url = "https://getpocket.com/v3/oauth/authorize"
web_authorize_url = "https://getpocket.com/auth/authorize?request_token={}&redirect_uri={}"
pocket_add_url = "https://getpocket.com/v3/add"
pocket_send_url = "https://getpocket.com/v3/send"
# local webserver setup
redirect_uri = "http://localhost:{}/authorized"
port_number = 54321 # TODO: randomize this to avoid port collision
# user stuff
user_authorized_access = False
# config location
config_file = os.path.expanduser("~/.csv2pocket")
def set_user_authorized_access(b):
global user_authorized_access
user_authorized_access = b
def parse_response(resp):
resp_content = resp.readlines()[0]
values = {}
splits = resp_content.split("&")
for v in splits:
v_split = v.split("=")
values[v_split[0]] = v_split[1]
return values
class getHandler(BaseHTTPRequestHandler):
def do_GET(self):
set_user_authorized_access(True)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
return
class PocketItem:
"""An item to put in Pocket"""
def __init__(self, url, title, tags):
self.url = url
self.title = title
self.tags = tags
def read_pocket_items_from_csv(csv_file_name):
pocket_items = []
with open(csv_file_name, "r") as csvfile:
item_reader = csv.reader(csvfile)
for row in item_reader:
if (len(row) == 1):
# just a url
pocket_items.append(PocketItem(row[0], "", ""))
elif (len(row) == 2):
# url and title
pocket_items.append(PocketItem(row[0], row[1], ""))
else: # assume len == 3
# url and title and tags
pocket_items.append(PocketItem(row[0], row[1], row[2]))
return pocket_items
def do_pocket_auth():
oauth_request_post_body = urllib.urlencode(
{"consumer_key": pocket_consumer_key, "redirect_uri": redirect_uri})
resp = urllib2.urlopen(oauth_request_url, oauth_request_post_body)
if (resp.getcode() == 200):
request_token = parse_response(resp)["code"]
server = HTTPServer(("", port_number), getHandler)
print "Started httpserver on port", port_number
webbrowser.open(web_authorize_url.format(
request_token, redirect_uri.format(port_number)))
while (not user_authorized_access):
server.handle_request()
print "User access granted. Getting authorization token."
oauth_authorize_post_body = urllib.urlencode(
{"consumer_key": pocket_consumer_key, "code": request_token})
resp = urllib2.urlopen(oauth_authorize_url, oauth_authorize_post_body)
if (resp.getcode() == 200):
resp_values = parse_response(resp)
print "Authorized for user", resp_values["username"]
user_access_token = resp_values["access_token"]
return user_access_token
else:
print "An error happened during oauth authorize: " + resp.getcode()
# TODO: print content of X-Error-Code header
else:
print "An error happened setting up oauth request: " + resp.getcode()
# TODO: print content of X-Error-Code header
def add_to_pocket(pocket_consumer_key, user_access_token,
url, title, tags):
print "Adding", url,
pocket_add_post_body = json.dumps(
{"consumer_key": pocket_consumer_key,
"access_token": user_access_token,
"url": url,
"title": title,
"tags": tags})
req = urllib2.Request(pocket_add_url, pocket_add_post_body,
{'Content-Type': 'application/json'})
resp = urllib2.urlopen(req)
try:
if (resp.getcode() == 200):
# TODO: handle return data
print " --- done"
print resp.info()
else:
print " --- An error happened during add: " + resp.getcode()
print resp.info()
except urllib2.HTTPError as e:
print " --- An error happened during add: " + str(e.code)
print e.hdrs
def add_multiple_to_pocket(pocket_consumer_key, user_access_token, items):
for p in items:
# append csv2pocket tag to all items imported
extended_tags = p.tags
if (extended_tags == ""):
extended_tags = "csv2pocket"
else:
extended_tags += ",csv2pocket"
add_to_pocket(pocket_consumer_key, user_access_token,
p.url, p.title, extended_tags)
def add_bulk_to_pocket(pocket_consumer_key, user_access_token, items):
print "Adding {} items".format(len(items)),
bulk_add = []
for p in items:
# append csv2pocket tag to all items imported
extended_tags = p.tags
if (extended_tags == ""):
extended_tags = "csv2pocket"
else:
extended_tags += ",csv2pocket"
bulk_add.append({"action": "add",
"url": p.url,
"title": p.title,
"tags": extended_tags})
pocket_add_post_body = json.dumps(
{"consumer_key": pocket_consumer_key,
"access_token": user_access_token,
"actions": bulk_add})
req = urllib2.Request(pocket_send_url, pocket_add_post_body,
{'Content-Type': 'application/json'})
try:
resp = urllib2.urlopen(req)
if (resp.getcode() == 200):
# TODO: handle return data
print " --- done"
else:
print " --- An error happened during add: " + resp.getcode()
except urllib2.HTTPError as e:
print " --- An error happened during add: " + str(e.code)
print e.hdrs
def main():
parser = argparse.ArgumentParser(description='A simple tool for taking a CSV file and importing it to Pocket')
parser.add_argument('csv_file_name', type=str, help='the CSV file to read from')
args = parser.parse_args()
if (os.path.exists(config_file)):
# load user_access_token from file
config = ConfigParser.RawConfigParser()
config.readfp(open(config_file, "r"))
user_access_token = config.get("main", "user_access_token")
else:
# authorize and save user_access_token to avoid making
# authorization again
user_access_token = do_pocket_auth()
config = ConfigParser.RawConfigParser()
config.add_section("main")
config.set("main", "user_access_token", user_access_token)
config.write(open(config_file, "w"))
# parse csv and add each item to Pocket
pocket_items = read_pocket_items_from_csv(args.csv_file_name)
add_bulk_to_pocket(pocket_consumer_key, user_access_token,
pocket_items)
if __name__ == "__main__":
main()