Skip to content

Commit

Permalink
fix(webext): ensure that videos are correctly added when using contex…
Browse files Browse the repository at this point in the history
…tmenu actions
  • Loading branch information
AXeL-dev committed Sep 30, 2022
1 parent 1f25250 commit 3c68426
Show file tree
Hide file tree
Showing 8 changed files with 150 additions and 135 deletions.
46 changes: 1 addition & 45 deletions public/content.js
Original file line number Diff line number Diff line change
@@ -1,54 +1,10 @@
/* global browser, chrome */

(function () {
function getMeta(name) {
const query = document.querySelector('meta[itemprop="' + name + '"]');
return query ? query.content : undefined;
}

function getVideoId(url) {
let videoId = null;
if (url.indexOf('v=') !== -1) {
/**
* Example:
* https://www.youtube.com/watch?v=aZ-dSpfdHok
* https://www.youtube.com/watch?v=aZ-dSpfdHok&feature=feedrec_grec_index
*/
videoId = url.split('v=')[1];
const index = videoId.indexOf('&');
if (index !== -1) {
videoId = videoId.substring(0, index);
}
} else if (url.indexOf('/') !== -1) {
/**
* Example:
* https://youtu.be/aZ-dSpfdHok
* https://youtu.be/PqkaBUmJpq8?list=PLmmPGQQTKzSZSPd3pa6q9UQ-PkeCx1fam
*/
const link = url.split('?')[0];
const params = link.split('/');
videoId = params[params.length - 1];
}
return videoId;
}

function handleMessage(request, sender) {
switch (request.message) {
case 'getVideoInfos': {
const videoId = getMeta('videoId') || getVideoId(window.location.href);
const channelId = getMeta('channelId');
const datePublished = getMeta('datePublished');
port.postMessage({
request,
response: {
videoId,
channelId,
datePublished,
},
});
break;
}
default:
// ToDo: add commands to control the youtube player (play/stop video, update video link, etc...)
break;
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/helpers/webext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@ export async function closeTabs(resolver: TabResolver) {
return closedTabs;
}

export function closeExtensionTabs() {
return closeTabs((tab) => tab.url.startsWith(indexUrl));
}

export function getUrl(path: string): string {
return browser.runtime.getURL(path);
}
Expand Down
23 changes: 19 additions & 4 deletions src/store/reducers/videos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ const initialState: VideosState = {
list: [],
};

interface AddVideoParams {
interface PersistVideoParams {
state: VideosState;
video: AddVideoPayload;
flags: VideoFlags;
}

function addVideo({ state, video, flags }: AddVideoParams) {
function persistVideo({ state, video, flags }: PersistVideoParams) {
const found = setVideoFlags({
state,
video,
Expand Down Expand Up @@ -68,6 +68,20 @@ export const videosSlice = createSlice({
...action.payload,
};
},
addVideo: (
state,
action: PayloadAction<{
video: AddVideoPayload;
flags?: VideoFlags;
}>,
) => {
const { video, flags = {} } = action.payload;
persistVideo({
state,
video,
flags,
});
},
addVideoFlag: (
state,
action: PayloadAction<{
Expand All @@ -76,7 +90,7 @@ export const videosSlice = createSlice({
}>,
) => {
const { video, flag } = action.payload;
addVideo({
persistVideo({
state,
video,
flags: { [flag]: true },
Expand Down Expand Up @@ -179,7 +193,7 @@ export const videosSlice = createSlice({
) => {
const { videos, flags } = action.payload;
for (const video of videos) {
addVideo({
persistVideo({
state,
video,
flags,
Expand All @@ -191,6 +205,7 @@ export const videosSlice = createSlice({

export const {
setVideos,
addVideo,
addVideoFlag,
removeVideoFlag,
clearWatchLaterList,
Expand Down
2 changes: 1 addition & 1 deletion src/store/services/youtube/endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ type GetChannelActivitiesResponse = {
total: number;
};

type GetVideosByIdArgs = {
export type GetVideosByIdArgs = {
ids: string[];
maxResults?: number;
};
Expand Down
36 changes: 23 additions & 13 deletions src/store/thunks.ts → src/store/thunks/channels.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,41 @@
import { createAsyncThunk } from '@reduxjs/toolkit';
import { RootState } from 'store';
import { Channel } from 'types';
import { addChannel } from './reducers/channels';
import { extendedApi } from './services/youtube';
import { addChannel } from '../reducers/channels';
import { extendedApi } from '../services/youtube';

export const fetchChannelById = createAsyncThunk<
Channel | undefined,
{ id: string },
{ state: RootState }
>('channels/fetchChannelById', async ({ id }, { getState, dispatch }) => {
const { channels } = getState();
// check for existing channel
const found = channels.list.find((channel: Channel) => channel.id === id);
if (found) {
return found;
}

// fetch channel by id
>('channels/fetchChannelById', async ({ id }, { dispatch }) => {
const result = dispatch(
extendedApi.endpoints.findChannelById.initiate({ id }),
);
result.unsubscribe();
const response = await result;
const channel = response.data?.items[0];

return channel;
});

export const addChannelById = createAsyncThunk<
void,
{ id: string },
{ state: RootState }
>('channels/addChannelById', async ({ id }, { getState, dispatch }) => {
// check if channel exists
const { channels } = getState();
const found = channels.list.find((channel: Channel) => channel.id === id);
if (found) {
return;
}

// fetch channel by id
const channel = await dispatch(fetchChannelById({ id })).unwrap();

// save to channels list
if (channel) {
// save to channels list
dispatch(addChannel(channel));
}
return channel;
});
53 changes: 53 additions & 0 deletions src/store/thunks/videos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { createAsyncThunk } from '@reduxjs/toolkit';
import { RootState } from 'store';
import { Video, VideoCache, VideoFlags } from 'types';
import { addVideo } from '../reducers/videos';
import { extendedApi, GetVideosByIdArgs } from '../services/youtube';
import { addChannelById } from './channels';

export const fetchVideosById = createAsyncThunk<
Video[],
GetVideosByIdArgs,
{ state: RootState }
>('videos/fetchVideosById', async (payload, { dispatch }) => {
const result = dispatch(
extendedApi.endpoints.getVideosById.initiate(payload),
);
result.unsubscribe();
const response = await result;
const videos = response.data?.items || [];

return videos;
});

export const addVideoById = createAsyncThunk<
void,
{ id: string; flags?: VideoFlags },
{ state: RootState }
>('videos/addVideoById', async ({ id, flags }, { getState, dispatch }) => {
// check if video exists
const { videos } = getState();
let video: Video | VideoCache | undefined = videos.list.find(
(video) => video.id === id,
);

if (!video) {
// fetch video by id
const result = await dispatch(
fetchVideosById({ ids: [id], maxResults: 1 }),
).unwrap();
video = result[0];
}

// save to videos list
if (video) {
dispatch(
addVideo({
video,
flags,
}),
);
// ensure to add channel too (if it does not exist)
dispatch(addChannelById({ id: video.channelId }));
}
});
5 changes: 5 additions & 0 deletions src/types/webext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ export interface ContextMenu {
contexts: Context[];
}

export interface ContextMenuInfo {
menuItemId: string;
checked: boolean;
}

export interface Tab {
id: number;
url: string;
Expand Down
Loading

0 comments on commit 3c68426

Please sign in to comment.