@enplug/scripts 1.11.4-dev.1 → 1.11.4-dev2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
package/bin/build-ng.js CHANGED
File without changes
File without changes
@@ -13,8 +13,11 @@ const { catchError, switchMap, tap, filter } = require('rxjs/operators');
13
13
  const HTTP_UNAUTHORIZED_STATUS_CODE = 401;
14
14
  const HTTP_NOT_FOUND_STATUS_CODE = 404;
15
15
 
16
- const CROWDIN_PROJECT_ID = 'enplug';
17
- const CROWDIN_PROJECT_URL = `https://api.crowdin.com/api/project/${CROWDIN_PROJECT_ID}`;
16
+ // const CROWDIN_PROJECT_ID = 'enplug';
17
+ const CROWDIN_PROJECT_ID = '401630';
18
+ // const CROWDIN_PROJECT_URL = `https://api.crowdin.com/api/project/${CROWDIN_PROJECT_ID}`;
19
+ const CROWDIN_PROJECT_URL = `https://api.crowdin.com/api/v2/projects/${CROWDIN_PROJECT_ID}`;
20
+ const CROWDIN_STORAGE_URL = `https://api.crowdin.com/api/v2/storages`;
18
21
  const CROWDIN_DIRECTORY_NOT_FOUND_ERROR_CODE = 17;
19
22
 
20
23
  async function uploadFileToCrowdin(credentials, crowdinPath, localPath) {
@@ -105,26 +108,119 @@ function getCrowdinConfig() {
105
108
  return pkg.config.crowdin;
106
109
  }
107
110
 
108
- function generateFormData(credentials, crowdinPath, localPath) {
111
+ function generateFormData(crowdinPath, localPath) {
109
112
  const formData = new FormData();
110
113
 
111
- formData.append('login', credentials.login);
112
- formData.append('account-key', credentials.accountKey);
113
- formData.append('update_option', 'update_without_changes'); // Previous translations should remain valid
114
+ // formData.append('update_option', 'update_without_changes'); // Previous translations should remain valid
114
115
  formData.append('json', '');
115
116
  formData.append(`files[${crowdinPath}]`, fs.createReadStream(localPath));
116
117
  formData.append(`export_patterns[${crowdinPath}]`, '%locale%.json');
117
-
118
118
  return formData;
119
119
  }
120
120
 
121
121
  function postFileToCrowdin(operation, credentials, crowdinPath, localPath) {
122
- const formData = generateFormData(credentials, crowdinPath, localPath);
122
+ const AuthStr = 'Bearer '.concat(credentials.token);
123
+ const formData = generateFormData(crowdinPath, localPath);
124
+
125
+ const url = `${CROWDIN_STORAGE_URL}`;
126
+
127
+ return from(axios.post(url, formData, { headers: {
128
+ "Authorization": AuthStr,
129
+ "Content-Type": "application/json",
130
+ "Crowdin-API-FileName": "en.json"
131
+ } }));
132
+ }
133
+
134
+ async function findCrowdinAppDirectoryId(credentials, crowdinPath) {
135
+ path = crowdinPath.startsWith('/') ? crowdinPath.substr(1) : crowdinPath;
136
+ if(path.startsWith('apps')){
137
+ const appName = path.split('/')[1];
138
+ const url = `${CROWDIN_PROJECT_URL}/directories?filter=${appName}`;
139
+ const AuthStr = 'Bearer '.concat(credentials.token);
140
+ const directories = await axios.get(url, { headers: { Authorization: AuthStr } });
141
+ return directories.data.find(d => d.data.name === appName).id;
142
+ } else if(path.startsWith('dashboard')) {
143
+ const url = `${CROWDIN_PROJECT_URL}/directories?filter=dashboard`;
144
+ const AuthStr = 'Bearer '.concat(credentials.token);
145
+ const directories = axios.get(url, { headers: { Authorization: AuthStr } });
146
+ return directories.data.find(d => d.data.name === 'dashboard' && d.data.title === 'Dashboard' && d.data.path === '/dashboard').id;
147
+ }
148
+ }
123
149
 
124
- const operationEndpoint = operation === 'update' ? `update-file` : 'add-file';
125
- const url = `${CROWDIN_PROJECT_URL}/${operationEndpoint}`;
150
+ async function findCrowdinAppSubFolderId(credentials, directoryId, subfolderName) {
151
+ const url = `${CROWDIN_PROJECT_URL}/directories?directoryId=${directoryId}`;
152
+ const AuthStr = 'Bearer '.concat(credentials.token);
153
+ const directories = await axios.get(url, { headers: { Authorization: AuthStr } });
154
+ return directories.data.find(d => d.data.name === subfolderName).id;
155
+ }
156
+
157
+ async function getFileIdIfExists(credentials, directoryId, fileName) {
158
+ const url = `${CROWDIN_PROJECT_URL}/files?directoryId=${directoryId}`;
159
+ const AuthStr = 'Bearer '.concat(credentials.token);
160
+ const files = await axios.get(url, { headers: { Authorization: AuthStr } });
161
+ return files.data.find(d => d.data.name === fileName).id;
162
+ }
126
163
 
127
- return from(axios.post(url, formData, { headers: formData.getHeaders() }));
164
+ async function uploadFileToCrowdinStorage(credentials, crowdinPath, localPath) {
165
+ if (!fs.existsSync(localPath)) {
166
+ console.error(`${chalk.red.bold('Local file does not exists')} ${chalk.yellow.bold(`[${localPath}]`)}`);
167
+ throw new Error('Local file does not exist');
168
+ }
169
+
170
+ return postFileToCrowdin('update', credentials, crowdinPath, localPath).pipe(
171
+ catchError(error => {
172
+ if (error.response.status === HTTP_NOT_FOUND_STATUS_CODE) {
173
+ return promptAddFile(crowdinPath).pipe(
174
+ filter(({addFileConfirm}) => addFileConfirm === true),
175
+ switchMap(() => postFileToCrowdin('add', credentials, crowdinPath, localPath))
176
+ );
177
+ }
178
+
179
+ return throwError(error);
180
+ }),
181
+ tap({
182
+ next: response => {
183
+ if (response.data) {
184
+ console.log(`${chalk.green.bold('Translations uploaded to Crowdin')} ${chalk.yellow.bold(`[${crowdinPath}]`)}`);
185
+ } else {
186
+ console.error('Unexpected result');
187
+ console.log(response);
188
+ }
189
+ },
190
+ error: error => {
191
+ const crowdinError = error.response && error.response.data && error.response.data.error;
192
+
193
+ if (crowdinError && crowdinError.code === CROWDIN_DIRECTORY_NOT_FOUND_ERROR_CODE) {
194
+ console.error(`\n${chalk.red.bold('Directory does not exist')} ${chalk.yellow.bold(`[${crowdinPath}]`)}`);
195
+ console.log('Create the directory in the Crowdin panel first.');
196
+ } else if (error.response.status === HTTP_UNAUTHORIZED_STATUS_CODE) {
197
+ console.error(`\n${chalk.red.bold('Provided Crowdin credentials are incorrect')}`);
198
+ console.log(`Check the ${chalk.default.yellow('dev.private.json')} file.`);
199
+ } else {
200
+ console.error('\nUnexpected error:');
201
+ console.error(error);
202
+ }
203
+ }
204
+ })
205
+ ).toPromise();
206
+ }
207
+
208
+ function updateCrowdinFile(credentials, storageId, fileId) {
209
+ const url = `${CROWDIN_PROJECT_URL}/files/${fileId}`;
210
+ const AuthStr = 'Bearer '.concat(credentials.token);
211
+ const body = {
212
+ "storageId": storageId,
213
+ "updateOption": "keep_translations_and_approvals",
214
+ "importOptions": {
215
+ "contentSegmentation": false,
216
+ "customSegmentation": false
217
+ },
218
+ "exportOptions": {
219
+ "exportPattern": "%locale%.json"
220
+ },
221
+ "replaceModifiedContext": false
222
+ }
223
+ return axios.put(url, body, { headers: { Authorization: AuthStr } });
128
224
  }
129
225
 
130
226
  function fetchFileFromCrowdin(credentials, crowdinPath, language) {
@@ -149,4 +245,4 @@ function promptAddFile(crowdinPath) {
149
245
  }));
150
246
  }
151
247
 
152
- module.exports = { getCrowdinCredentials, getCrowdinConfig, uploadFileToCrowdin, fetchFileFromCrowdin };
248
+ module.exports = { getCrowdinCredentials, getCrowdinConfig, findCrowdinAppDirectoryId, findCrowdinAppSubFolderId, getFileIdIfExists, uploadFileToCrowdinStorage, updateCrowdinFile, uploadFileToCrowdin, fetchFileFromCrowdin };
@@ -5,7 +5,7 @@ const inquirer = require('inquirer');
5
5
  const fs = require('fs');
6
6
  const path = require('path');
7
7
 
8
- const { getCrowdinCredentials, getCrowdinConfig, uploadFileToCrowdin, fetchFileFromCrowdin } = require('./crowdin');
8
+ const { getCrowdinCredentials, getCrowdinConfig, findCrowdinAppDirectoryId, findCrowdinAppSubFolderId, getFileIdIfExists, uploadFileToCrowdinStorage, updateCrowdinFile, uploadFileToCrowdin, fetchFileFromCrowdin } = require('./crowdin');
9
9
  const { checkKeys, validateTranslationFile } = require('./transloco');
10
10
  const { uploadTranslationToS3 } = require('./translation-s3');
11
11
  const getPackageJson = require('../getPackageJson');
@@ -43,6 +43,12 @@ async function syncTranslations(s3Client, bucket) {
43
43
  config = getCrowdinConfig();
44
44
  } catch {}
45
45
 
46
+ if (!credentials || !credentials.token) {
47
+ console.error(`${chalk.red.bold('Crowdin credentials not provided')}`);
48
+ console.log(`Make sure that the ${chalk.default.yellow('dev.private.json')} file contains ${chalk.default.yellow('crowdinCredentials: { token }')}`);
49
+ throw new Error('Crowdin credentials not provided');
50
+ }
51
+
46
52
  if (credentials && config) {
47
53
  const { confirmUpload } = await promptUpload(config.crowdinPath, isProduction);
48
54
 
@@ -55,13 +61,29 @@ async function syncTranslations(s3Client, bucket) {
55
61
  await uploadTranslationToS3(s3Client, bucket, s3EnPath, enTranslation);
56
62
 
57
63
  if (isProduction) {
58
- await uploadFileToCrowdin(credentials, config.crowdinPath, config.localPath);
59
- const { data: fakeTranslation } = await fetchFileFromCrowdin(credentials, config.crowdinPath, FAKE_IN_CONTEXT_LANGUAGE);
60
-
61
- const s3TranslationsPath = path.parse(s3EnPath).dir;
62
- const s3FakeTranslationPath = path.join(s3TranslationsPath, FAKE_IN_CONTEXT_LANGUAGE_FILE);
63
-
64
- await uploadTranslationToS3(s3Client, bucket, s3FakeTranslationPath, JSON.stringify(fakeTranslation));
64
+ const appDirectoryId = await findCrowdinAppDirectoryId(credentials, config.crowdinPath);
65
+ console.log('found directoryId', appDirectoryId);
66
+ if(config.crowdinPath.includes('apps')) {
67
+ const path = crowdinPath.startsWith('/') ? crowdinPath.substr(1) : crowdinPath;
68
+ const subfolderName = path.split('/')[2];
69
+ const folderId = await findCrowdinAppSubFolderId(credentials, appDirectoryId, subfolderName);
70
+ console.log('found folderId', folderId);
71
+ const fileId = await getFileIdIfExists(credentials, appDirectoryId, path.split('/')[3]);
72
+ console.log('found fileId', fileId);
73
+ const storageId = await uploadFileToCrowdinStorage(credentials, config.crowdinPath, config.localPath)
74
+ if(fileId) {
75
+ await updateCrowdinFile(credentials, storageId, fileId);
76
+ }
77
+ } else {
78
+ // TODO Update dashboard transtlations file
79
+ }
80
+ // await uploadFileToCrowdin(credentials, config.crowdinPath, config.localPath);
81
+ // const { data: fakeTranslation } = await fetchFileFromCrowdin(credentials, config.crowdinPath, FAKE_IN_CONTEXT_LANGUAGE);
82
+
83
+ // const s3TranslationsPath = path.parse(s3EnPath).dir;
84
+ // const s3FakeTranslationPath = path.join(s3TranslationsPath, FAKE_IN_CONTEXT_LANGUAGE_FILE);
85
+
86
+ // await uploadTranslationToS3(s3Client, bucket, s3FakeTranslationPath, JSON.stringify(fakeTranslation));
65
87
  }
66
88
  }
67
89
  }
File without changes
File without changes
package/bin/release-ng.js CHANGED
File without changes
File without changes
package/bin/serve-ng.js CHANGED
File without changes
@@ -1,23 +1,23 @@
1
-
2
- # sqs_is_prod = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"select * from Settings;\""
3
- adb_devices = "adb devices"
4
- build_binary = "pyinstaller --onefile enplug_device.py --distpath ../bin/"
5
- change_env_to_development = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"delete from settings where key='eduid';delete from settings where key='eduid';delete from settings where key='edutoken';delete from settings where key='eduname';insert into settings (key, value) values ('environment', 'development');update settings set value='development' where key='environment';\""
6
- change_env_to_production = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"delete from settings where key='eduid';delete from settings where key='eduid';delete from settings where key='edutoken';delete from settings where key='eduname';insert into settings (key, value) values ('environment', 'development');update settings set value='development' where key='environment';\""
7
- change_env_to_staging = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"delete from settings where key='eduid';delete from settings where key='eduid';delete from settings where key='edutoken';delete from settings where key='eduname';insert into settings (key, value) values ('environment', 'staging');update settings set value='staging' where key='environment';\""
8
- clear_cache = "adb shell pm clear com.enplug.player"
9
- copy_player_file_to_device = "adb push Player.apk '/sdcard/Download'"
10
- disable_webview = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"delete from Settings where key='UseWebView'; insert into Settings values ('UseWebView', 'false');\""
11
- enable_web_debugger = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"insert into settings values('WebRemoteDebugging','true')\""
12
- enable_webview = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"delete from Settings where key='UseWebView'; insert into Settings values ('UseWebView', 'true');\""
13
- get_environment = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"select value from Settings where key='environment';\""
14
- install_package = "adb install Player.apk"
15
- logs_delete_all = "adb shell rm /sdcard/LogWriter/*"
16
- make_sdcard_writable = "adb shell mount -o rw,remount rootfs /"
17
- reboot = "adb shell reboot"
18
- set_zoning_version_development = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"delete from Settings where key='ZoningHostUrl'; insert into Settings values ('ZoningHostUrl', 'https://dev-player.enplug.in/{0}/');\""
19
- set_zoning_version_production = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"delete from Settings where key='ZoningHostUrl'; insert into Settings values ('ZoningHostUrl', 'https://player.enplug.com/{0}/');\""
20
- set_zoning_version_staging = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"delete from Settings where key='ZoningHostUrl'; insert into Settings values ('ZoningHostUrl', 'https://player.enplug.in/{0}/');\""
21
- show_settings="adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"select * from Settings;\""
22
- uninstall_package = "adb uninstall com.enplug.player"
1
+
2
+ # sqs_is_prod = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"select * from Settings;\""
3
+ adb_devices = "adb devices"
4
+ build_binary = "pyinstaller --onefile enplug_device.py --distpath ../bin/"
5
+ change_env_to_development = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"delete from settings where key='eduid';delete from settings where key='eduid';delete from settings where key='edutoken';delete from settings where key='eduname';insert into settings (key, value) values ('environment', 'development');update settings set value='development' where key='environment';\""
6
+ change_env_to_production = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"delete from settings where key='eduid';delete from settings where key='eduid';delete from settings where key='edutoken';delete from settings where key='eduname';insert into settings (key, value) values ('environment', 'development');update settings set value='development' where key='environment';\""
7
+ change_env_to_staging = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"delete from settings where key='eduid';delete from settings where key='eduid';delete from settings where key='edutoken';delete from settings where key='eduname';insert into settings (key, value) values ('environment', 'staging');update settings set value='staging' where key='environment';\""
8
+ clear_cache = "adb shell pm clear com.enplug.player"
9
+ copy_player_file_to_device = "adb push Player.apk '/sdcard/Download'"
10
+ disable_webview = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"delete from Settings where key='UseWebView'; insert into Settings values ('UseWebView', 'false');\""
11
+ enable_web_debugger = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"insert into settings values('WebRemoteDebugging','true')\""
12
+ enable_webview = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"delete from Settings where key='UseWebView'; insert into Settings values ('UseWebView', 'true');\""
13
+ get_environment = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"select value from Settings where key='environment';\""
14
+ install_package = "adb install Player.apk"
15
+ logs_delete_all = "adb shell rm /sdcard/LogWriter/*"
16
+ make_sdcard_writable = "adb shell mount -o rw,remount rootfs /"
17
+ reboot = "adb shell reboot"
18
+ set_zoning_version_development = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"delete from Settings where key='ZoningHostUrl'; insert into Settings values ('ZoningHostUrl', 'https://dev-player.enplug.in/{0}/');\""
19
+ set_zoning_version_production = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"delete from Settings where key='ZoningHostUrl'; insert into Settings values ('ZoningHostUrl', 'https://player.enplug.com/{0}/');\""
20
+ set_zoning_version_staging = "adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"delete from Settings where key='ZoningHostUrl'; insert into Settings values ('ZoningHostUrl', 'https://player.enplug.in/{0}/');\""
21
+ show_settings="adb shell sqlite3 /data/data/com.enplug.player/databases/settings.db \"select * from Settings;\""
22
+ uninstall_package = "adb uninstall com.enplug.player"
23
23
  test_elevator="adb shell am broadcast -a com.enplug.player.LIFT --es Floor \"2\" --ei Arrow 1 --ei Status 0"
@@ -1,256 +1,256 @@
1
- #!/usr/bin/python -u
2
-
3
- import getopt
4
- import json
5
- import os
6
- import shutil
7
- import sys
8
- import time
9
- from urllib.request import Request
10
- from urllib.request import urlopen
11
- from urllib.request import urlretrieve
12
- import subprocess
13
-
14
-
15
- import commands as cmd
16
-
17
- DEVELOPMENT_DEPLOYMENTS_URL = "https://dev-devices.enplug.in/devices/app/deployments?platform=Edu"
18
- PROD_DEPLOYMENTS_URL = "https://devices.enplug.com/devices/app/deployments?platform=Edu"
19
- STAGING_DEPLOYMENTS_URL = "https://staging-devices.enplug.in/devices/app/deployments?platform=Edu"
20
- KONE_STAGING_URL = "https://s3-us-west-2.amazonaws.com/enplug-android-image/test/StagingPlayer.apk"
21
-
22
-
23
- def main(argv):
24
- run_command(cmd.adb_devices)
25
- showOptions()
26
-
27
-
28
- def showOptions():
29
- environment = run_command(cmd.get_environment)
30
- print('\nEnvironment is set to: ' + environment.upper() + '\n')
31
-
32
- print('[1] Reboot')
33
- print('[2] Clear Device Cache')
34
- print('[3] Set Custom Zoning Host Version')
35
- print('[4] Logs')
36
- print('[5] Change Environment')
37
- print('[6] Enable Web Debugger')
38
- print('[7] Enable/Disable WebView')
39
- print('[8] Show settings table')
40
- print('[9] Test elevator')
41
- print('')
42
- # print ('[B] Build .exe File')
43
- print('[Q] Quit')
44
- sys.stdout.flush()
45
-
46
- option = input().strip().lower()
47
-
48
- if option == "1":
49
- reboot()
50
- elif option == "2":
51
- clearCache()
52
- elif option == "3":
53
- setZoningVersion()
54
- elif option == "4":
55
- showLogOptions()
56
- elif option == "5":
57
- changeEnvironment()
58
- elif option == "6":
59
- enableWebDebugger()
60
- elif option == "7":
61
- enableDisableWebView()
62
- elif option == "8":
63
- showSettingsTable()
64
- elif option == "9":
65
- sendElevatorIntent()
66
- elif option == "b":
67
- build()
68
-
69
- elif option == "q":
70
- sys.exit(0)
71
-
72
- sys.stdout.flush()
73
- log('------------------------')
74
- time.sleep(5)
75
- showOptions()
76
-
77
-
78
- def build():
79
- run_command(cmd.build_binary)
80
- shutil.rmtree('build')
81
- os.remove('commands.pyc')
82
- os.remove('enplug_device.spec')
83
-
84
-
85
- def changeEnvironment():
86
- log("Select target environment", True)
87
- log('[1] Development')
88
- log('[2] Staging')
89
- log('[3] Production')
90
- log('[4] KONE Staging')
91
- option = input().strip().lower()
92
- is_kone = False
93
-
94
- if option == "1":
95
- log("Changing device environment to: DEVELOPMENT", True)
96
- url = DEVELOPMENT_DEPLOYMENTS_URL
97
- elif option == "2":
98
- log("Changing device environment to: STAGING", True)
99
- url = STAGING_DEPLOYMENTS_URL
100
- elif option == "3":
101
- log("Changing device environment to: PRODUCTION")
102
- url = PROD_DEPLOYMENTS_URL
103
- elif option == "4":
104
- log("Changing KONE device environment to STAGING", True)
105
- is_kone = True
106
- else:
107
- log("Invalid input. Exiting.")
108
- sys.exit()
109
-
110
- if is_kone:
111
- downloadFile(KONE_STAGING_URL, "Player.apk")
112
- run_command(cmd.uninstall_package)
113
- run_command(cmd.install_package)
114
- log("Please wait (20s) while the script makes appropriate database changes...", True)
115
- time.sleep(20)
116
- run_command(cmd.change_env_to_staging)
117
- run_command(cmd.reboot)
118
- return
119
-
120
- log("Fetching deployment URLs from " + url)
121
-
122
- response = urlopen(url)
123
- html = response.read()
124
- package_json_data = json.loads(html)
125
- player_packages = package_json_data["Result"]
126
-
127
- for pkg in player_packages:
128
- if pkg["AppName"] == "Player":
129
- pkg_url = pkg["PackageUrl"]
130
- log("Original URL: " + pkg_url)
131
- pkg_url = pkg_url.replace('https://staging-eduapps.enplug.in', 'http://staging-eduapps.enplug.in.s3-website-us-west-2.amazonaws.com')
132
- pkg_url = pkg_url.replace('https://eduapps.enplug.com', 'https://s3-us-west-2.amazonaws.com/eduapps.enplug.com')
133
- pkg_url = pkg_url.replace('https://dev-eduapps.enplug.in', 'http://dev-eduapps.enplug.in.s3-website-us-west-2.amazonaws.com')
134
-
135
- downloadFile(pkg_url, "Player.apk")
136
- run_command(cmd.uninstall_package)
137
- run_command(cmd.install_package)
138
- if (option == "1"): # Development
139
- log("Please wait (20s) while the script makes appropriate database changes (dev)...", True)
140
- time.sleep(20)
141
- run_command(cmd.change_env_to_development)
142
- if (option == "2"): # Staging
143
- log("Please wait (20s) while the script makes appropriate database changes (staging)...", True)
144
- time.sleep(20)
145
- run_command(cmd.change_env_to_staging)
146
- if (option == "3"): # Production
147
- log("Please wait (20s) while the script makes appropriate database changes (prod)...", True)
148
- time.sleep(20)
149
- run_command(cmd.change_env_to_production)
150
- clearCache()
151
-
152
-
153
- def clearCache():
154
- log("Clearing cache...")
155
- sys.stdout.flush()
156
- run_command(cmd.clear_cache)
157
-
158
-
159
- def downloadFile(url, filename):
160
- log("Downloading package file: " + url)
161
- urlretrieve(url, filename)
162
- log("Downloaded file and saved as " + filename)
163
-
164
-
165
- def deleteAllLogFiles():
166
- run_command(cmd.logs_delete_all)
167
-
168
-
169
- def enableDisableWebView():
170
- log('[1] Enable WebView')
171
- log('[2] Disable WebView')
172
- option = input().strip().lower()
173
-
174
- if option == "1":
175
- log("Enabling WebView setting...", True)
176
- run_command(cmd.enable_webview)
177
- elif option == "2":
178
- log("Disabling WebView setting...", True)
179
- run_command(cmd.disable_webview)
180
- else:
181
- log("Invalid input. Exiting.")
182
- sys.exit()
183
-
184
- def enableWebDebugger():
185
- run_command(cmd.enable_web_debugger)
186
-
187
-
188
- def log(message, new_line=False):
189
- if new_line:
190
- print()
191
- print(message)
192
- sys.stdout.flush()
193
-
194
-
195
- def reboot():
196
- log("Rebooting device...")
197
- sys.stdout.flush()
198
- run_command(cmd.reboot)
199
-
200
-
201
- def run_command(command, *params):
202
- command = command.format(*params)
203
- # log("Executing command: ", True)
204
- # log(' ' + command)
205
- command = command.split()
206
- p = subprocess.Popen(command, stdout=subprocess.PIPE)
207
- out, err = p.communicate()
208
- return out.strip().decode('utf-8')
209
-
210
-
211
- def setZoningVersion():
212
- environment = run_command(cmd.get_environment)
213
- log("Enter new version: ")
214
- ver = input().strip()
215
- if not environment:
216
- environment = run_command(cmd.get_environment)
217
-
218
- if environment == "production":
219
- run_command(cmd.set_zoning_version_production, ver)
220
- elif environment == "staging":
221
- run_command(cmd.set_zoning_version_staging, ver)
222
- elif environment == "dev":
223
- run_command(cmd.set_zoning_version_development, ver)
224
- else:
225
- print("Error: Unable to change version. Unknown current environment")
226
- run_command(cmd.reboot)
227
-
228
-
229
- def showLogOptions():
230
- log('[1] Download Logs Directory')
231
- log('[2] Download Logs as One File')
232
- log('[3] Delete All Logs')
233
- option = input().strip().lower()
234
-
235
- if option == "1":
236
- log("Downloading logs directory...", True)
237
- elif option == "2":
238
- log("Downloading and concatenating available logs...")
239
- elif option == "3":
240
- log("Deleting all logs...")
241
- deleteAllLogFiles()
242
- else:
243
- log("Invalid input. Exiting.")
244
- sys.exit()
245
-
246
-
247
- def showSettingsTable():
248
- settingsOut = run_command(cmd.show_settings)
249
- print(settingsOut)
250
-
251
- def sendElevatorIntent():
252
- elevator = run_command(cmd.test_elevator)
253
-
254
-
255
- if __name__ == "__main__":
256
- main(sys.argv[1:])
1
+ #!/usr/bin/python -u
2
+
3
+ import getopt
4
+ import json
5
+ import os
6
+ import shutil
7
+ import sys
8
+ import time
9
+ from urllib.request import Request
10
+ from urllib.request import urlopen
11
+ from urllib.request import urlretrieve
12
+ import subprocess
13
+
14
+
15
+ import commands as cmd
16
+
17
+ DEVELOPMENT_DEPLOYMENTS_URL = "https://dev-devices.enplug.in/devices/app/deployments?platform=Edu"
18
+ PROD_DEPLOYMENTS_URL = "https://devices.enplug.com/devices/app/deployments?platform=Edu"
19
+ STAGING_DEPLOYMENTS_URL = "https://staging-devices.enplug.in/devices/app/deployments?platform=Edu"
20
+ KONE_STAGING_URL = "https://s3-us-west-2.amazonaws.com/enplug-android-image/test/StagingPlayer.apk"
21
+
22
+
23
+ def main(argv):
24
+ run_command(cmd.adb_devices)
25
+ showOptions()
26
+
27
+
28
+ def showOptions():
29
+ environment = run_command(cmd.get_environment)
30
+ print('\nEnvironment is set to: ' + environment.upper() + '\n')
31
+
32
+ print('[1] Reboot')
33
+ print('[2] Clear Device Cache')
34
+ print('[3] Set Custom Zoning Host Version')
35
+ print('[4] Logs')
36
+ print('[5] Change Environment')
37
+ print('[6] Enable Web Debugger')
38
+ print('[7] Enable/Disable WebView')
39
+ print('[8] Show settings table')
40
+ print('[9] Test elevator')
41
+ print('')
42
+ # print ('[B] Build .exe File')
43
+ print('[Q] Quit')
44
+ sys.stdout.flush()
45
+
46
+ option = input().strip().lower()
47
+
48
+ if option == "1":
49
+ reboot()
50
+ elif option == "2":
51
+ clearCache()
52
+ elif option == "3":
53
+ setZoningVersion()
54
+ elif option == "4":
55
+ showLogOptions()
56
+ elif option == "5":
57
+ changeEnvironment()
58
+ elif option == "6":
59
+ enableWebDebugger()
60
+ elif option == "7":
61
+ enableDisableWebView()
62
+ elif option == "8":
63
+ showSettingsTable()
64
+ elif option == "9":
65
+ sendElevatorIntent()
66
+ elif option == "b":
67
+ build()
68
+
69
+ elif option == "q":
70
+ sys.exit(0)
71
+
72
+ sys.stdout.flush()
73
+ log('------------------------')
74
+ time.sleep(5)
75
+ showOptions()
76
+
77
+
78
+ def build():
79
+ run_command(cmd.build_binary)
80
+ shutil.rmtree('build')
81
+ os.remove('commands.pyc')
82
+ os.remove('enplug_device.spec')
83
+
84
+
85
+ def changeEnvironment():
86
+ log("Select target environment", True)
87
+ log('[1] Development')
88
+ log('[2] Staging')
89
+ log('[3] Production')
90
+ log('[4] KONE Staging')
91
+ option = input().strip().lower()
92
+ is_kone = False
93
+
94
+ if option == "1":
95
+ log("Changing device environment to: DEVELOPMENT", True)
96
+ url = DEVELOPMENT_DEPLOYMENTS_URL
97
+ elif option == "2":
98
+ log("Changing device environment to: STAGING", True)
99
+ url = STAGING_DEPLOYMENTS_URL
100
+ elif option == "3":
101
+ log("Changing device environment to: PRODUCTION")
102
+ url = PROD_DEPLOYMENTS_URL
103
+ elif option == "4":
104
+ log("Changing KONE device environment to STAGING", True)
105
+ is_kone = True
106
+ else:
107
+ log("Invalid input. Exiting.")
108
+ sys.exit()
109
+
110
+ if is_kone:
111
+ downloadFile(KONE_STAGING_URL, "Player.apk")
112
+ run_command(cmd.uninstall_package)
113
+ run_command(cmd.install_package)
114
+ log("Please wait (20s) while the script makes appropriate database changes...", True)
115
+ time.sleep(20)
116
+ run_command(cmd.change_env_to_staging)
117
+ run_command(cmd.reboot)
118
+ return
119
+
120
+ log("Fetching deployment URLs from " + url)
121
+
122
+ response = urlopen(url)
123
+ html = response.read()
124
+ package_json_data = json.loads(html)
125
+ player_packages = package_json_data["Result"]
126
+
127
+ for pkg in player_packages:
128
+ if pkg["AppName"] == "Player":
129
+ pkg_url = pkg["PackageUrl"]
130
+ log("Original URL: " + pkg_url)
131
+ pkg_url = pkg_url.replace('https://staging-eduapps.enplug.in', 'http://staging-eduapps.enplug.in.s3-website-us-west-2.amazonaws.com')
132
+ pkg_url = pkg_url.replace('https://eduapps.enplug.com', 'https://s3-us-west-2.amazonaws.com/eduapps.enplug.com')
133
+ pkg_url = pkg_url.replace('https://dev-eduapps.enplug.in', 'http://dev-eduapps.enplug.in.s3-website-us-west-2.amazonaws.com')
134
+
135
+ downloadFile(pkg_url, "Player.apk")
136
+ run_command(cmd.uninstall_package)
137
+ run_command(cmd.install_package)
138
+ if (option == "1"): # Development
139
+ log("Please wait (20s) while the script makes appropriate database changes (dev)...", True)
140
+ time.sleep(20)
141
+ run_command(cmd.change_env_to_development)
142
+ if (option == "2"): # Staging
143
+ log("Please wait (20s) while the script makes appropriate database changes (staging)...", True)
144
+ time.sleep(20)
145
+ run_command(cmd.change_env_to_staging)
146
+ if (option == "3"): # Production
147
+ log("Please wait (20s) while the script makes appropriate database changes (prod)...", True)
148
+ time.sleep(20)
149
+ run_command(cmd.change_env_to_production)
150
+ clearCache()
151
+
152
+
153
+ def clearCache():
154
+ log("Clearing cache...")
155
+ sys.stdout.flush()
156
+ run_command(cmd.clear_cache)
157
+
158
+
159
+ def downloadFile(url, filename):
160
+ log("Downloading package file: " + url)
161
+ urlretrieve(url, filename)
162
+ log("Downloaded file and saved as " + filename)
163
+
164
+
165
+ def deleteAllLogFiles():
166
+ run_command(cmd.logs_delete_all)
167
+
168
+
169
+ def enableDisableWebView():
170
+ log('[1] Enable WebView')
171
+ log('[2] Disable WebView')
172
+ option = input().strip().lower()
173
+
174
+ if option == "1":
175
+ log("Enabling WebView setting...", True)
176
+ run_command(cmd.enable_webview)
177
+ elif option == "2":
178
+ log("Disabling WebView setting...", True)
179
+ run_command(cmd.disable_webview)
180
+ else:
181
+ log("Invalid input. Exiting.")
182
+ sys.exit()
183
+
184
+ def enableWebDebugger():
185
+ run_command(cmd.enable_web_debugger)
186
+
187
+
188
+ def log(message, new_line=False):
189
+ if new_line:
190
+ print()
191
+ print(message)
192
+ sys.stdout.flush()
193
+
194
+
195
+ def reboot():
196
+ log("Rebooting device...")
197
+ sys.stdout.flush()
198
+ run_command(cmd.reboot)
199
+
200
+
201
+ def run_command(command, *params):
202
+ command = command.format(*params)
203
+ # log("Executing command: ", True)
204
+ # log(' ' + command)
205
+ command = command.split()
206
+ p = subprocess.Popen(command, stdout=subprocess.PIPE)
207
+ out, err = p.communicate()
208
+ return out.strip().decode('utf-8')
209
+
210
+
211
+ def setZoningVersion():
212
+ environment = run_command(cmd.get_environment)
213
+ log("Enter new version: ")
214
+ ver = input().strip()
215
+ if not environment:
216
+ environment = run_command(cmd.get_environment)
217
+
218
+ if environment == "production":
219
+ run_command(cmd.set_zoning_version_production, ver)
220
+ elif environment == "staging":
221
+ run_command(cmd.set_zoning_version_staging, ver)
222
+ elif environment == "dev":
223
+ run_command(cmd.set_zoning_version_development, ver)
224
+ else:
225
+ print("Error: Unable to change version. Unknown current environment")
226
+ run_command(cmd.reboot)
227
+
228
+
229
+ def showLogOptions():
230
+ log('[1] Download Logs Directory')
231
+ log('[2] Download Logs as One File')
232
+ log('[3] Delete All Logs')
233
+ option = input().strip().lower()
234
+
235
+ if option == "1":
236
+ log("Downloading logs directory...", True)
237
+ elif option == "2":
238
+ log("Downloading and concatenating available logs...")
239
+ elif option == "3":
240
+ log("Deleting all logs...")
241
+ deleteAllLogFiles()
242
+ else:
243
+ log("Invalid input. Exiting.")
244
+ sys.exit()
245
+
246
+
247
+ def showSettingsTable():
248
+ settingsOut = run_command(cmd.show_settings)
249
+ print(settingsOut)
250
+
251
+ def sendElevatorIntent():
252
+ elevator = run_command(cmd.test_elevator)
253
+
254
+
255
+ if __name__ == "__main__":
256
+ main(sys.argv[1:])
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enplug/scripts",
3
- "version": "1.11.4-dev.1",
3
+ "version": "1.11.4-dev2",
4
4
  "description": "Enplug scripts",
5
5
  "scripts": {
6
6
  "test": "echo \"Error: no test specified\" && exit 1",