-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
95 lines (77 loc) · 2.92 KB
/
background.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
function convertSecondsToMinutes(seconds) {
// Parse the input to ensure it's a float
let floatSeconds = parseFloat(seconds);
// Convert seconds to minutes
let minutes = floatSeconds / 60;
// Round up to the nearest integer
let roundedMinutes = Math.ceil(minutes);
return roundedMinutes;
}
function addMinutesToDate(date, minutes) {
// Create a new Date object from the existing one to avoid mutating the original date
let newDate = new Date(date.getTime());
// Add the minutes
newDate.setMinutes(newDate.getMinutes() + minutes);
return newDate;
}
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: 'addToTodoist',
title: 'Add YouTube video to Todoist',
contexts: ['page']
});
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === 'addToTodoist') {
chrome.scripting.executeScript(
{
target: { tabId: tab.id },
function: getVideoDetails
},
(results) => {
const videoDetails = results[0].result;
chrome.storage.sync.get('todoistApiToken', (data) => {
if (data.todoistApiToken) {
addToTodoist(videoDetails, data.todoistApiToken);
} else {
console.error('Todoist API token not set.');
}
});
}
);
}
});
function addToTodoist(videoDetails, apiToken) {
let minutes = convertSecondsToMinutes(videoDetails.duration);
let due = addMinutesToDate(new Date(), minutes);
fetch('https://api.todoist.com/rest/v2/tasks', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
content: videoDetails.title,
due_datetime: due.toISOString(),
duration: minutes,
duration_unit: "minute",
description: videoDetails.description
})
}).then(response => response.json())
.then(data => console.log('Task added:', data))
.catch(error => console.error('Error:', error));
}
function getVideoDetails() {
const videoTitle = document.querySelector('meta[name="title"]').content;
const videoURL = document.querySelector('link[rel="shortlinkUrl"]').href;
const videoDesc = document.querySelector('meta[property="og:description"]').content;
const videoLength = document.querySelector('.ytp-time-duration').textContent;
const duration = videoLength.match(/\d+:\d+/)[0]; // Extract duration
const durationInSeconds = parseInt(duration.split(':')[0]) * 60 + parseInt(duration.split(':')[1]);
let description = videoURL + "\n" + videoDesc;
return {
title: videoTitle,
duration: durationInSeconds,
description: description
};
}