-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutil.js
107 lines (95 loc) · 2.56 KB
/
util.js
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
export function getPath(serverUrl, userPublicKey, filename, mode) {
if (isAbsoluteUrl(filename)) {
return filename
}
if (mode !== 'm') {
return `${serverUrl}/${filename}`
} else {
return `${serverUrl}/${userPublicKey}/${filename}`
}
}
export function getMimeType(filename) {
const extension = filename.split('.').pop().toLowerCase()
switch (extension) {
case 'txt':
return 'text/plain'
case 'ttl':
return 'text/turtle'
case 'json':
return 'application/json'
case 'jsonld':
return 'application/ld+json'
case 'md':
return 'text/markdown' // Added Markdown support
default:
return 'text/plain'
}
}
export function isAbsoluteUrl(url) {
try {
new URL(url)
return true
} catch (e) {
return false
}
}
export function getQueryStringValue(key) {
const queryString = window.location.search.substring(1)
const queryParams = new URLSearchParams(queryString)
return queryParams.get(key)
}
export async function generateAuthorizationHeader(path) {
const event = {
kind: 27235,
created_at: Math.floor(Date.now() / 1000),
tags: [['u', path]],
content: ''
}
const signedEvent = await window.nostr.signEvent(event)
console.log(signedEvent)
console.log(JSON.stringify(signedEvent))
console.log(btoa(JSON.stringify(signedEvent)))
return `Nostr ${btoa(JSON.stringify(signedEvent))}`
}
export async function loadFile(serverUrl, userPublicKey, filename, mode) {
const path = getPath(serverUrl, userPublicKey, filename, mode)
try {
const response = await fetch(path, {
headers: {
Authorization: `Nostr ${userPublicKey}`
}
})
if (response.status === 200) {
return await response.text()
} else {
throw new Error('Failed to load file content')
}
} catch (error) {
console.error(error)
}
}
export async function saveFile(serverUrl, userPublicKey, filename, mode, fileContent) {
const path = getPath(serverUrl, userPublicKey, filename, mode)
const contentType = getMimeType(filename)
const authorization = await generateAuthorizationHeader(path)
try {
const response = await fetch(path, {
method: 'PUT',
body: fileContent,
headers: {
Authorization: authorization,
'Content-Type': contentType,
'Content-Length': fileContent.length
}
})
if (response.status === 201) {
console.log('File saved successfully')
return true
} else {
throw new Error('Failed to save file')
}
} catch (error) {
console.error(error)
return false
}
}