-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.ux
234 lines (227 loc) · 7.87 KB
/
app.ux
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
<script>
/**
* @desc: Application-level configurations and methods are shared by all pages.
*/
import fetch from '@system.fetch'
import configuration from '@system.configuration'
import device from '@system.device'
import cipher from '@system.cipher'
import geolocation from '@system.geolocation'
import prompt from '@system.prompt'
// URL for the Maps
const mapBaseUrl = 'https://geojson.pbest.me'
const markerIconColor = 'red'
// to enable async
const injectRef = Object.getPrototypeOf(global) || global
injectRef.regeneratorRuntime = require('@babel/runtime/regenerator')
/* The main configuration and data resource */
const data = require('./common/json/data.json')
export default {
onCreate() {
// Setup the locale
this.locale = 'en' // by default
this._setupLocale(data.content) // Find the closest match based on the config file
// Initialize the data cached by the app
this.dataCache = {
meta: Object.assign({}, data.meta),
appInfo: Object.assign({}, data.content[this.locale].app),
pois: [].concat(data.content[this.locale].pois),
myCoordinates: { lat: 0, lon: 0}, // user's coordinates
globalMapURL: mapBaseUrl,
userId: cipher.getRandomValues(8)
}
this.channel = new BroadcastChannel('updateChannel')
this._updateDatabase()
.then(() => this.geolocateUser())
.then(() => this.generateMapUrl())
.then(() => {
// Notify all the components that the database is ready
this.channel.postMessage('ready')
console.info(` ✔️ All set!`)
})
},
onDestroy: function () {
this.channel.close()
},
/**
* Obtains data cached by the app.
* @param key
*/
getAppData(key) {
return this.dataCache[key]
},
/**
* Sets the data cached by the app.
* @param key
* @param val
*/
setAppData(key, val) {
this.dataCache[key] = val
},
_updateDatabase() {
return new Promise((resolve, reject) => {
console.info('[2] Fetching external resources with latest configuration...')
fetch.fetch({
url: data.meta.source_url,
method: 'get'
}).then((result) => {
try {
if (result && result.data.code === 200) {
const json = JSON.parse(result.data.data)
if (json.meta.version && (json.meta.version > data.meta.version)) {
// Updates the locale
this._setupLocale(json.content)
this.setAppData('meta', Object.assign({}, json.meta))
this.setAppData('appInfo', Object.assign({}, json.content[this.locale].app))
this.setAppData('pois', [].concat(json.content[this.locale].pois))
console.info(` ✔️ Using (remote) database version v${json.meta.version}`);
} else {
console.info(` ✔️ Using local database version v ${data.meta.version}`);
}
}
} catch(e) {
console.error(` 🐛 I could not fetch the external resource. Reason: ${e}`);
}
console.info(` ✔️ ${this.getAppData('pois').length} POIs loaded from Release v${this.getAppData('meta').version}`)
})
.finally(() => { resolve(this.getAppData('meta').version)} )
})
},
/**
* Finds the closest locale from a JSON object whose keys are the ISO tags to match
* with the given `locale` string.
*/
_closestLocale (locale, available) {
if (typeof locale === 'string' && available[locale]) {
return locale
}
const components = locale.split('-');
while (components.length) {
const potential = components.join('-')
if (available[potential]) {
return potential
}
components.pop()
}
// If none, returns the first available
return Object.keys(available)[0]
},
/**
* Configure the best locale to serve the content, based on the config JSON object
* */
_setupLocale(json) {
const localeObject = configuration.getLocale()
const systemLocale = [localeObject.language, localeObject.countryOrRegion]
.filter(n => !!n)
.join('-')
this.locale = this._closestLocale(systemLocale, json)
console.info(`[1] Selected the closest locale [${this.locale}]`)
},
geolocateUser() {
return new Promise((resolve, reject) => {
const res = this.tryAndGetGeolocation()
resolve(res)
})
},
/**
* Get the permission from the user,
*/
async tryAndGetGeolocation() {
const self = this
let granted = false
console.info('[3] Getting user location...')
const tryGeolocation = () => {
return new Promise((resolve, reject) => {
geolocation.getLocation({
success(res) {
self.setAppData('myCoordinates', { lat: res.latitude, lon: res.longitude })
// If the distance is short (to the first PoI), it enables continous geolocation
console.info(` ✔️ Got user\'s coordinates [${res.latitude},${res.longitude}]`)
resolve(true)
},
fail(res, code) {
console.error(` 🐛 Error getting the location (code ${code})`)
resolve(false)
},
})
})
}
const showDialog = () => {
return new Promise((resolve, reject) => {
prompt.showDialog({
title: self.i18n.$t('message.app.geolocation.request'),
message: self.i18n.$t('message.app.geolocation.description'),
buttons: [
{
text: self.i18n.$t('message.app.geolocation.no'),
color: '#B11623'
},
{
text: self.i18n.$t('message.app.geolocation.yes'),
color: '#88C100'
},
],
success: function (res) {
if (res.index === 1) {
console.info({ message: ' The user wants to repeat the process' })
} else if (res.index === 0) {
console.info(" 🚫 User doesn't grant geolocation permissions");
self.exit()
}
},
cancel: function(){
console.info(" 🚫 User cancelled the geolocation permission dialog");
},
complete: function() {
resolve(false)
},
})
})
}
while (!granted) {
// Infinite loop until geolocation is granted
granted = await tryGeolocation()
if (!granted) {
granted = await showDialog()
}
}
},
generateMapUrl() {
console.info('[5] Generating global map URL...')
const url = `${mapBaseUrl}?icon=${markerIconColor}&locale=${this.locale}&url=${encodeURIComponent(data.meta.source_url)}`
this.setAppData('globalMapURL', url)
return url
},
generateIndidivualMapUrl(item) {
console.info(`Generating individual map URL for ${item.id}...`)
const geojson = {
type: "Feature",
properties: {
popupContent: item.name
},
geometry: {
type: "Point",
coordinates: [ parseFloat(item.lon), parseFloat(item.lat) ]
}
}
const url = `${mapBaseUrl}?icon=${markerIconColor}`+
`&locale=${this.locale}&geojson=${encodeURIComponent(JSON.stringify(geojson))}`
return url
},
track(action, page) {
const matomoBaseUrl = this.dataCache.meta.matomo_base_url
if (!matomoBaseUrl) { return false }
const url = `http://${this.manifest.package}/v${this.manifest.versionCode}/${page}`
const random = String(Math.floor(Math.random()*1000)).padStart(4, '0');
let matomoUrl = matomoBaseUrl + `&rand=${random}&action_name=${action}&url=${url}`
matomoUrl += `&_id=${this.dataCache.userId}`
device.getInfo()
.then((res) => {
matomoUrl += `&res=${res.data.screenWidth}x${res.data.screenHeight}`
matomoUrl += `&lang=${res.data.language}-${res.data.region}`
matomoUrl += `&ua=${res.data.model}-${res.data.platformVersionCode}`
fetch.fetch({url: matomoUrl})
})
}
}
</script>