forked from MapComplete/MapComplete
Feature: stabilize saved history, add code to cleanup old preferences, make loading preferences faster (which prevents a 'hang') when just logged in
This commit is contained in:
parent
dc1e582664
commit
c1d3f35d30
10 changed files with 249 additions and 146 deletions
|
|
@ -17,6 +17,7 @@ import ChangeTagAction from "./Actions/ChangeTagAction"
|
|||
import DeleteAction from "./Actions/DeleteAction"
|
||||
import MarkdownUtils from "../../Utils/MarkdownUtils"
|
||||
import FeaturePropertiesStore from "../FeatureSource/Actors/FeaturePropertiesStore"
|
||||
import { Feature, Point } from "geojson"
|
||||
|
||||
/**
|
||||
* Handles all changes made to OSM.
|
||||
|
|
@ -37,7 +38,7 @@ export class Changes {
|
|||
public readonly backend: string
|
||||
public readonly isUploading = new UIEventSource(false)
|
||||
public readonly errors = new UIEventSource<string[]>([], "upload-errors")
|
||||
private readonly historicalUserLocations?: FeatureSource
|
||||
private readonly historicalUserLocations?: FeatureSource<Feature<Point, GeoLocationPointProperties>>
|
||||
private _nextId: number = 0 // Newly assigned ID's are negative
|
||||
private readonly previouslyCreated: OsmObject[] = []
|
||||
private readonly _leftRightSensitive: boolean
|
||||
|
|
@ -53,7 +54,7 @@ export class Changes {
|
|||
osmConnection: OsmConnection
|
||||
reportError?: (error: string) => void
|
||||
featureProperties?: FeaturePropertiesStore
|
||||
historicalUserLocations?: FeatureSource
|
||||
historicalUserLocations?: FeatureSource<Feature<Point, GeoLocationPointProperties>>
|
||||
allElements?: IndexedFeatureSource
|
||||
},
|
||||
leftRightSensitive: boolean = false
|
||||
|
|
@ -66,7 +67,7 @@ export class Changes {
|
|||
if (isNaN(this._nextId) && state.reportError !== undefined) {
|
||||
state.reportError(
|
||||
"Got a NaN as nextID. Pending changes IDs are:" +
|
||||
this.pendingChanges.data?.map((pch) => pch?.id).join(".")
|
||||
this.pendingChanges.data?.map((pch) => pch?.id).join(".")
|
||||
)
|
||||
this._nextId = -100
|
||||
}
|
||||
|
|
@ -90,8 +91,8 @@ export class Changes {
|
|||
return new Changes({
|
||||
osmConnection: new OsmConnection(),
|
||||
featureSwitches: {
|
||||
featureSwitchIsTesting: new ImmutableStore(true),
|
||||
},
|
||||
featureSwitchIsTesting: new ImmutableStore(true)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -178,50 +179,50 @@ export class Changes {
|
|||
[
|
||||
{
|
||||
key: "comment",
|
||||
docs: "The changeset comment. Will be a fixed string, mentioning the theme",
|
||||
docs: "The changeset comment. Will be a fixed string, mentioning the theme"
|
||||
},
|
||||
{
|
||||
key: "theme",
|
||||
docs: "The name of the theme that was used to create this change. ",
|
||||
docs: "The name of the theme that was used to create this change. "
|
||||
},
|
||||
{
|
||||
key: "source",
|
||||
value: "survey",
|
||||
docs: "The contributor had their geolocation enabled while making changes",
|
||||
docs: "The contributor had their geolocation enabled while making changes"
|
||||
},
|
||||
{
|
||||
key: "change_within_{distance}",
|
||||
docs: "If the contributor enabled their geolocation, this will hint how far away they were from the objects they edited. This gives an indication of proximity and if they truly surveyed or were armchair-mapping",
|
||||
docs: "If the contributor enabled their geolocation, this will hint how far away they were from the objects they edited. This gives an indication of proximity and if they truly surveyed or were armchair-mapping"
|
||||
},
|
||||
{
|
||||
key: "change_over_{distance}",
|
||||
docs: "If the contributor enabled their geolocation, this will hint how far away they were from the objects they edited. If they were over 5000m away, the might have been armchair-mapping",
|
||||
docs: "If the contributor enabled their geolocation, this will hint how far away they were from the objects they edited. If they were over 5000m away, the might have been armchair-mapping"
|
||||
},
|
||||
{
|
||||
key: "created_by",
|
||||
value: "MapComplete <version>",
|
||||
docs: "The piece of software used to create this changeset; will always start with MapComplete, followed by the version number",
|
||||
docs: "The piece of software used to create this changeset; will always start with MapComplete, followed by the version number"
|
||||
},
|
||||
{
|
||||
key: "locale",
|
||||
value: "en|nl|de|...",
|
||||
docs: "The code of the language that the contributor used MapComplete in. Hints what language the user speaks.",
|
||||
docs: "The code of the language that the contributor used MapComplete in. Hints what language the user speaks."
|
||||
},
|
||||
{
|
||||
key: "host",
|
||||
value: "https://mapcomplete.org/<theme>",
|
||||
docs: "The URL that the contributor used to make changes. One can see the used instance with this",
|
||||
docs: "The URL that the contributor used to make changes. One can see the used instance with this"
|
||||
},
|
||||
{
|
||||
key: "imagery",
|
||||
docs: "The identifier of the used background layer, this will probably be an identifier from the [editor layer index](https://github.com/osmlab/editor-layer-index)",
|
||||
},
|
||||
docs: "The identifier of the used background layer, this will probably be an identifier from the [editor layer index](https://github.com/osmlab/editor-layer-index)"
|
||||
}
|
||||
],
|
||||
"default"
|
||||
),
|
||||
...addSource(ChangeTagAction.metatags, "ChangeTag"),
|
||||
...addSource(ChangeLocationAction.metatags, "ChangeLocation"),
|
||||
...addSource(DeleteAction.metatags, "DeleteAction"),
|
||||
...addSource(DeleteAction.metatags, "DeleteAction")
|
||||
// TODO
|
||||
/*
|
||||
...DeleteAction.metatags,
|
||||
|
|
@ -243,11 +244,11 @@ export class Changes {
|
|||
docs,
|
||||
specialMotivation
|
||||
? "This might give a reason per modified node or way"
|
||||
: "",
|
||||
: ""
|
||||
].join("\n"),
|
||||
source,
|
||||
source
|
||||
])
|
||||
),
|
||||
)
|
||||
].join("\n\n")
|
||||
}
|
||||
|
||||
|
|
@ -266,7 +267,7 @@ export class Changes {
|
|||
this._changesetHandler._remappings.has("node/" + this._nextId) ||
|
||||
this._changesetHandler._remappings.has("way/" + this._nextId) ||
|
||||
this._changesetHandler._remappings.has("relation/" + this._nextId)
|
||||
)
|
||||
)
|
||||
return this._nextId
|
||||
}
|
||||
|
||||
|
|
@ -333,6 +334,7 @@ export class Changes {
|
|||
this.previouslyCreated
|
||||
)
|
||||
}
|
||||
|
||||
public static createChangesetObjectsStatic(
|
||||
changes: ChangeDescription[],
|
||||
downloadedOsmObjects: OsmObject[],
|
||||
|
|
@ -502,7 +504,7 @@ export class Changes {
|
|||
const result = {
|
||||
newObjects: [],
|
||||
modifiedObjects: [],
|
||||
deletedObjects: [],
|
||||
deletedObjects: []
|
||||
}
|
||||
|
||||
objects.forEach((v, id) => {
|
||||
|
|
@ -559,9 +561,7 @@ export class Changes {
|
|||
const recentLocationPoints = locations
|
||||
.filter((feat) => feat.geometry.type === "Point")
|
||||
.filter((feat) => {
|
||||
const visitTime = new Date(
|
||||
(<GeoLocationPointProperties>(<any>feat.properties)).date
|
||||
)
|
||||
const visitTime = new Date(feat.properties.date)
|
||||
// In seconds
|
||||
const diff = (now.getTime() - visitTime.getTime()) / 1000
|
||||
return diff < Constants.nearbyVisitTime
|
||||
|
|
@ -665,7 +665,7 @@ export class Changes {
|
|||
} else {
|
||||
this._reportError(
|
||||
`Got an orphaned change. The 'creation'-change description for ${c.type}/${c.id} got lost. Permanently dropping this change:` +
|
||||
JSON.stringify(c)
|
||||
JSON.stringify(c)
|
||||
)
|
||||
}
|
||||
return
|
||||
|
|
@ -676,10 +676,10 @@ export class Changes {
|
|||
} else {
|
||||
console.log(
|
||||
"Refusing change about " +
|
||||
c.type +
|
||||
"/" +
|
||||
c.id +
|
||||
" as not in the objects. No internet?"
|
||||
c.type +
|
||||
"/" +
|
||||
c.id +
|
||||
" as not in the objects. No internet?"
|
||||
)
|
||||
refused.push(c)
|
||||
}
|
||||
|
|
@ -694,7 +694,7 @@ export class Changes {
|
|||
*/
|
||||
private async flushSelectChanges(
|
||||
pending: ChangeDescription[],
|
||||
openChangeset: UIEventSource<number>
|
||||
openChangeset: UIEventSource<{ id: number, opened: number }>
|
||||
): Promise<ChangeDescription[]> {
|
||||
const neededIds = Changes.GetNeededIds(pending)
|
||||
/* Download the latest version of the OSM-objects
|
||||
|
|
@ -775,14 +775,14 @@ export class Changes {
|
|||
([key, count]) => ({
|
||||
key: key,
|
||||
value: count,
|
||||
aggregate: true,
|
||||
aggregate: true
|
||||
})
|
||||
)
|
||||
const motivations = pending
|
||||
.filter((descr) => descr.meta.specialMotivation !== undefined)
|
||||
.map((descr) => ({
|
||||
key: descr.meta.changeType + ":" + descr.type + "/" + descr.id,
|
||||
value: descr.meta.specialMotivation,
|
||||
value: descr.meta.specialMotivation
|
||||
}))
|
||||
|
||||
const distances = Utils.NoNull(pending.map((descr) => descr.meta.distanceToObject))
|
||||
|
|
@ -813,7 +813,7 @@ export class Changes {
|
|||
return {
|
||||
key,
|
||||
value: count,
|
||||
aggregate: true,
|
||||
aggregate: true
|
||||
}
|
||||
})
|
||||
)
|
||||
|
|
@ -828,19 +828,20 @@ export class Changes {
|
|||
const metatags: ChangesetTag[] = [
|
||||
{
|
||||
key: "comment",
|
||||
value: comment,
|
||||
value: comment
|
||||
},
|
||||
{
|
||||
key: "theme",
|
||||
value: theme,
|
||||
value: theme
|
||||
},
|
||||
...perType,
|
||||
...motivations,
|
||||
...perBinMessage,
|
||||
...perBinMessage
|
||||
]
|
||||
return metatags
|
||||
}
|
||||
|
||||
|
||||
private async flushChangesAsync(): Promise<void> {
|
||||
try {
|
||||
// At last, we build the changeset and upload
|
||||
|
|
@ -858,16 +859,12 @@ export class Changes {
|
|||
const refusedChanges: ChangeDescription[][] = await Promise.all(
|
||||
Array.from(pendingPerTheme, async ([theme, pendingChanges]) => {
|
||||
try {
|
||||
const openChangeset = UIEventSource.asInt(
|
||||
this.state.osmConnection.GetPreference(
|
||||
"current-open-changeset-" + theme
|
||||
)
|
||||
)
|
||||
const openChangeset = this.state.osmConnection.getCurrentChangesetFor(theme)
|
||||
console.log(
|
||||
"Using current-open-changeset-" +
|
||||
theme +
|
||||
" from the preferences, got " +
|
||||
openChangeset.data
|
||||
theme +
|
||||
" from the preferences, got " +
|
||||
openChangeset.data
|
||||
)
|
||||
|
||||
const refused = await this.flushSelectChanges(pendingChanges, openChangeset)
|
||||
|
|
|
|||
|
|
@ -113,11 +113,11 @@ export class ChangesetHandler {
|
|||
|
||||
private async UploadWithNew(
|
||||
generateChangeXML: (csid: number, remappings: Map<string, string>) => string,
|
||||
openChangeset: UIEventSource<number>,
|
||||
openChangeset: UIEventSource<{ id: number, opened: number }>,
|
||||
extraMetaTags: ChangesetTag[]
|
||||
) {
|
||||
const csId = await this.OpenChangeset(extraMetaTags)
|
||||
openChangeset.setData(csId)
|
||||
openChangeset.setData({ id: csId, opened: new Date().getTime() })
|
||||
const changeset = generateChangeXML(csId, this._remappings)
|
||||
console.log(
|
||||
"Opened a new changeset (openChangeset.data is undefined):",
|
||||
|
|
@ -145,7 +145,7 @@ export class ChangesetHandler {
|
|||
public async UploadChangeset(
|
||||
generateChangeXML: (csid: number, remappings: Map<string, string>) => string,
|
||||
extraMetaTags: ChangesetTag[],
|
||||
openChangeset: UIEventSource<number>
|
||||
openChangeset: UIEventSource<{ id: number, opened: number }>
|
||||
): Promise<void> {
|
||||
if (
|
||||
!extraMetaTags.some((tag) => tag.key === "comment") ||
|
||||
|
|
@ -169,18 +169,21 @@ export class ChangesetHandler {
|
|||
}
|
||||
|
||||
console.log("Trying to reuse changeset", openChangeset.data)
|
||||
if (openChangeset.data) {
|
||||
const now = new Date()
|
||||
const changesetIsUsable = openChangeset.data !== undefined &&
|
||||
(now.getTime() - openChangeset.data.opened < 24 * 60 * 60 * 1000)
|
||||
if (changesetIsUsable) {
|
||||
try {
|
||||
const csId = openChangeset.data
|
||||
const oldChangesetMeta = await this.GetChangesetMeta(csId)
|
||||
const oldChangesetMeta = await this.GetChangesetMeta(csId.id)
|
||||
console.log("Got metadata:", oldChangesetMeta, "isopen", oldChangesetMeta?.open)
|
||||
if (oldChangesetMeta.open) {
|
||||
// We can hopefully reuse the changeset
|
||||
|
||||
try {
|
||||
const rewritings = await this.UploadChange(
|
||||
csId,
|
||||
generateChangeXML(csId, this._remappings)
|
||||
csId.id,
|
||||
generateChangeXML(csId.id, this._remappings)
|
||||
)
|
||||
|
||||
const rewrittenTags = this.RewriteTagsOf(
|
||||
|
|
@ -188,7 +191,7 @@ export class ChangesetHandler {
|
|||
rewritings,
|
||||
oldChangesetMeta
|
||||
)
|
||||
await this.UpdateTags(csId, rewrittenTags)
|
||||
await this.UpdateTags(csId.id, rewrittenTags)
|
||||
return // We are done!
|
||||
} catch (e) {
|
||||
this._reportError(e, "While reusing a changeset " + openChangeset.data)
|
||||
|
|
@ -236,9 +239,9 @@ export class ChangesetHandler {
|
|||
/**
|
||||
* Given an existing changeset with metadata and extraMetaTags to add, will fuse them to a new set of metatags
|
||||
* Does not yet send data
|
||||
* @param extraMetaTags: new changeset tags to add/fuse with this changeset
|
||||
* @param rewriteIds: the mapping of ids
|
||||
* @param oldChangesetMeta: the metadata-object of the already existing changeset
|
||||
* @param extraMetaTags new changeset tags to add/fuse with this changeset
|
||||
* @param rewriteIds the mapping of ids
|
||||
* @param oldChangesetMeta the metadata-object of the already existing changeset
|
||||
*
|
||||
* @public for testing purposes
|
||||
*/
|
||||
|
|
@ -250,7 +253,7 @@ export class ChangesetHandler {
|
|||
id: number
|
||||
uid: number // User ID
|
||||
changes_count: number
|
||||
tags: any
|
||||
tags: Record<string, string>
|
||||
}
|
||||
): ChangesetTag[] {
|
||||
// Note: extraMetaTags is where all the tags are collected into
|
||||
|
|
@ -300,11 +303,11 @@ export class ChangesetHandler {
|
|||
|
||||
/**
|
||||
* Updates the id in the AllElements store, returns the new ID
|
||||
* @param node: the XML-element, e.g. <node old_id="-1" new_id="9650458521" new_version="1"/>
|
||||
* @param node the XML-element, e.g. <node old_id="-1" new_id="9650458521" new_version="1"/>
|
||||
* @param type
|
||||
* @private
|
||||
*/
|
||||
private static parseIdRewrite(node: any, type: string): [string, string] {
|
||||
private static parseIdRewrite(node: any, type: "node" | "way" | "relation"): [string, string] {
|
||||
const oldId = parseInt(node.attributes.old_id.value)
|
||||
if (node.attributes.new_id === undefined) {
|
||||
return [type + "/" + oldId, undefined]
|
||||
|
|
|
|||
|
|
@ -246,11 +246,13 @@ export class OsmConnection {
|
|||
}
|
||||
|
||||
public getPreference<T extends string = string>(
|
||||
key: string,
|
||||
defaultValue: string = undefined,
|
||||
prefix: string = "mapcomplete-"
|
||||
key: string, options?: {
|
||||
defaultValue?: string,
|
||||
prefix?: "mapcomplete-" | string,
|
||||
saveToLocalStorage?: true | boolean
|
||||
}
|
||||
): UIEventSource<T | undefined> {
|
||||
return <UIEventSource<T>>this.preferencesHandler.getPreference(key, defaultValue, prefix)
|
||||
return <UIEventSource<T>>this.preferencesHandler.getPreference(key, options?.defaultValue, options?.prefix ?? "mapcomplete-")
|
||||
}
|
||||
|
||||
public LogOut() {
|
||||
|
|
@ -731,4 +733,24 @@ export class OsmConnection {
|
|||
return { api: "offline", gpx: "offline", database: "online" }
|
||||
}
|
||||
}
|
||||
|
||||
public getCurrentChangesetFor(theme: string) {
|
||||
return UIEventSource.asObject<{ id: number, opened: number }>(
|
||||
this.GetPreference(
|
||||
"current-changeset-" + theme
|
||||
),
|
||||
undefined
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the names of the themes that have an open changeset
|
||||
*/
|
||||
public getAllOpenChangesetsPreferences(): Store<string[]> {
|
||||
const prefix = "current-changeset-"
|
||||
return this.preferencesHandler.allPreferences.map(dict =>
|
||||
Object.keys(dict)
|
||||
.filter(k => k.startsWith(prefix))
|
||||
.map(k => k.substring(prefix.length)))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ export class OsmPreferences {
|
|||
private localStorageInited: Set<string> = new Set()
|
||||
/**
|
||||
* Contains all the keys as returned by the OSM-preferences.
|
||||
* This includes combined preferences, such as: pref, pref:0, pref:1
|
||||
* Used to clean up old preferences
|
||||
*/
|
||||
private seenKeys: string[] = []
|
||||
|
|
@ -59,18 +60,18 @@ export class OsmPreferences {
|
|||
value: string = undefined,
|
||||
deferPing = false
|
||||
): UIEventSource<string> {
|
||||
if (this.preferences[key] !== undefined) {
|
||||
const cached = this.preferences[key]
|
||||
if (cached !== undefined) {
|
||||
if (value !== undefined) {
|
||||
this.preferences[key].set(value)
|
||||
cached.set(value)
|
||||
}
|
||||
return this.preferences[key]
|
||||
return cached
|
||||
}
|
||||
const pref = (this.preferences[key] = new UIEventSource(value, "preference: " + key))
|
||||
if (value) {
|
||||
this.setPreferencesAll(key, value, deferPing)
|
||||
}
|
||||
pref.addCallback((v) => {
|
||||
console.log("Got an update:", key, "--->", v)
|
||||
this.uploadKvSplit(key, v)
|
||||
this.setPreferencesAll(key, v, deferPing)
|
||||
})
|
||||
|
|
@ -82,13 +83,16 @@ export class OsmPreferences {
|
|||
this.seenKeys = Object.keys(prefs)
|
||||
const merged = OsmPreferences.mergeDict(prefs)
|
||||
for (const key in merged) {
|
||||
this.initPreference(key, prefs[key], true)
|
||||
this.initPreference(key, merged[key], true)
|
||||
}
|
||||
this._allPreferences.ping()
|
||||
if (this.osmConnection.isLoggedIn.data) {
|
||||
await this.cleanup()
|
||||
}
|
||||
}
|
||||
|
||||
public getPreference(key: string, defaultValue: string = undefined, prefix?: string) {
|
||||
return this.getPreferenceSeedFromlocal(key, defaultValue, { prefix })
|
||||
public getPreference(key: string, defaultValue: string = undefined, prefix?: string, saveLocally = true) {
|
||||
return this.getPreferenceSeedFromlocal(key, defaultValue, { prefix, saveToLocalStorage: saveLocally })
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -139,23 +143,52 @@ export class OsmPreferences {
|
|||
* OsmPreferences.mergeDict({abc: "123", def: "123", "def:0": "456", "def:1":"789"}) // => {abc: "123", def: "123456789"}
|
||||
*/
|
||||
private static mergeDict(dict: Record<string, string>): Record<string, string> {
|
||||
const newDict = {}
|
||||
|
||||
const allKeys: string[] = Object.keys(dict)
|
||||
const normalKeys = allKeys.filter((k) => !k.match(/[a-z-_0-9A-Z]*:[0-9]+/))
|
||||
for (const normalKey of normalKeys) {
|
||||
if (normalKey.match(/-combined-[0-9]*$/) || normalKey.match(/-combined-length$/)) {
|
||||
const keyParts: Record<string, Record<number, string>> = {}
|
||||
const endsWithNumber = /:[0-9]+$/
|
||||
for (const key of Object.keys(dict)) {
|
||||
if (key.match(/-combined-[0-9]*$/) || key.match(/-combined-length$/)) {
|
||||
continue
|
||||
}
|
||||
const partKeys = OsmPreferences.keysStartingWith(allKeys, normalKey)
|
||||
const parts = partKeys.map((k) => dict[k])
|
||||
newDict[normalKey] = parts.join("")
|
||||
const nr = key.match(endsWithNumber)
|
||||
if (nr) {
|
||||
const i = Number(nr[0].substring(1))
|
||||
const k = key.substring(0, key.length - nr[0].length)
|
||||
let subparts = keyParts[k]
|
||||
if (!subparts) {
|
||||
subparts = {}
|
||||
keyParts[k] = subparts
|
||||
}
|
||||
subparts[i] = dict[key]
|
||||
} else {
|
||||
let subparts = keyParts[key]
|
||||
if (!subparts) {
|
||||
subparts = keyParts[key] = {}
|
||||
}
|
||||
subparts[""] = dict[key]
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
const newDict = {}
|
||||
|
||||
for (const key in keyParts) {
|
||||
const subparts = keyParts[key]
|
||||
let i = 0
|
||||
let v = subparts[""] ?? ""
|
||||
while (subparts[i]) {
|
||||
v += subparts[i]
|
||||
i++
|
||||
}
|
||||
newDict[key] = v
|
||||
}
|
||||
|
||||
return newDict
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulk-downloads all preferences, creates a simple record from all
|
||||
* Bulk-downloads all preferences, creates a simple record from all preferences.
|
||||
* This should still be merged!
|
||||
* @private
|
||||
*/
|
||||
private async getPreferencesDictDirectly(): Promise<Record<string, string>> {
|
||||
|
|
@ -166,7 +199,7 @@ export class OsmPreferences {
|
|||
this.auth.xhr(
|
||||
{
|
||||
method: "GET",
|
||||
path: "/api/0.6/user/preferences",
|
||||
path: "/api/0.6/user/preferences"
|
||||
},
|
||||
(error, value: XMLDocument) => {
|
||||
if (error) {
|
||||
|
|
@ -187,6 +220,9 @@ export class OsmPreferences {
|
|||
})
|
||||
}
|
||||
|
||||
|
||||
private static readonly endsWithNumber = /:[0-9]+$/
|
||||
|
||||
/**
|
||||
* Returns all keys matching `k:[number]`
|
||||
* Split separately for test
|
||||
|
|
@ -198,7 +234,24 @@ export class OsmPreferences {
|
|||
*
|
||||
*/
|
||||
private static keysStartingWith(allKeys: string[], key: string): string[] {
|
||||
const keys = allKeys.filter((k) => k === key || k.match(new RegExp(key + ":[0-9]+")))
|
||||
|
||||
const keys = allKeys.filter((k) => {
|
||||
if (k === key) {
|
||||
return true
|
||||
}
|
||||
if (!k.startsWith(key)) {
|
||||
return false
|
||||
}
|
||||
const match = k.match(OsmPreferences.endsWithNumber)
|
||||
if (!match) {
|
||||
return false
|
||||
}
|
||||
const matchLength = match[0].length
|
||||
if (key.length + matchLength !== k.length) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
keys.sort()
|
||||
return keys
|
||||
}
|
||||
|
|
@ -247,7 +300,7 @@ export class OsmPreferences {
|
|||
{
|
||||
method: "DELETE",
|
||||
path: "/api/0.6/user/preferences/" + encodeURIComponent(k),
|
||||
headers: { "Content-Type": "text/plain" },
|
||||
headers: { "Content-Type": "text/plain" }
|
||||
},
|
||||
(error) => {
|
||||
if (error) {
|
||||
|
|
@ -255,7 +308,6 @@ export class OsmPreferences {
|
|||
reject(error)
|
||||
return
|
||||
}
|
||||
console.debug("Preference ", k, "removed!")
|
||||
resolve()
|
||||
}
|
||||
)
|
||||
|
|
@ -289,33 +341,50 @@ export class OsmPreferences {
|
|||
throw "Preference too long, at most 255 characters are supported"
|
||||
}
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
this.auth.xhr(
|
||||
{
|
||||
method: "PUT",
|
||||
path: "/api/0.6/user/preferences/" + encodeURIComponent(k),
|
||||
headers: { "Content-Type": "text/plain" },
|
||||
content: v,
|
||||
},
|
||||
(error) => {
|
||||
if (error) {
|
||||
console.warn(`Could not set preference "${k}"'`, error)
|
||||
reject(error)
|
||||
return
|
||||
}
|
||||
resolve()
|
||||
}
|
||||
)
|
||||
})
|
||||
try {
|
||||
|
||||
return this.osmConnection.interact("user/preferences/" + encodeURIComponent(k),
|
||||
"PUT", { "Content-Type": "text/plain" }, v)
|
||||
} catch (e) {
|
||||
console.error("Could not upload preference due to", e)
|
||||
}
|
||||
}
|
||||
|
||||
async removeAllWithPrefix(prefix: string) {
|
||||
const keys = this.seenKeys
|
||||
let somethingChanged = false
|
||||
for (const key of keys) {
|
||||
if (!key.startsWith(prefix)) {
|
||||
continue
|
||||
}
|
||||
console.log("Cleaning up preference", key)
|
||||
await this.deleteKeyDirectly(key)
|
||||
somethingChanged = true
|
||||
}
|
||||
return somethingChanged
|
||||
}
|
||||
|
||||
private async cleanup() {
|
||||
const prefixesToClean = ["mapcomplete-mapcomplete-", "mapcomplete-places-history", "unofficial-theme-", "mapcompleteplaces", "mapcompletethemes"] // TODO enable this one once the new system is in prod "mapcomplete-current-open-changeset-"]
|
||||
let somethingChanged = false
|
||||
for (const prefix of prefixesToClean) {
|
||||
const hasChange = await this.removeAllWithPrefix(prefix) // Don't inline - short-circuiting
|
||||
somethingChanged ||= hasChange
|
||||
}
|
||||
if (somethingChanged) {
|
||||
this._allPreferences.ping()
|
||||
}
|
||||
|
||||
const themes = this.osmConnection.getAllOpenChangesetsPreferences()
|
||||
const now = new Date()
|
||||
|
||||
for (const theme of themes.data) {
|
||||
const cs = this.osmConnection.getCurrentChangesetFor(theme)
|
||||
if (now.getTime() - cs.data.opened > 24 * 60 * 60 * 1000) {
|
||||
console.log("Clearing 'open changeset' for theme", theme, "; definitively expired by now")
|
||||
cs.set(undefined)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue