-
Notifications
You must be signed in to change notification settings - Fork 23
/
gplayweb
executable file
·287 lines (249 loc) · 8.76 KB
/
gplayweb
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
#! /usr/bin/python2
# -*- coding: utf-8 -*-
import sys, os, traceback, ConfigParser, argparse, multiprocessing
import tornado.ioloop, tornado.web
import pkg_resources
from gplaycli.gplaycli import GPlaycli
from subprocess import Popen, PIPE
import os.path
# Main handler
class MainHandler(tornado.web.RequestHandler):
def __init__(self, *args, **kwargs):
tornado.web.RequestHandler.__init__(self,*args, **kwargs)
self.cli = cli
# Get conf
# Where apk are stored
self.apk_folder = config['folder']
if not os.path.isdir(self.apk_folder):
os.makedirs(self.apk_folder)
# Root of the HTTP URL
self.root_url = config['root_url']
self.cache_file = '/tmp/.cache-gplayweb'
self.fdroid = False
# FDroid support is asked
if 'fdroid_exec' in config:
self.fdroid=True
self.fdroid_exec = config['fdroid_exec']
self.fdroid_repo_dir = config['fdroid_repo_dir']
# If custom category is specified
if 'fdroid_custom_category' in config:
self.fdroid_custom_category = config['fdroid_custom_category']
# Routes
def get(self):
page = self.get_argument('page',None)
if page == None:
self.redirect('list')
elif page == 'list':
self.list()
elif page == 'search':
self.search()
elif page == 'download':
self.download()
elif page == 'remove':
self.remove()
elif page == 'downloadfromserver':
self.download_from_server()
elif page == 'emptycache':
self.empty_cache()
elif page == 'fdroid-forceupdate':
self.fdroid_forceupdate()
else:
return
def redirect(self,url,permanent=False,status=None):
super(MainHandler,self).redirect(self.root_url+"?page="+url, permanent, status)
# Templates
def get_template_path(self):
embedded = os.path.dirname(os.path.abspath(__file__))+"/templates"
deployed = '/usr/share/gplayweb/templates'
# Return the embedded templates if they exists, otherwise return deployed ones via setuptools
return embedded if os.path.isdir(embedded) else deployed
def render(self, mode, items, **kwargs):
super(MainHandler,self).render(mode+".html", title="GPlayWeb", ROOT=self.root_url, items=items, **kwargs)
# Core
# Show the list of downloaded apks
def list(self):
results = self.cli.list_folder_apks(self.apk_folder)
cached_infos = self.get_infos(results)
self.render('list', cached_infos)
# ask gplay api if infos are not cached
def get_infos(self, apks):
apks = map(self.kick_extension, apks)
separator = ";"
# Ensure the cache file exists
open(self.cache_file,'a+')
cached_infos = dict()
for line in open(self.cache_file).read().splitlines():
infos = line.split(separator)
apk_name = infos[0]
if apk_name not in apks:
continue
infos.pop(0)
cached_infos[apk_name] = infos
apks = set(apks)-set(cached_infos.keys())
details = self.cli.get_bulk_details(apks)
buff = open(self.cache_file,'a')
for apk in details:
if details[apk][0]=='':
details[apk][0]=apk
buff.write(apk+separator+separator.join(details[apk]).encode('utf-8')+'\n')
buff.close()
cached_infos.update(details)
return cached_infos
def empty_cache(self):
os.remove(self.cache_file)
self.redirect('list')
def fdroid_forceupdate(self):
self.update_fdroid()
self.redirect('list')
# Search an apk by string
def search(self):
search_string = self.get_argument('name', None)
if not search_string is None : search_string = search_string.encode('utf8')
if search_string == None:
self.render('form_search', None)
return
number = self.get_argument('number',10)
results = self.cli.search(list(),search_string,number, free_only=False)
if results == None:
results = [["No Result"]]
self.render('search', results, string=search_string, number=number)
# Download an apk by codename to the server (org.mozilla.firefox)
def download(self):
package = self.get_argument('name', None)
if package == None:
self.render('download_ask', None)
return
self.cli.set_download_folder(self.apk_folder)
self.cli.download_packages([package])
# Update fdroid repo if asked
self.update_fdroid()
self.redirect('list')
# Remove the apk from the folder
def remove(self):
filename = self.get_argument('name', None)
filename = os.path.basename(filename)+'.apk'
os.remove(os.path.join(self.apk_folder, filename))
# Update fdroid repo if asked
self.update_fdroid()
self.redirect('list')
# Download the available apk from the server
def download_from_server(self):
filename = self.get_argument('name', None)
base_filename = os.path.basename(filename)+'.apk'
filename = os.path.join(self.apk_folder, base_filename)
buf_size = 4096
self.set_header('Content-Type', 'application/octet-stream')
self.set_header('Content-Disposition', 'attachment; filename=' + base_filename)
with open(filename, 'r') as f:
while True:
data = f.read(buf_size)
if not data:
break
self.write(data)
self.finish()
## Fdroid
def update_fdroid(self):
current_dir = os.path.dirname(os.path.realpath(__file__))
os.chdir(self.fdroid_repo_dir)
try:
process = Popen([self.fdroid_exec,"update","-c"], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
if process.returncode != 0:
sys.stderr.write("error while updating fdroid repository " + stderr)
else:
print("fdroid repository updated")
except:
traceback.print_exc(file=sys.stdout)
os.chdir(current_dir)
# Add custom category to downloaded apps
def customize_metadata(self):
for metadir, dirnames, metafiles in os.walk('metadata'):
for metafile in metafiles:
if metafile.endswith('.txt'):
metafile = os.path.join('metadata',metafile)
buff = open(metafile, 'a+')
if 'Categories:' not in buff.read():
buff.write('Categories:'+self.fdroid_custom_category+'\n')
buff.close()
# Delete the extension of the given string
def kick_extension(self,apkfile):
return os.path.splitext(apkfile)[0]
def default_params():
config = {
'ip': '0.0.0.0',
'port': '8888',
'root_url': '/',
'folder': 'repo',
'fdroid_custom_category': 'GPlayWeb',
}
return config
def check_config(config):
if ('fdroid_exec' in config and 'fdroid_repo_dir' not in config)\
or ('fdroid_repo_dir' in config and 'fdroid_exec' not in config):
return False, "Need to define both 'fdroid_exec' and 'fdroid_repo_dir' to support Fdroid server update! "
return True, "Success"
def fdroid_init(fdroid_exec, fdroid_repo_dir):
if not os.path.isfile(fdroid_exec):
sys.stderr.write("fdroid executable not be found: '" + fdroid_exec + "'")
try:
process = Popen([fdroid_exec,"init"], stdout=PIPE, stderr=PIPE, cwd=fdroid_repo_dir)
stdout, stderr = process.communicate()
if process.returncode != 0:
sys.stderr.write("error while initializing fdroid repository " + stderr)
else:
print("fdroid repository initialized successfully in " + fdroid_repo_dir)
except:
traceback.print_exc(file=sys.stdout)
def main():
global cli_args, config, cli
# Parsing CLI arguments
parser = argparse.ArgumentParser(description="A web interface for GPlayCli")
parser.add_argument('-c','--config',action='store',dest='CONFFILE',metavar="CONF_FILE",nargs=1,
type=str,
# default=os.path.dirname(os.path.abspath(__file__))+"/gplayweb.conf",
default="/etc/gplayweb/gplayweb.conf",
help="Use a different config file than /etc/gplayweb/gplayweb.conf")
cli_args = parser.parse_args()
configparser = ConfigParser.ConfigParser()
configparser.read(cli_args.CONFFILE)
try:
config_list = configparser.items("Server")
except ConfigParser.NoSectionError:
print("Error: [Server] section not found. Please make sure "+cli_args.CONFFILE+" exists and contains a [Server] section")
sys.exit(1)
# Get default params
config = default_params()
# Override default params
for key, value in config_list:
config[key] = value
status, errorString = check_config(config)
# If something went wrong
if not status:
print errorString
return
static_path = "/usr/share/gplayweb/static" if os.path.isdir("/usr/share/gplayweb/static") else os.path.join(os.path.dirname(__file__), "static")
if config['root_url'] != '/':
static_path = os.path.join(config['root_url'],static_path)
settings = {
"static_path": static_path,
"root_url": r""+config['root_url'],
"port": r""+config['port'],
"ip": r""+config['ip']
}
application = tornado.web.Application([
(settings['root_url'], MainHandler),
(r"/static/", tornado.web.StaticFileHandler,
dict(path=settings['static_path'])),
],**settings)
# Parsing conffile
cli = GPlaycli(cli_args.CONFFILE)
# Connect to API
cli.connect_to_googleplay_api()
# init fdroid repository, if necessary
if 'fdroid_exec' in config:
fdroid_init(config['fdroid_exec'], config['fdroid_repo_dir'])
print("starting gplayweb server, listening on " + settings['ip'] + ":"+ settings['port'])
application.listen(settings['port'],settings['ip'])
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()