generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFeatureServiceConnection.ts
221 lines (186 loc) · 6.6 KB
/
FeatureServiceConnection.ts
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
import esriConfig from "@arcgis/core/config";
import PortalItemResource from "@arcgis/core/portal/PortalItemResource";
import { ArcGISInObsidianSettings } from "./main";
import { readFile } from "fs";
import { MetadataCache, Vault, Workspace, App, TFile } from "obsidian";
import FeatureServiceSyncSetting from "FeatureServiceSyncSetting";
import {
addressToLocations,
locationToAddress,
} from "@arcgis/core/rest/locator";
import FeatureLayer from "@arcgis/core/layers/FeatureLayer";
import Graphic from "@arcgis/core/Graphic";
import { Point } from "@arcgis/core/geometry";
import { parseYaml, stringifyYaml } from "obsidian";
export class FeatureServiceConnection {
settings: ArcGISInObsidianSettings;
app: App;
connections?: Map<string, FeatureLayer>;
constructor(settings: ArcGISInObsidianSettings, app: App) {
this.settings = settings;
this.app = app;
this.connections = new Map();
}
establishConnections() {
for (var config of this.settings.featureServiceSync) {
if (config.featureServiceUrl) {
let featureLayer = new FeatureLayer({
url: config.featureServiceUrl,
});
// TODO = warn if layer doesn't support editing
this.connections.set(config.featureServiceUrl, featureLayer);
}
}
}
getFieldMapAsObj(
config: FeatureServiceSyncSetting
): { obsYaml: string; arcField: string }[] | undefined {
if (!config.fieldMap || config.fieldMap === "") {
return undefined;
}
let maps = config.fieldMap.split(",");
return maps.map((val, idx, arr) => {
let [obs, arcField] = val.split(":", 2);
return { obsYaml: obs, arcField: arcField };
});
}
async syncIndividaulFileForConfig(
config: FeatureServiceSyncSetting,
file: TFile,
location: Point
) {
// prep
let featureLayer = this.connections.get(config.featureServiceUrl);
let metadata = this.app.metadataCache.getFileCache(file);
let obsidianUrl = `obsidian://open?vault=${file.vault.getName()}&file=${encodeURIComponent(file.path)}`;
let fieldstoSync = this.getFieldMapAsObj(config);
var edits: __esri.FeatureLayerApplyEditsEdits = {
addFeatures: [],
updateFeatures: [],
};
var featureGraphic: Graphic
// sync feature if indicated
// TODO = refactor to share code between add and update
if (metadata.frontmatter["OBJECTID"]) {
featureGraphic = (
await featureLayer.queryFeatures({
outFields: ["*"],
where: `OBJECTID = ${metadata.frontmatter["OBJECTID"]}`,
})
).features.first();
}
if (featureGraphic){
edits.updateFeatures.push(featureGraphic);
}
else {
featureGraphic = new Graphic();
featureGraphic.attributes = {}
edits.addFeatures.push(featureGraphic);
}
featureGraphic.attributes[config.titleField ?? "TITLE"] = file.basename;
featureGraphic.attributes["OBSIDIAN_LINK"] = obsidianUrl;
// apply field map values
if (fieldstoSync) {
fieldstoSync.map((fieldPair, idx) => {
if (metadata.frontmatter[fieldPair.obsYaml]) {
featureGraphic.attributes[fieldPair.arcField] =
metadata.frontmatter[fieldPair.obsYaml];
}
});
}
featureGraphic.geometry = new Point({ x: location.x, y: location.y });
// Apply edits
let editsResults = await featureLayer.applyEdits(edits);
if (editsResults.addFeatureResults) {
let addedFeature = editsResults.addFeatureResults.first();
}
let objectId = featureGraphic.getObjectId() ?? editsResults.addFeatureResults.first().objectId;
await this.rewriteFileYAML(file, featureGraphic.geometry as Point,featureGraphic, objectId.toString());
}
async rewriteFileYAML(file:TFile, newLocation?:Point, feature?:Graphic, objectId?:string){
// Read existing content
let originalContents = await this.app.vault.read(file);
// parse existing frontmatter
if (!originalContents.startsWith("---")){
return;
}
// splice out frontmatter
let [_, yamlFrontmatter, restOfFile] = originalContents.split("---", 3)
let frontMatter = parseYaml(yamlFrontmatter);
// update frontmatter
if (feature){
frontMatter['OBJECTID'] = objectId;
}
if (newLocation){
frontMatter['geoXYCached'] = `x:${newLocation.x},y:${newLocation.y}`
}
// rewrite file with new frontmatter
let newFileContents = `---\n${stringifyYaml(frontMatter).trimEnd()}\n---\n${restOfFile.trimStart()}`
await this.app.vault.modify(file, newFileContents)
}
async syncOneConfiguration(config: FeatureServiceSyncSetting) {
// scan vault for matching documents
let allFiles = this.app.vault.getFiles();
let regexTest = new RegExp(config.noteIncludePattern ?? "*");
let matchingFiles = allFiles.filter((file, index) => {
if (file.extension != "md") return false;
return regexTest.test(file.basename);
});
// extract metadata from notes
let geoFiles = (
await Promise.all(
matchingFiles.map(async (file, idx, arr) => {
let metadata = this.app.metadataCache.getFileCache(file);
if (!metadata.frontmatter) {
return null;
}
let geotag = metadata.frontmatter["geo"];
if (!geotag) {
return null;
}
let cachedValue = metadata.frontmatter['geoXYCached'];
if (cachedValue){
let [xpart,ypart] = cachedValue.split(',', 2)
let newX = xpart.trim().split(':', 2)[1]
let newY = ypart.trim().split(':', 2)[1]
let cachedPoint = new Point();
cachedPoint.x = parseFloat(newX);
cachedPoint.y = parseFloat(newY);
return {file:file, location: cachedPoint}
}
if (typeof geotag == "string") {
// process single location
let location = await addressToLocations(
"https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer",
{
address: { SingleLine: geotag },
}
);
let point = location.first().location;
return { file: file, location: point };
}
// Todo: support polypoints
})
)
).filter((fileGeoPair, idx) => fileGeoPair != null);
//console.dir(geoFiles);
await Promise.all(
geoFiles.map((fileGeoPair, idx, arr) => {
this.syncIndividaulFileForConfig(
config,
fileGeoPair.file,
fileGeoPair.location
);
})
);
}
syncAll() {
// establish connection
this.establishConnections();
// read sync configurations
for (var config of this.settings.featureServiceSync) {
this.syncOneConfiguration(config);
}
// sync each configuration
}
}