Skip to content

Commit

Permalink
feat: create task with cookie (#24)
Browse files Browse the repository at this point in the history
  • Loading branch information
monkeyWie committed Apr 20, 2024
1 parent 4430079 commit 0cdcdf8
Show file tree
Hide file tree
Showing 11 changed files with 1,675 additions and 1,018 deletions.
6 changes: 4 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,16 @@ jobs:
with:
version: latest
run_install: true
- name: Use Node.js 16.x
- name: Use Node.js
uses: actions/setup-node@v3.4.1
with:
node-version: 16.x
node-version: 18.x
cache: "pnpm"
- name: Build the extension
run: |
pnpm build --target=chrome-mv3 --zip
rm -rf pacakge.json
mv package.firefox.json package.json
pnpm build --target=firefox-mv2 --zip
- uses: monkeyWie/get-latest-release@v2.1
id: get-release
Expand Down
6 changes: 6 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit"
}
}
166 changes: 123 additions & 43 deletions background/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import sniffer from "url:~/pages/sniffer.tsx"
import contentDisposition from "content-disposition"
import path from "path"

import { Storage } from "@plasmohq/storage"

import path from "path"

import { STORAGE_SERVER_STATUS, STORAGE_SERVERS } from "~constants"
import { getSelectedServer } from "~util"
import {
STORAGE_SERVER_SELECTED,
STORAGE_SERVER_STATUS,
STORAGE_SERVERS
} from "~constants"
import { getSelectedServer } from "~service/server"

export { }

Expand All @@ -17,7 +20,6 @@ export async function checkServer(server: Server): Promise<CheckResult> {
resolve("network_error")
}, 5000)
try {
console.log(server.url)
const resp = await fetch(`${server.url}/api/v1/tasks/0`, {
headers: {
"X-Api-Token": server.token
Expand All @@ -34,7 +36,6 @@ export async function checkServer(server: Server): Promise<CheckResult> {
resolve("network_error")
}
})

}

/* function initContextMenus() {
Expand All @@ -53,57 +54,136 @@ export async function checkServer(server: Server): Promise<CheckResult> {
})
})
} */
const isFirefox = process.env.PLASMO_BROWSER === "firefox"
const checkIntervalTime = 1500
const storage = new Storage()
let capture = false

; (async function () {
// initContextMenus()

async function updateCapture() {
// Sleep for a while to wait for the server check
await new Promise((resolve) => setTimeout(resolve, checkIntervalTime + 1))
capture = !!(await getSelectedServer())
}
updateCapture()
storage.watch({
[STORAGE_SERVER_SELECTED]: updateCapture
})

; (async function () {
// initContextMenus()

const storage = new Storage()

async function checkAllServers() {
const servers = await storage.get<Server[]>(STORAGE_SERVERS)
if (!servers || servers.length === 0) return
await Promise.all(
servers.map(async (server) => {
const status = await checkServer(server)
const prev = await storage.get<Record<string, boolean>>(
STORAGE_SERVER_STATUS
)
await storage.set(STORAGE_SERVER_STATUS, {
...prev,
[server.url]: status === "success"
async function checkAllServers() {
const servers = await storage.get<Server[]>(STORAGE_SERVERS)
if (!servers || servers.length === 0) return
await Promise.all(
servers.map(async (server) => {
const status = await checkServer(server)
const prev = await storage.get<Record<string, boolean>>(
STORAGE_SERVER_STATUS
)
await storage.set(STORAGE_SERVER_STATUS, {
...prev,
[server.url]: status === "success"
})
})
})
)
}
checkAllServers()
setInterval(checkAllServers, 3000)
})()
)
}
checkAllServers()
setInterval(checkAllServers, checkIntervalTime)
})()

// chrome.downloads.onDeterminingFilename only available in Chrome
const downloadEvent = chrome.downloads.onDeterminingFilename || chrome.downloads.onCreated
const downloadEvent =
chrome.downloads.onDeterminingFilename || chrome.downloads.onCreated

downloadEvent.addListener(async function (item) {
if (!capture) {
return
}
const finalUrl = item.finalUrl || item.url
if (finalUrl.startsWith("blob:") || finalUrl.startsWith("data:")) return

const server = await getSelectedServer()
if (!server) return
if (finalUrl.startsWith("blob:") || finalUrl.startsWith("data:")) {
return
}

await chrome.downloads.cancel(item.id)
if (item.state === "complete") {
await chrome.downloads.removeFile(item.id)
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message)
}
if (isFirefox) {
await chrome.downloads.erase({ id: item.id })
}

const asset = <Asset>{
downloadConfirm({
filename: path.basename(item.filename.replaceAll("\\", "/")),
filesize: item.fileSize,
finalUrl
}
finalUrl,
referer: item.referrer,
cookieStoreId: (item as any).cookieStoreId
})
})

function checkContentDisposition(
res: chrome.webRequest.WebResponseHeadersDetails
): string {
return res.responseHeaders.find(
(header) =>
header.name.toLowerCase() === "content-disposition" &&
header.value.toLowerCase().startsWith("attachment")
)?.value
}

if (isFirefox) {
chrome.webRequest.onHeadersReceived.addListener(
function (res) {
if (res.statusCode !== 200) {
return
}
const contentDispositionValue = checkContentDisposition(res)
if (!contentDispositionValue) {
return
}

let filename = ""
// Parse filename from content-disposition
if (contentDispositionValue) {
const parse = contentDisposition.parse(contentDispositionValue)
filename = parse.parameters.filename
} else {
filename = path.basename(res.url)
}

let filesize = 0
const contentLength = res.responseHeaders.find(
(header) => header.name.toLowerCase() === "content-length"
)?.value
if (contentLength) {
filesize = parseInt(contentLength)
}

downloadConfirm({
filename,
filesize,
finalUrl: res.url,
referer: (res as any).originUrl,
cookieStoreId: (res as any).cookieStoreId
})
return { cancel: true }
},
{ urls: ["<all_urls>"], types: ["main_frame", "sub_frame"] },
["blocking", "responseHeaders"]
)
}

function downloadConfirm(asset: Asset) {
chrome.windows.getCurrent((currentWindow) => {
const width = 480
const height = 600
const left = Math.round((currentWindow.width - width) * 0.5 + currentWindow.left)
const top = Math.round((currentWindow.height - height) * 0.5 + currentWindow.top)
const left = Math.round(
(currentWindow.width - width) * 0.5 + currentWindow.left
)
const top = Math.round(
(currentWindow.height - height) * 0.5 + currentWindow.top
)
chrome.windows.create({
url: `tabs/create.html?asset=${encodeURIComponent(
JSON.stringify(asset)
Expand All @@ -115,4 +195,4 @@ downloadEvent.addListener(async function (item) {
top
})
})
})
}
2 changes: 1 addition & 1 deletion background/messages/api/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { CreateTaskWithRequest } from "@gopeed/types"

import type { PlasmoMessaging } from "@plasmohq/messaging"

import { getSelectedServer } from "~util"
import { getSelectedServer } from "~service/server"

const handler: PlasmoMessaging.MessageHandler<
CreateTaskWithRequest,
Expand Down
62 changes: 62 additions & 0 deletions package.firefox.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{
"name": "gopeed-browser-extension",
"displayName": "Gopeed",
"version": "0.0.3",
"description": "Gopeed browser extension",
"homepage": "https://gopeed.com",
"author": "Levi",
"scripts": {
"dev": "plasmo dev",
"dev:firefox": "plasmo dev --target=firefox-mv2",
"build": "plasmo build --zip",
"build:firefox": "plasmo build --target=firefox-mv2 --zip"
},
"dependencies": {
"@emotion/cache": "11.11.0",
"@emotion/react": "11.11.1",
"@emotion/styled": "11.11.0",
"@gopeed/rest": "^1.3.7",
"@mui/icons-material": "^5.15.10",
"@mui/lab": "5.0.0-alpha.165",
"@mui/material": "5.15.10",
"@mui/x-date-pickers": "^6.19.4",
"@plasmohq/messaging": "^0.6.1",
"@plasmohq/storage": "^1.9.0",
"content-disposition": "^0.5.4",
"plasmo": "0.84.2",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-file-icon": "^1.4.0",
"react-hook-form": "^7.50.1",
"react-hook-form-mui": "7.0.0-beta.0"
},
"devDependencies": {
"@babel/core": "7.23.3",
"@gopeed/types": "^1.3.7",
"@ianvs/prettier-plugin-sort-imports": "4.1.1",
"@types/chrome": "0.0.251",
"@types/content-disposition": "^0.5.8",
"@types/node": "20.9.0",
"@types/react": "18.2.37",
"@types/react-dom": "18.2.15",
"prettier": "3.0.3",
"typescript": "5.2.2"
},
"manifest": {
"host_permissions": [
"http://*/*",
"https://*/*"
],
"permissions": [
"downloads",
"cookies",
"webRequest",
"webRequestBlocking"
],
"browser_specific_settings": {
"gecko": {
"id": "{c5d69a8f-2ed0-46a7-afa4-b3a00dc58088}"
}
}
}
}
14 changes: 11 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
"author": "Levi",
"scripts": {
"dev": "plasmo dev",
"build": "plasmo build",
"package": "plasmo package"
"dev:firefox": "plasmo dev --target=firefox-mv2",
"build": "plasmo build --zip",
"build:firefox": "plasmo build --target=firefox-mv2 --zip"
},
"dependencies": {
"@emotion/cache": "11.11.0",
Expand All @@ -21,6 +22,7 @@
"@mui/x-date-pickers": "^6.19.4",
"@plasmohq/messaging": "^0.6.1",
"@plasmohq/storage": "^1.9.0",
"content-disposition": "^0.5.4",
"plasmo": "0.84.2",
"react": "18.2.0",
"react-dom": "18.2.0",
Expand All @@ -33,15 +35,21 @@
"@gopeed/types": "^1.3.7",
"@ianvs/prettier-plugin-sort-imports": "4.1.1",
"@types/chrome": "0.0.251",
"@types/content-disposition": "^0.5.8",
"@types/node": "20.9.0",
"@types/react": "18.2.37",
"@types/react-dom": "18.2.15",
"prettier": "3.0.3",
"typescript": "5.2.2"
},
"manifest": {
"host_permissions": [
"http://*/*",
"https://*/*"
],
"permissions": [
"downloads"
"downloads",
"cookies"
],
"browser_specific_settings": {
"gecko": {
Expand Down
Loading

0 comments on commit 0cdcdf8

Please sign in to comment.