Skip to content

Commit

Permalink
delete remote cards
Browse files Browse the repository at this point in the history
  • Loading branch information
rsenna committed Apr 4, 2024
1 parent dcb87db commit 1546195
Show file tree
Hide file tree
Showing 2 changed files with 147 additions and 30 deletions.
175 changes: 146 additions & 29 deletions src/commands.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import {SupernotesPluginSettings, SyncOptions} from "./settings";
import {createNoteForEntry, getAllNotesInFolder, getNoteInFolder} from "./note";
import {App, moment, normalizePath, Notice, requestUrl, RequestUrlParam, RequestUrlResponse, TFile} from "obsidian";
import {formatDate, getEnumValues, isObject, isValidDateString} from "./utils";
import {SupernotesCard, SupernotesStatus} from "./types";
import {DeleteOptions, SupernotesPluginSettings, SyncOptions} from "./settings"
import {createNoteForEntry, getAllNotesInFolder, getNoteInFolder} from "./note"
import {App, moment, normalizePath, Notice, requestUrl, RequestUrlParam, RequestUrlResponse, TFile} from "obsidian"
import {formatDate, getEnumValues, isObject, isValidDateString} from "./utils"
import {SupernotesCard, SupernotesStatus} from "./types"

const getRequestUrlParamsBody = (includeJunk: boolean) => {
const getDownloadRequestUrlParamsBody = (includeJunk: boolean): string => {
const query: string[] = []

query.push('{')
Expand All @@ -20,6 +20,26 @@ const getRequestUrlParamsBody = (includeJunk: boolean) => {
return query.join('')
}

const getDeleteRequestUrlParamsBody = (cardIds: string[]): string => {
const query: string[] = []

query.push('[')
query.push(cardIds.map(it => `"${it}"`).join(','))
query.push(']')

return query.join('')
}

const getDisableRequestUrlParamsBody = (cardIds: string[]): string => {
const query: string[] = []

query.push('{')
query.push(cardIds.map(it => `"${it}": {"membership": {"status": -2}}`).join(',\n'))
query.push('}')

return query.join('')
}

export const downloadAll = async (
app: App,
settings: SupernotesPluginSettings,
Expand All @@ -33,14 +53,39 @@ export const downloadAll = async (
const snDataHtml = 'sn-data-html';
const ignoredKeys = [snDataMarkup, snDataHtml]

const requestUrlParams: RequestUrlParam = {
const downloadRequestUrlParams: RequestUrlParam = {
url: 'https://api.supernotes.app/v1/cards/get/select',
method: 'POST',
headers: {
'Api-Key': settings.basic.apiKey,
'Content-Type': 'application/json'
},
body: getRequestUrlParamsBody(settings.junk.enabled)
body: getDownloadRequestUrlParamsBody(settings.junk.enabled)
}

const deleteRequestUrlParams = (cardIds: string[]): RequestUrlParam => {
return {
url: 'https://api.supernotes.app/v1/cards/delete',
method: 'POST',
headers: {
'Api-Key': settings.basic.apiKey,
'Content-Type': 'application/json'
},
body: getDeleteRequestUrlParamsBody(cardIds)
}
}

const disableRequestUrlParams = (cardIds: string[]): RequestUrlParam => {
return {
url: 'https://api.supernotes.app/v1/cards',
method: 'PATCH',
headers: {
'Api-Key': settings.basic.apiKey,
'Content-Type': 'application/json',
'accept': 'application/json'
},
body: getDisableRequestUrlParamsBody(cardIds)
}
}

const getExistingNoteMtime = async (file: TFile) => {
Expand Down Expand Up @@ -101,60 +146,132 @@ export const downloadAll = async (
return [download, existingNoteFile]
}

let entryCount = 0
let downloadEntryCount = 0
let deletedCount = 0

try {
const response: RequestUrlResponse = await requestUrl(requestUrlParams)
const downloadResponse: RequestUrlResponse = await requestUrl(downloadRequestUrlParams)

if (response.status != 200) {
new Notice(`Error (${response.status}): ${response.text}.`)
if (downloadResponse.status != 200) {
console.error(`Error (${downloadResponse.status}): ${downloadResponse.text}.`)
new Notice('Error downloading Supernotes cards. See development console for details.')
return;
}

console.debug('response.status', response.status)
const downloadResponseJson = downloadResponse.json
const downloadResponseCards: SupernotesCard[] = Object.values(downloadResponseJson)

const responseJson = response.json
const responseCards: SupernotesCard[] = Object.values(responseJson)
downloadEntryCount = downloadResponseCards.length

console.debug('responseCards.length', responseCards.length)
entryCount = responseCards.length
const downloadedCards: string[] = []

for (const responseEntry of responseCards) {
const [download, existingNoteFile] = await shouldDownloadFile(responseEntry)
for (const downloadResponseEntry of downloadResponseCards) {
const [download, existingNoteFile] = await shouldDownloadFile(downloadResponseEntry)

// Create note from supernotes card:
if (download) {
const noteFile = existingNoteFile || await createNoteForEntry(app, settings, responseEntry)
const noteFile = existingNoteFile || await createNoteForEntry(app, settings, downloadResponseEntry)

await app.fileManager.processFrontMatter(noteFile, frontmatter => {
setFrontmatter(basePrefix, responseEntry, frontmatter)
setFrontmatter(basePrefix, downloadResponseEntry, frontmatter)

frontmatter['created'] = formatDate(responseEntry.data.created_when)
frontmatter['updated'] = formatDate(responseEntry.data.modified_when)
frontmatter['created'] = formatDate(downloadResponseEntry.data.created_when)
frontmatter['updated'] = formatDate(downloadResponseEntry.data.modified_when)
})

await app.vault.append(noteFile, responseEntry.data.html)
await app.vault.append(noteFile, downloadResponseEntry.data.html)

downloadedCards.push(downloadResponseEntry.data.id)
}
}

const deleteSupernotesCards = async (cardIds: string[]) => {
const deleteRequest = deleteRequestUrlParams(cardIds)
const deleteResponse: RequestUrlResponse = await requestUrl(deleteRequest)

if (deleteResponse.status != 207) {
console.error(`Error (${deleteResponse.status}): ${deleteResponse.text}.`)
new Notice('Error deleting remote Supernotes cards. See development console for details.')
return;
}

deletedCount = downloadedCards.length
}

const disableSupernotesCards = async (cardIds: string[]) => {
const disableRequest = disableRequestUrlParams(cardIds)
const disableResponse: RequestUrlResponse = await requestUrl(disableRequest)

if (disableResponse.status != 207) {
console.error(`Error (${disableResponse.status}): ${disableResponse.text}.`)
new Notice('Error disabling remote Supernotes cards. See development console for details.')
return;
}

deletedCount = downloadedCards.length
}

// Delete supernotes cards:
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const deleteDownloadedSupernotesCards = async () => {
if (settings.syncRules.delete === DeleteOptions.Remote && downloadedCards.length > 0) {
await deleteSupernotesCards(downloadedCards)
}
}

// Delete supernotes cards, one by one:
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const deleteDownloadedSupernotesCards1By1 = async () => {
if (settings.syncRules.delete === DeleteOptions.Remote) {
for (const cardId of downloadedCards) {
await deleteSupernotesCards([cardId])
}
}
}

// Delete supernotes cards, one by one:
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const disableDownloadedSupernotesCards = async () => {
if (settings.syncRules.delete === DeleteOptions.Remote) {
await disableSupernotesCards(downloadedCards)
}
}

// Delete supernotes cards, one by one:
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const disableDownloadedSupernotesCards1By1 = async () => {
if (settings.syncRules.delete === DeleteOptions.Remote) {
for (const cardId of downloadedCards) {
await disableSupernotesCards([cardId])
}
}
}

await disableDownloadedSupernotesCards()
await deleteDownloadedSupernotesCards()

} catch (ex) {
console.error('ERROR ' + ex)
new Notice(ex)
new Notice('An unknown error happened during download of Supernotes cards. See development console for details.')
} finally {
statusBarEl.setText(`Download complete (total = ${entryCount} notes downloaded).`)
statusBarEl.setText(`Download complete. ${downloadEntryCount} card(s) downloaded, ${deletedCount} card(s) deleted from Supernotes.`)
}
}

export const uploadAll = async (
app: App,
settings: SupernotesPluginSettings,
statusBarItem: HTMLElement,
ignore: number[]
_statusBarItem: HTMLElement,
_ignore: number[]
) => {
const folderPath = normalizePath(settings.basic.folder)
for (const file of getAllNotesInFolder(app, folderPath)) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
for (const _file of getAllNotesInFolder(app, folderPath)) {
// TODO
}
}

// TODO: synchronizeAll is currently not being used
export const synchronizeAll = async (
app: App,
settings: SupernotesPluginSettings,
Expand Down
2 changes: 1 addition & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export default class SupernotesPlugin extends Plugin implements HasSettings {
}

onunload() {

// TODO: delete if unused
}

async loadSettings(): Promise<SupernotesPluginSettings> {
Expand Down

0 comments on commit 1546195

Please sign in to comment.