forked from NoMore201/googleplay-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflask_api.py
More file actions
153 lines (124 loc) · 4.64 KB
/
Copy pathflask_api.py
File metadata and controls
153 lines (124 loc) · 4.64 KB
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
#!/usr/bin/env python3
import logging
import os
import re
import json
from requests.exceptions import ChunkedEncodingError
from flask import Flask, make_response, jsonify, abort, send_from_directory
from gpapi.googleplay import GooglePlayAPI
if "LOG_LEVEL" in os.environ:
log_level = os.environ["LOG_LEVEL"]
else:
log_level = logging.INFO
# Logging configuration.
logger = logging.getLogger(__name__)
logging.basicConfig(
format="%(asctime)s> [%(levelname)s][%(name)s][%(funcName)s()] %(message)s",
datefmt="%d/%m/%Y %H:%M:%S",
level=log_level,
)
logging.getLogger("werkzeug").disabled = True
if 'ACCOUNTS' not in os.environ or 'accounts' not in os.environ['ACCOUNTS']:
logger.error("NO ACCOUNTS")
exit(1)
else:
accounts = json.loads(os.environ['ACCOUNTS'])
indx = 0
# Directory where to save the downloaded applications.
downloaded_apk_location = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "Downloads"
)
# https://developer.android.com/guide/topics/manifest/manifest-element#package
package_name_regex = re.compile(
r"^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$", flags=re.IGNORECASE
)
def create_app():
app = Flask(__name__)
# Create the download directory (if not already existing).
if not os.path.isdir(downloaded_apk_location):
os.makedirs(downloaded_apk_location)
return app
application = create_app()
@application.errorhandler(500)
def application_error(error):
logger.error(error)
return make_response(jsonify(str(error)), error.code)
@application.route("/process/<package_name>", methods=["GET"], strict_slashes=False)
def process(package_name):
if package_name_regex.match(package_name):
try:
account = _get_account()
gsf_id = int(account['gsf_id'])
auth_sub_token = account['token']
server = GooglePlayAPI(account['lang'], account['timezone'], device_codename=account['device'])
server.login(None, None, gsf_id, auth_sub_token)
try:
# server.log(package_name)
fl = server.download(package_name)
filename = "%s_%s(%s).apk" % (package_name, fl.get('versionString'), fl.get('versionCode'))
downloaded_apk_file_path = os.path.join(
downloaded_apk_location,
filename,
)
with open(downloaded_apk_file_path, "wb") as apk_file:
for chunk in fl.get("file").get("data"):
apk_file.write(chunk)
return {
"error": False,
"package": package_name,
"filename": filename,
"version": fl.get('versionString'),
"version_code": fl.get('versionCode')
}
except ChunkedEncodingError:
logger.error(
f"An error during the download "
f"package name '{package_name}'",
)
return {
"package": package_name,
"error": True,
"status": "download error"
}
except AttributeError:
logger.error(
f"Unable to retrieve application with "
f"package name '{package_name}'",
)
return {
"package": package_name,
"error": True,
"status": "not valid"
}
except Exception as e:
logger.critical(f"Error during the download: {e}")
desc = 'unknown'
if e.value and "not supported in your country" in e.value:
return {
"package": package_name,
"error": True,
"status": "country"
}
if e.value and "device is not compatible" in e.value:
return {
"package": package_name,
"error": True,
"status": "device"
}
abort(500, desc)
else:
logger.critical("Please specify a valid package name")
abort(400, description='Not valid package')
@application.route('/download/<path:filename>', methods=['GET', 'POST'])
def download(filename):
return send_from_directory(downloaded_apk_location, filename)
def _get_account():
global indx
if len(accounts['accounts']) == indx:
indx = 0
acc = accounts['accounts'][indx]
indx += 1
return acc
if __name__ == "__main__":
from waitress import serve
serve(application, host="0.0.0.0", port=8085)