Commit 89279b51 by ramdayalmunda

added custom fetch query to send request from background.js

parent a5ffea72
...@@ -8,32 +8,128 @@ var getUserDetails = null ...@@ -8,32 +8,128 @@ var getUserDetails = null
var loggedIn = false; var loggedIn = false;
var userDetails = {} var userDetails = {}
function sendReq(url=origin, method='GET', body={}, headers={}){
if (url.slice(0,4)!='http') url = origin += `/api${url[0]=='/'?'':'/'}${url}` function createAPI(origin){
return new Promise( (res, rej)=>{ var baseURL = origin
let bodyObj = { ...body } function objectToQueryString(obj) {
let headerObj = { const keyValuePairs = [];
'Content-Type': 'application/json',
...headers for (const key in obj) {
} if (obj.hasOwnProperty(key)) {
fetch( url,{ const value = obj[key];
method: method, if (value !== undefined) {
body: JSON.stringify({ ...bodyObj }), keyValuePairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
headers: headerObj, }
} ).then( async (data)=>{
if ( headerObj['Content-Type']=='application/json' ){
res( await data.json() )
}else{
res(data)
} }
} ).catch(err=>{ }
console.log('fetch err', err)
rej(err) return keyValuePairs.join('&');
}) }
} ) return {
post(url, body={}, headers={}) {
if (url.slice(0, 4) != 'http') url = (baseURL + `/api${url[0] == '/' ? '' : '/'}${url}`)
return new Promise((res, rej) => {
let bodyObj = { ...body }
let headerObj = {
'Content-Type': 'application/json',
...headers,
}
fetch(url, {
method: 'POST',
body: JSON.stringify({ ...bodyObj }),
headers: headerObj,
}).then(async (data) => {
if (headerObj['Content-Type'] == 'application/json') {
res(await data.json())
} else {
res(data)
}
}).catch(err => {
console.log('fetch err', err)
rej(err)
})
})
},
put(url, body={}, headers={}) {
if (url.slice(0, 4) != 'http') url = baseURL + `/api${url[0] == '/' ? '' : '/'}${url}`
return new Promise((res, rej) => {
let bodyObj = { ...body }
let headerObj = {
'Content-Type': 'application/json',
...headers,
}
fetch(url, {
method: 'PUT',
body: JSON.stringify({ ...bodyObj }),
headers: headerObj,
}).then(async (data) => {
if (headerObj['Content-Type'] == 'application/json') {
res(await data.json())
} else {
res(data)
}
}).catch(err => {
console.log('fetch err', err)
rej(err)
})
})
},
delete(url, obj={ params: {}, headers: {} }){
if (url.slice(0, 4) != 'http') url = baseURL + `/api${url[0] == '/' ? '' : '/'}${url}`
let params = objectToQueryString(obj.params)
if (params) url += `?${params}`
return new Promise((res, rej) => {
let headerObj = {
'Content-Type': 'application/json',
...obj.headers,
}
fetch(url, {
method: 'DELETE',
headers: headerObj,
}).then(async (data) => {
if (headerObj['Content-Type'] == 'application/json') {
res(await data.json())
} else {
res(data)
}
}).catch(err => {
console.log('fetch err', err)
rej(err)
})
})
},
get(url, obj={ params: {}, headers: {} }){
if (url.slice(0, 4) != 'http') url = baseURL + `/api${url[0] == '/' ? '' : '/'}${url}`
let params = objectToQueryString(obj.params)
if (params) url += `?${params}`
return new Promise((res, rej) => {
let headerObj = {
'Content-Type': 'application/json',
...obj.headers,
}
fetch(url, {
method: 'DELETE',
headers: headerObj,
}).then(async (data) => {
if (headerObj['Content-Type'] == 'application/json') {
res(await data.json())
} else {
res(data)
}
}).catch(err => {
console.log('fetch err', err)
rej(err)
})
})
},
objectToQueryString
}
} }
function onMessage(request, sender, sendResponse) { var api = createAPI(origin)
async function onMessage(request, sender, sendResponse) {
if (request.action === 'login') { if (request.action === 'login') {
console.log('B: to logged in', request.userDetails) console.log('B: to logged in', request.userDetails)
...@@ -49,8 +145,8 @@ var getUserDetails = null ...@@ -49,8 +145,8 @@ var getUserDetails = null
userDetails, userDetails,
tutorShotOid: tutorShotId, tutorShotOid: tutorShotId,
imageNumber: imageNumber, imageNumber: imageNumber,
status: tutorShotId?(recording?"recording":"paused"):"stopped", status: tutorShotId ? (recording ? "recording" : "paused") : "stopped",
}) })
sendMessageToActiveTab("loggedIn") sendMessageToActiveTab("loggedIn")
return return
...@@ -63,7 +159,7 @@ var getUserDetails = null ...@@ -63,7 +159,7 @@ var getUserDetails = null
recording, recording,
tutorShotOid: tutorShotId, tutorShotOid: tutorShotId,
imageNumber: imageNumber, imageNumber: imageNumber,
status: tutorShotId?(recording?"recording":"paused"):"stopped" status: tutorShotId ? (recording ? "recording" : "paused") : "stopped"
}) })
return return
} }
...@@ -76,7 +172,7 @@ var getUserDetails = null ...@@ -76,7 +172,7 @@ var getUserDetails = null
userDetails, userDetails,
loggedIn, loggedIn,
recording, recording,
status: tutorShotId?(recording?"recording":"paused"):"stopped" status: tutorShotId ? (recording ? "recording" : "paused") : "stopped"
}); });
sendMessageToActiveTab("recordingStarted") sendMessageToActiveTab("recordingStarted")
return return
...@@ -87,7 +183,7 @@ var getUserDetails = null ...@@ -87,7 +183,7 @@ var getUserDetails = null
userDetails, userDetails,
loggedIn, loggedIn,
recording, recording,
status: tutorShotId?(recording?"recording":"paused"):"stopped" status: tutorShotId ? (recording ? "recording" : "paused") : "stopped"
}); });
sendMessageToActiveTab("recordingPaused") sendMessageToActiveTab("recordingPaused")
return return
...@@ -98,7 +194,7 @@ var getUserDetails = null ...@@ -98,7 +194,7 @@ var getUserDetails = null
userDetails, userDetails,
loggedIn, loggedIn,
recording, recording,
status: tutorShotId?(recording?"recording":"paused"):"stopped" status: tutorShotId ? (recording ? "recording" : "paused") : "stopped"
}); });
sendMessageToActiveTab("recordingResumed") sendMessageToActiveTab("recordingResumed")
return return
...@@ -110,8 +206,10 @@ var getUserDetails = null ...@@ -110,8 +206,10 @@ var getUserDetails = null
userDetails, userDetails,
loggedIn, loggedIn,
recording, recording,
status: tutorShotId?(recording?"recording":"paused"):"stopped" status: tutorShotId ? (recording ? "recording" : "paused") : "stopped"
}); });
await api.post('/tutor-shot/finalize', { _id: tutorShotId }, { headers: { userid: userDetails.uid } })
sendMessageToActiveTab("recordingStopped") sendMessageToActiveTab("recordingStopped")
return return
} }
...@@ -121,7 +219,7 @@ var getUserDetails = null ...@@ -121,7 +219,7 @@ var getUserDetails = null
userDetails, userDetails,
loggedIn, loggedIn,
recording, recording,
status: tutorShotId?(recording?"recording":"paused"):"stopped" status: tutorShotId ? (recording ? "recording" : "paused") : "stopped"
}); });
sendMessageToActiveTab("recordingRestarted") sendMessageToActiveTab("recordingRestarted")
return return
...@@ -136,7 +234,7 @@ var getUserDetails = null ...@@ -136,7 +234,7 @@ var getUserDetails = null
console.log('recording not started for SS'); console.log('recording not started for SS');
return; return;
} }
if (!tutorShotId){ if (!tutorShotId) {
console.log('how to set not created'); console.log('how to set not created');
return return
} }
...@@ -149,14 +247,14 @@ var getUserDetails = null ...@@ -149,14 +247,14 @@ var getUserDetails = null
tutorShotOid: tutorShotId, tutorShotOid: tutorShotId,
action: 'SSCaptured', action: 'SSCaptured',
dataUrl: dataUrl, imageNumber: imageNumber++, dataUrl: dataUrl, imageNumber: imageNumber++,
status: tutorShotId?(recording?"recording":"paused"):"stopped", status: tutorShotId ? (recording ? "recording" : "paused") : "stopped",
...request.captureInfo ? request.captureInfo : {} ...request.captureInfo ? request.captureInfo : {}
} }
// to send message to the content instance of the // to send message to the content instance of the
chrome.tabs.sendMessage(activeTab.id, message); chrome.tabs.sendMessage(activeTab.id, message);
console.log('to take screenshot', message) console.log('to take screenshot', message)
let data = await sendReq('/tutor-shot/screen-shot', 'POST', message) let data = await api.post('/tutor-shot/screen-shot', message)
console.log('sent to server', data) console.log('sent SS to server', data)
}) })
} }
}) })
...@@ -178,23 +276,23 @@ var getUserDetails = null ...@@ -178,23 +276,23 @@ var getUserDetails = null
return dataSet return dataSet
} }
function sendMessageToActiveTab(messageObj){ function sendMessageToActiveTab(messageObj) {
try{ try {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) { chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
let activeTab = tabs[0] let activeTab = tabs[0]
if (activeTab?.url?.slice(0,6)!='chrome') { // if any tab is active if (activeTab?.url?.slice(0, 6) != 'chrome') { // if any tab is active
let message = { let message = {
userDetails, userDetails,
tutorShotOid: tutorShotId, tutorShotOid: tutorShotId,
imageNumber: imageNumber, imageNumber: imageNumber,
status: tutorShotId?(recording?"recording":"paused"):"stopped", status: tutorShotId ? (recording ? "recording" : "paused") : "stopped",
message: messageObj message: messageObj
} }
console.log('sending message:', message) console.log('sending message:', message)
chrome.tabs.sendMessage(activeTab.id, message); chrome.tabs.sendMessage(activeTab.id, message);
} }
}) })
}catch(err){ } catch (err) {
console.log(err) console.log(err)
} }
} }
......
...@@ -377,7 +377,8 @@ async function resumeRecording() { ...@@ -377,7 +377,8 @@ async function resumeRecording() {
async function stopRecording() { async function stopRecording() {
try { try {
await api.post('/tutor-shot/finalize', { _id: tutorShotOid }, { headers: { userid: userDetails.uid } }) console.log('to stop recording')
// await api.post('/tutor-shot/finalize', { _id: tutorShotOid }, { headers: { userid: userDetails.uid } })
await chrome.runtime.sendMessage({ action: "stopRecording" }) await chrome.runtime.sendMessage({ action: "stopRecording" })
} catch (err) { } catch (err) {
console.log(err) console.log(err)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment